MDL-57696 mod_lesson: Remove redirects from API
[moodle.git] / mod / lesson / locallib.php
blob0d46715b6367ff4844dffe5b8b5f43a34d3cf662
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Local library file for Lesson. These are non-standard functions that are used
20 * only by Lesson.
22 * @package mod_lesson
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
25 **/
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');
35 /** This page */
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);
43 /** End of Lesson */
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);
53 /** Cluster Jump */
54 define("LESSON_CLUSTERJUMP", -80);
55 /** Undefined */
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_
68 /**
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.
77 **/
78 function lesson_display_teacher_warning($lesson) {
79 global $DB;
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
85 return false;
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) {
90 return true;
94 // if no answers use either of the two jumps
95 return false;
98 /**
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) {
109 global $DB;
111 // get the number of retakes
112 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
113 $retakes = 0;
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;
121 } else {
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) {
135 break;
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
143 $unseen = 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
154 } else {
155 // there are no pages inside the branch, so return the next page
156 $nextpage = $lessonpages[$pageid]->nextpageid;
158 if ($nextpage == 0) {
159 return LESSON_EOL;
160 } else {
161 return $nextpage;
163 } else {
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) {
176 global $DB;
178 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
179 $retakes = 0;
182 if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
183 print_error('cannotfindrecords', 'lesson');
186 // get the lesson pages
187 $lessonpages = $lesson->load_all_pages();
189 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
190 // which is the branch table that starts the unseenbranch function
191 $seen = array();
192 foreach ($seenbranches as $seenbranch) {
193 if (!$seenbranch->flag) {
194 $seen[$seenbranch->pageid] = $seenbranch->pageid;
195 } else {
196 $start = $seenbranch->pageid;
197 break;
200 // this function searches through the lesson pages to find all the branch tables
201 // that follow the flagged branch table
202 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
203 $branchtables = array();
204 while ($pageid != 0) { // grab all of the branch table till eol
205 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
206 $branchtables[] = $lessonpages[$pageid]->id;
208 $pageid = $lessonpages[$pageid]->nextpageid;
210 $unseen = array();
211 foreach ($branchtables as $branchtable) {
212 // load all of the unseen branch tables into unseen
213 if (!array_key_exists($branchtable, $seen)) {
214 $unseen[] = $branchtable;
217 if (count($unseen) > 0) {
218 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
219 } else {
220 return LESSON_EOL; // has viewed all of the branch tables
225 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
227 * @param lesson $lesson
228 * @param int $pageid The id of the page that we are jumping from (?)
229 * @return int The pageid of a random page that is within a branch table
231 function lesson_random_question_jump($lesson, $pageid) {
232 global $DB;
234 // get the lesson pages
235 $params = array ("lessonid" => $lesson->id);
236 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
237 print_error('cannotfindpages', 'lesson');
240 // go up the pages till branch table
241 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
243 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
244 break;
246 $pageid = $lessonpages[$pageid]->prevpageid;
249 // get the pages within the branch
250 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
252 if(count($pagesinbranch) == 0) {
253 // there are no pages inside the branch, so return the next page
254 return $lessonpages[$pageid]->nextpageid;
255 } else {
256 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
261 * Calculates a user's grade for a lesson.
263 * @param object $lesson The lesson that the user is taking.
264 * @param int $retries The attempt number.
265 * @param int $userid Id of the user (optional, default current user).
266 * @return object { nquestions => number of questions answered
267 attempts => number of question attempts
268 total => max points possible
269 earned => points earned by student
270 grade => calculated percentage grade
271 nmanual => number of manually graded questions
272 manualpoints => point value for manually graded questions }
274 function lesson_grade($lesson, $ntries, $userid = 0) {
275 global $USER, $DB;
277 if (empty($userid)) {
278 $userid = $USER->id;
281 // Zero out everything
282 $ncorrect = 0;
283 $nviewed = 0;
284 $score = 0;
285 $nmanual = 0;
286 $manualpoints = 0;
287 $thegrade = 0;
288 $nquestions = 0;
289 $total = 0;
290 $earned = 0;
292 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
293 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
294 userid = :userid AND retry = :retry", $params, "timeseen")) {
295 // group each try with its page
296 $attemptset = array();
297 foreach ($useranswers as $useranswer) {
298 $attemptset[$useranswer->pageid][] = $useranswer;
301 // Drop all attempts that go beyond max attempts for the lesson
302 foreach ($attemptset as $key => $set) {
303 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
306 // get only the pages and their answers that the user answered
307 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
308 array_unshift($parameters, $lesson->id);
309 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
310 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
312 // Number of pages answered
313 $nquestions = count($pages);
315 foreach ($attemptset as $attempts) {
316 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
317 if ($lesson->custom) {
318 $attempt = end($attempts);
319 // If essay question, handle it, otherwise add to score
320 if ($page->requires_manual_grading()) {
321 $useranswerobj = unserialize($attempt->useranswer);
322 if (isset($useranswerobj->score)) {
323 $earned += $useranswerobj->score;
325 $nmanual++;
326 $manualpoints += $answers[$attempt->answerid]->score;
327 } else if (!empty($attempt->answerid)) {
328 $earned += $page->earned_score($answers, $attempt);
330 } else {
331 foreach ($attempts as $attempt) {
332 $earned += $attempt->correct;
334 $attempt = end($attempts); // doesn't matter which one
335 // If essay question, increase numbers
336 if ($page->requires_manual_grading()) {
337 $nmanual++;
338 $manualpoints++;
341 // Number of times answered
342 $nviewed += count($attempts);
345 if ($lesson->custom) {
346 $bestscores = array();
347 // Find the highest possible score per page to get our total
348 foreach ($answers as $answer) {
349 if(!isset($bestscores[$answer->pageid])) {
350 $bestscores[$answer->pageid] = $answer->score;
351 } else if ($bestscores[$answer->pageid] < $answer->score) {
352 $bestscores[$answer->pageid] = $answer->score;
355 $total = array_sum($bestscores);
356 } else {
357 // Check to make sure the student has answered the minimum questions
358 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
359 // Nope, increase number viewed by the amount of unanswered questions
360 $total = $nviewed + ($lesson->minquestions - $nquestions);
361 } else {
362 $total = $nviewed;
367 if ($total) { // not zero
368 $thegrade = round(100 * $earned / $total, 5);
371 // Build the grade information object
372 $gradeinfo = new stdClass;
373 $gradeinfo->nquestions = $nquestions;
374 $gradeinfo->attempts = $nviewed;
375 $gradeinfo->total = $total;
376 $gradeinfo->earned = $earned;
377 $gradeinfo->grade = $thegrade;
378 $gradeinfo->nmanual = $nmanual;
379 $gradeinfo->manualpoints = $manualpoints;
381 return $gradeinfo;
385 * Determines if a user can view the left menu. The determining factor
386 * is whether a user has a grade greater than or equal to the lesson setting
387 * of displayleftif
389 * @param object $lesson Lesson object of the current lesson
390 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
392 function lesson_displayleftif($lesson) {
393 global $CFG, $USER, $DB;
395 if (!empty($lesson->displayleftif)) {
396 // get the current user's max grade for this lesson
397 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
398 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)) {
399 if ($maxgrade->maxgrade < $lesson->displayleftif) {
400 return 0; // turn off the displayleft
402 } else {
403 return 0; // no grades
407 // if we get to here, keep the original state of displayleft lesson setting
408 return $lesson->displayleft;
413 * @param $cm
414 * @param $lesson
415 * @param $page
416 * @return unknown_type
418 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
419 $bc = lesson_menu_block_contents($cm->id, $lesson);
420 if (!empty($bc)) {
421 $regions = $page->blocks->get_regions();
422 $firstregion = reset($regions);
423 $page->blocks->add_fake_block($bc, $firstregion);
426 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
427 if (!empty($bc)) {
428 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
431 if (!empty($timer)) {
432 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
433 if (!empty($bc)) {
434 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
440 * If there is a media file associated with this
441 * lesson, return a block_contents that displays it.
443 * @param int $cmid Course Module ID for this lesson
444 * @param object $lesson Full lesson record object
445 * @return block_contents
447 function lesson_mediafile_block_contents($cmid, $lesson) {
448 global $OUTPUT;
449 if (empty($lesson->mediafile)) {
450 return null;
453 $options = array();
454 $options['menubar'] = 0;
455 $options['location'] = 0;
456 $options['left'] = 5;
457 $options['top'] = 5;
458 $options['scrollbars'] = 1;
459 $options['resizable'] = 1;
460 $options['width'] = $lesson->mediawidth;
461 $options['height'] = $lesson->mediaheight;
463 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
464 $action = new popup_action('click', $link, 'lessonmediafile', $options);
465 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
467 $bc = new block_contents();
468 $bc->title = get_string('linkedmedia', 'lesson');
469 $bc->attributes['class'] = 'mediafile block';
470 $bc->content = $content;
472 return $bc;
476 * If a timed lesson and not a teacher, then
477 * return a block_contents containing the clock.
479 * @param int $cmid Course Module ID for this lesson
480 * @param object $lesson Full lesson record object
481 * @param object $timer Full timer record object
482 * @return block_contents
484 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
485 // Display for timed lessons and for students only
486 $context = context_module::instance($cmid);
487 if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
488 return null;
491 $content = '<div id="lesson-timer">';
492 $content .= $lesson->time_remaining($timer->starttime);
493 $content .= '</div>';
495 $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
496 $page->requires->data_for_js('clocksettings', $clocksettings, true);
497 $page->requires->strings_for_js(array('timeisup'), 'lesson');
498 $page->requires->js('/mod/lesson/timer.js');
499 $page->requires->js_init_call('show_clock');
501 $bc = new block_contents();
502 $bc->title = get_string('timeremaining', 'lesson');
503 $bc->attributes['class'] = 'clock block';
504 $bc->content = $content;
506 return $bc;
510 * If left menu is turned on, then this will
511 * print the menu in a block
513 * @param int $cmid Course Module ID for this lesson
514 * @param lesson $lesson Full lesson record object
515 * @return void
517 function lesson_menu_block_contents($cmid, $lesson) {
518 global $CFG, $DB;
520 if (!$lesson->displayleft) {
521 return null;
524 $pages = $lesson->load_all_pages();
525 foreach ($pages as $page) {
526 if ((int)$page->prevpageid === 0) {
527 $pageid = $page->id;
528 break;
531 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
533 if (!$pageid || !$pages) {
534 return null;
537 $content = '<a href="#maincontent" class="accesshide">' .
538 get_string('skip', 'lesson') .
539 "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
541 while ($pageid != 0) {
542 $page = $pages[$pageid];
544 // Only process branch tables with display turned on
545 if ($page->displayinmenublock && $page->display) {
546 if ($page->id == $currentpageid) {
547 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
548 } else {
549 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&amp;pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
553 $pageid = $page->nextpageid;
555 $content .= "</ul>\n</div>\n";
557 $bc = new block_contents();
558 $bc->title = get_string('lessonmenu', 'lesson');
559 $bc->attributes['class'] = 'menu block';
560 $bc->content = $content;
562 return $bc;
566 * Adds header buttons to the page for the lesson
568 * @param object $cm
569 * @param object $context
570 * @param bool $extraeditbuttons
571 * @param int $lessonpageid
573 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
574 global $CFG, $PAGE, $OUTPUT;
575 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
576 if ($lessonpageid === null) {
577 print_error('invalidpageid', 'lesson');
579 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
580 $url = new moodle_url('/mod/lesson/editpage.php', array(
581 'id' => $cm->id,
582 'pageid' => $lessonpageid,
583 'edit' => 1,
584 'returnto' => $PAGE->url->out(false)
586 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
592 * This is a function used to detect media types and generate html code.
594 * @global object $CFG
595 * @global object $PAGE
596 * @param object $lesson
597 * @param object $context
598 * @return string $code the html code of media
600 function lesson_get_media_html($lesson, $context) {
601 global $CFG, $PAGE, $OUTPUT;
602 require_once("$CFG->libdir/resourcelib.php");
604 // get the media file link
605 if (strpos($lesson->mediafile, '://') !== false) {
606 $url = new moodle_url($lesson->mediafile);
607 } else {
608 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
609 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
611 $title = $lesson->mediafile;
613 $clicktoopen = html_writer::link($url, get_string('download'));
615 $mimetype = resourcelib_guess_url_mimetype($url);
617 $extension = resourcelib_get_extension($url->out(false));
619 $mediamanager = core_media_manager::instance($PAGE);
620 $embedoptions = array(
621 core_media_manager::OPTION_TRUSTED => true,
622 core_media_manager::OPTION_BLOCK => true
625 // find the correct type and print it out
626 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
627 $code = resourcelib_embed_image($url, $title);
629 } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
630 // Media (audio/video) file.
631 $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
633 } else {
634 // anything else - just try object tag enlarged as much as possible
635 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
638 return $code;
642 * Logic to happen when a/some group(s) has/have been deleted in a course.
644 * @param int $courseid The course ID.
645 * @param int $groupid The group id if it is known
646 * @return void
648 function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
649 global $DB;
651 $params = array('courseid' => $courseid);
652 if ($groupid) {
653 $params['groupid'] = $groupid;
654 // We just update the group that was deleted.
655 $sql = "SELECT o.id, o.lessonid
656 FROM {lesson_overrides} o
657 JOIN {lesson} lesson ON lesson.id = o.lessonid
658 WHERE lesson.course = :courseid
659 AND o.groupid = :groupid";
660 } else {
661 // No groupid, we update all orphaned group overrides for all lessons in course.
662 $sql = "SELECT o.id, o.lessonid
663 FROM {lesson_overrides} o
664 JOIN {lesson} lesson ON lesson.id = o.lessonid
665 LEFT JOIN {groups} grp ON grp.id = o.groupid
666 WHERE lesson.course = :courseid
667 AND o.groupid IS NOT NULL
668 AND grp.id IS NULL";
670 $records = $DB->get_records_sql_menu($sql, $params);
671 if (!$records) {
672 return; // Nothing to do.
674 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
678 * Abstract class that page type's MUST inherit from.
680 * This is the abstract class that ALL add page type forms must extend.
681 * You will notice that all but two of the methods this class contains are final.
682 * Essentially the only thing that extending classes can do is extend custom_definition.
683 * OR if it has a special requirement on creation it can extend construction_override
685 * @abstract
686 * @copyright 2009 Sam Hemelryk
687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
689 abstract class lesson_add_page_form_base extends moodleform {
692 * This is the classic define that is used to identify this pagetype.
693 * Will be one of LESSON_*
694 * @var int
696 public $qtype;
699 * The simple string that describes the page type e.g. truefalse, multichoice
700 * @var string
702 public $qtypestring;
705 * An array of options used in the htmleditor
706 * @var array
708 protected $editoroptions = array();
711 * True if this is a standard page of false if it does something special.
712 * Questions are standard pages, branch tables are not
713 * @var bool
715 protected $standard = true;
718 * Answer format supported by question type.
720 protected $answerformat = '';
723 * Response format supported by question type.
725 protected $responseformat = '';
728 * Each page type can and should override this to add any custom elements to
729 * the basic form that they want
731 public function custom_definition() {}
734 * Returns answer format used by question type.
736 public function get_answer_format() {
737 return $this->answerformat;
741 * Returns response format used by question type.
743 public function get_response_format() {
744 return $this->responseformat;
748 * Used to determine if this is a standard page or a special page
749 * @return bool
751 public final function is_standard() {
752 return (bool)$this->standard;
756 * Add the required basic elements to the form.
758 * This method adds the basic elements to the form including title and contents
759 * and then calls custom_definition();
761 public final function definition() {
762 $mform = $this->_form;
763 $editoroptions = $this->_customdata['editoroptions'];
765 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
767 if (!empty($this->_customdata['returnto'])) {
768 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
769 $mform->setType('returnto', PARAM_URL);
772 $mform->addElement('hidden', 'id');
773 $mform->setType('id', PARAM_INT);
775 $mform->addElement('hidden', 'pageid');
776 $mform->setType('pageid', PARAM_INT);
778 if ($this->standard === true) {
779 $mform->addElement('hidden', 'qtype');
780 $mform->setType('qtype', PARAM_INT);
782 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
783 $mform->setType('title', PARAM_TEXT);
784 $mform->addRule('title', get_string('required'), 'required', null, 'client');
786 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
787 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
788 $mform->setType('contents_editor', PARAM_RAW);
789 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
792 $this->custom_definition();
794 if ($this->_customdata['edit'] === true) {
795 $mform->addElement('hidden', 'edit', 1);
796 $mform->setType('edit', PARAM_BOOL);
797 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
798 } else if ($this->qtype === 'questiontype') {
799 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
800 } else {
801 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
806 * Convenience function: Adds a jumpto select element
808 * @param string $name
809 * @param string|null $label
810 * @param int $selected The page to select by default
812 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
813 $title = get_string("jump", "lesson");
814 if ($label === null) {
815 $label = $title;
817 if (is_int($name)) {
818 $name = "jumpto[$name]";
820 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
821 $this->_form->setDefault($name, $selected);
822 $this->_form->addHelpButton($name, 'jumps', 'lesson');
826 * Convenience function: Adds a score input element
828 * @param string $name
829 * @param string|null $label
830 * @param mixed $value The default value
832 protected final function add_score($name, $label=null, $value=null) {
833 if ($label === null) {
834 $label = get_string("score", "lesson");
837 if (is_int($name)) {
838 $name = "score[$name]";
840 $this->_form->addElement('text', $name, $label, array('size'=>5));
841 $this->_form->setType($name, PARAM_INT);
842 if ($value !== null) {
843 $this->_form->setDefault($name, $value);
845 $this->_form->addHelpButton($name, 'score', 'lesson');
847 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
848 if (!$this->_customdata['lesson']->custom) {
849 $this->_form->freeze($name);
854 * Convenience function: Adds an answer editor
856 * @param int $count The count of the element to add
857 * @param string $label, null means default
858 * @param bool $required
859 * @param string $format
860 * @return void
862 protected final function add_answer($count, $label = null, $required = false, $format= '') {
863 if ($label === null) {
864 $label = get_string('answer', 'lesson');
867 if ($format == LESSON_ANSWER_HTML) {
868 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
869 array('rows' => '4', 'columns' => '80'),
870 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
871 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
872 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
873 } else {
874 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
875 array('size' => '50', 'maxlength' => '200'));
876 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
879 if ($required) {
880 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
884 * Convenience function: Adds an response editor
886 * @param int $count The count of the element to add
887 * @param string $label, null means default
888 * @param bool $required
889 * @return void
891 protected final function add_response($count, $label = null, $required = false) {
892 if ($label === null) {
893 $label = get_string('response', 'lesson');
895 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
896 array('rows' => '4', 'columns' => '80'),
897 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
898 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
899 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
901 if ($required) {
902 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
907 * A function that gets called upon init of this object by the calling script.
909 * This can be used to process an immediate action if required. Currently it
910 * is only used in special cases by non-standard page types.
912 * @return bool
914 public function construction_override($pageid, lesson $lesson) {
915 return true;
922 * Class representation of a lesson
924 * This class is used the interact with, and manage a lesson once instantiated.
925 * If you need to fetch a lesson object you can do so by calling
927 * <code>
928 * lesson::load($lessonid);
929 * // or
930 * $lessonrecord = $DB->get_record('lesson', $lessonid);
931 * $lesson = new lesson($lessonrecord);
932 * </code>
934 * The class itself extends lesson_base as all classes within the lesson module should
936 * These properties are from the database
937 * @property int $id The id of this lesson
938 * @property int $course The ID of the course this lesson belongs to
939 * @property string $name The name of this lesson
940 * @property int $practice Flag to toggle this as a practice lesson
941 * @property int $modattempts Toggle to allow the user to go back and review answers
942 * @property int $usepassword Toggle the use of a password for entry
943 * @property string $password The password to require users to enter
944 * @property int $dependency ID of another lesson this lesson is dependent on
945 * @property string $conditions Conditions of the lesson dependency
946 * @property int $grade The maximum grade a user can achieve (%)
947 * @property int $custom Toggle custom scoring on or off
948 * @property int $ongoing Toggle display of an ongoing score
949 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
950 * @property int $maxanswers The max number of answers or branches
951 * @property int $maxattempts The maximum number of attempts a user can record
952 * @property int $review Toggle use or wrong answer review button
953 * @property int $nextpagedefault Override the default next page
954 * @property int $feedback Toggles display of default feedback
955 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
956 * @property int $maxpages Maximum number of pages this lesson can contain
957 * @property int $retake Flag to allow users to retake a lesson
958 * @property int $activitylink Relate this lesson to another lesson
959 * @property string $mediafile File to pop up to or webpage to display
960 * @property int $mediaheight Sets the height of the media file popup
961 * @property int $mediawidth Sets the width of the media file popup
962 * @property int $mediaclose Toggle display of a media close button
963 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
964 * @property int $width Width of slideshow
965 * @property int $height Height of slideshow
966 * @property string $bgcolor Background colour of slideshow
967 * @property int $displayleft Display a left menu
968 * @property int $displayleftif Sets the condition on which the left menu is displayed
969 * @property int $progressbar Flag to toggle display of a lesson progress bar
970 * @property int $available Timestamp of when this lesson becomes available
971 * @property int $deadline Timestamp of when this lesson is no longer available
972 * @property int $timemodified Timestamp when lesson was last modified
974 * These properties are calculated
975 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
976 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
978 * @copyright 2009 Sam Hemelryk
979 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
981 class lesson extends lesson_base {
984 * The id of the first page (where prevpageid = 0) gets set and retrieved by
985 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
986 * @var int
988 protected $firstpageid = null;
990 * The id of the last page (where nextpageid = 0) gets set and retrieved by
991 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
992 * @var int
994 protected $lastpageid = null;
996 * An array used to cache the pages associated with this lesson after the first
997 * time they have been loaded.
998 * A note to developers: If you are going to be working with MORE than one or
999 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1000 * in order to save excess database queries.
1001 * @var array An array of lesson_page objects
1003 protected $pages = array();
1005 * Flag that gets set to true once all of the pages associated with the lesson
1006 * have been loaded.
1007 * @var bool
1009 protected $loadedallpages = false;
1012 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1013 * @see get_cm()
1014 * @var stdClass
1016 protected $cm = null;
1019 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1020 * @see get_courserecord()
1021 * @var stdClass
1023 protected $courserecord = null;
1026 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1027 * @see get_context()
1028 * @var stdClass
1030 protected $context = null;
1033 * Constructor method
1035 * @param object $properties
1036 * @param stdClass $cm course module object
1037 * @param stdClass $course course object
1038 * @since Moodle 3.3
1040 public function __construct($properties, $cm = null, $course = null) {
1041 parent::__construct($properties);
1042 $this->cm = $cm;
1043 $this->courserecord = $course;
1047 * Simply generates a lesson object given an array/object of properties
1048 * Overrides {@see lesson_base->create()}
1049 * @static
1050 * @param object|array $properties
1051 * @return lesson
1053 public static function create($properties) {
1054 return new lesson($properties);
1058 * Generates a lesson object from the database given its id
1059 * @static
1060 * @param int $lessonid
1061 * @return lesson
1063 public static function load($lessonid) {
1064 global $DB;
1066 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1067 print_error('invalidcoursemodule');
1069 return new lesson($lesson);
1073 * Deletes this lesson from the database
1075 public function delete() {
1076 global $CFG, $DB;
1077 require_once($CFG->libdir.'/gradelib.php');
1078 require_once($CFG->dirroot.'/calendar/lib.php');
1080 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1081 $context = context_module::instance($cm->id);
1083 $this->delete_all_overrides();
1085 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1086 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1087 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1088 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1089 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1090 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1091 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1092 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1093 foreach($events as $event) {
1094 $event = calendar_event::load($event);
1095 $event->delete();
1099 // Delete files associated with this module.
1100 $fs = get_file_storage();
1101 $fs->delete_area_files($context->id);
1103 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1104 return true;
1108 * Deletes a lesson override from the database and clears any corresponding calendar events
1110 * @param int $overrideid The id of the override being deleted
1111 * @return bool true on success
1113 public function delete_override($overrideid) {
1114 global $CFG, $DB;
1116 require_once($CFG->dirroot . '/calendar/lib.php');
1118 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1120 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1122 // Delete the events.
1123 $conds = array('modulename' => 'lesson',
1124 'instance' => $this->properties->id);
1125 if (isset($override->userid)) {
1126 $conds['userid'] = $override->userid;
1127 } else {
1128 $conds['groupid'] = $override->groupid;
1130 $events = $DB->get_records('event', $conds);
1131 foreach ($events as $event) {
1132 $eventold = calendar_event::load($event);
1133 $eventold->delete();
1136 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1138 // Set the common parameters for one of the events we will be triggering.
1139 $params = array(
1140 'objectid' => $override->id,
1141 'context' => context_module::instance($cm->id),
1142 'other' => array(
1143 'lessonid' => $override->lessonid
1146 // Determine which override deleted event to fire.
1147 if (!empty($override->userid)) {
1148 $params['relateduserid'] = $override->userid;
1149 $event = \mod_lesson\event\user_override_deleted::create($params);
1150 } else {
1151 $params['other']['groupid'] = $override->groupid;
1152 $event = \mod_lesson\event\group_override_deleted::create($params);
1155 // Trigger the override deleted event.
1156 $event->add_record_snapshot('lesson_overrides', $override);
1157 $event->trigger();
1159 return true;
1163 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1165 public function delete_all_overrides() {
1166 global $DB;
1168 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1169 foreach ($overrides as $override) {
1170 $this->delete_override($override->id);
1175 * Updates the lesson properties with override information for a user.
1177 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1178 * then use that otherwise, if there are group-specific overrides, return the most
1179 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1181 * Special case: if there is more than one password that applies to the user, then
1182 * lesson->extrapasswords will contain an array of strings giving the remaining
1183 * passwords.
1185 * @param int $userid The userid.
1187 public function update_effective_access($userid) {
1188 global $DB;
1190 // Check for user override.
1191 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1193 if (!$override) {
1194 $override = new stdClass();
1195 $override->available = null;
1196 $override->deadline = null;
1197 $override->timelimit = null;
1198 $override->review = null;
1199 $override->maxattempts = null;
1200 $override->retake = null;
1201 $override->password = null;
1204 // Check for group overrides.
1205 $groupings = groups_get_user_groups($this->properties->course, $userid);
1207 if (!empty($groupings[0])) {
1208 // Select all overrides that apply to the User's groups.
1209 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1210 $sql = "SELECT * FROM {lesson_overrides}
1211 WHERE groupid $extra AND lessonid = ?";
1212 $params[] = $this->properties->id;
1213 $records = $DB->get_records_sql($sql, $params);
1215 // Combine the overrides.
1216 $availables = array();
1217 $deadlines = array();
1218 $timelimits = array();
1219 $reviews = array();
1220 $attempts = array();
1221 $retakes = array();
1222 $passwords = array();
1224 foreach ($records as $gpoverride) {
1225 if (isset($gpoverride->available)) {
1226 $availables[] = $gpoverride->available;
1228 if (isset($gpoverride->deadline)) {
1229 $deadlines[] = $gpoverride->deadline;
1231 if (isset($gpoverride->timelimit)) {
1232 $timelimits[] = $gpoverride->timelimit;
1234 if (isset($gpoverride->review)) {
1235 $reviews[] = $gpoverride->review;
1237 if (isset($gpoverride->maxattempts)) {
1238 $attempts[] = $gpoverride->maxattempts;
1240 if (isset($gpoverride->retake)) {
1241 $retakes[] = $gpoverride->retake;
1243 if (isset($gpoverride->password)) {
1244 $passwords[] = $gpoverride->password;
1247 // If there is a user override for a setting, ignore the group override.
1248 if (is_null($override->available) && count($availables)) {
1249 $override->available = min($availables);
1251 if (is_null($override->deadline) && count($deadlines)) {
1252 if (in_array(0, $deadlines)) {
1253 $override->deadline = 0;
1254 } else {
1255 $override->deadline = max($deadlines);
1258 if (is_null($override->timelimit) && count($timelimits)) {
1259 if (in_array(0, $timelimits)) {
1260 $override->timelimit = 0;
1261 } else {
1262 $override->timelimit = max($timelimits);
1265 if (is_null($override->review) && count($reviews)) {
1266 $override->review = max($reviews);
1268 if (is_null($override->maxattempts) && count($attempts)) {
1269 $override->maxattempts = max($attempts);
1271 if (is_null($override->retake) && count($retakes)) {
1272 $override->retake = max($retakes);
1274 if (is_null($override->password) && count($passwords)) {
1275 $override->password = array_shift($passwords);
1276 if (count($passwords)) {
1277 $override->extrapasswords = $passwords;
1283 // Merge with lesson defaults.
1284 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1285 foreach ($keys as $key) {
1286 if (isset($override->{$key})) {
1287 $this->properties->{$key} = $override->{$key};
1291 // Special handling of lesson usepassword and password.
1292 if (isset($override->password)) {
1293 if ($override->password == '') {
1294 $this->properties->usepassword = 0;
1295 } else {
1296 $this->properties->usepassword = 1;
1297 $this->properties->password = $override->password;
1298 if (isset($override->extrapasswords)) {
1299 $this->properties->extrapasswords = $override->extrapasswords;
1306 * Fetches messages from the session that may have been set in previous page
1307 * actions.
1309 * <code>
1310 * // Do not call this method directly instead use
1311 * $lesson->messages;
1312 * </code>
1314 * @return array
1316 protected function get_messages() {
1317 global $SESSION;
1319 $messages = array();
1320 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1321 $messages = $SESSION->lesson_messages[$this->properties->id];
1322 unset($SESSION->lesson_messages[$this->properties->id]);
1325 return $messages;
1329 * Get all of the attempts for the current user.
1331 * @param int $retries
1332 * @param bool $correct Optional: only fetch correct attempts
1333 * @param int $pageid Optional: only fetch attempts at the given page
1334 * @param int $userid Optional: defaults to the current user if not set
1335 * @return array|false
1337 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1338 global $USER, $DB;
1339 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1340 if ($correct) {
1341 $params['correct'] = 1;
1343 if ($pageid !== null) {
1344 $params['pageid'] = $pageid;
1346 if ($userid === null) {
1347 $params['userid'] = $USER->id;
1349 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1354 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1356 * @param int $lessonattempt the lesson attempt number (also known as retries)
1357 * @param int $userid the user id to retrieve the data from
1358 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter)
1359 * @param string $fields a comma separated list of fields to return
1360 * @return array of pages
1361 * @since Moodle 3.3
1363 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1364 global $USER, $DB;
1366 if ($userid === null) {
1367 $userid = $USER->id;
1369 $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
1370 return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1374 * Returns the first page for the lesson or false if there isn't one.
1376 * This method should be called via the magic method __get();
1377 * <code>
1378 * $firstpage = $lesson->firstpage;
1379 * </code>
1381 * @return lesson_page|bool Returns the lesson_page specialised object or false
1383 protected function get_firstpage() {
1384 $pages = $this->load_all_pages();
1385 if (count($pages) > 0) {
1386 foreach ($pages as $page) {
1387 if ((int)$page->prevpageid === 0) {
1388 return $page;
1392 return false;
1396 * Returns the last page for the lesson or false if there isn't one.
1398 * This method should be called via the magic method __get();
1399 * <code>
1400 * $lastpage = $lesson->lastpage;
1401 * </code>
1403 * @return lesson_page|bool Returns the lesson_page specialised object or false
1405 protected function get_lastpage() {
1406 $pages = $this->load_all_pages();
1407 if (count($pages) > 0) {
1408 foreach ($pages as $page) {
1409 if ((int)$page->nextpageid === 0) {
1410 return $page;
1414 return false;
1418 * Returns the id of the first page of this lesson. (prevpageid = 0)
1419 * @return int
1421 protected function get_firstpageid() {
1422 global $DB;
1423 if ($this->firstpageid == null) {
1424 if (!$this->loadedallpages) {
1425 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1426 if (!$firstpageid) {
1427 print_error('cannotfindfirstpage', 'lesson');
1429 $this->firstpageid = $firstpageid;
1430 } else {
1431 $firstpage = $this->get_firstpage();
1432 $this->firstpageid = $firstpage->id;
1435 return $this->firstpageid;
1439 * Returns the id of the last page of this lesson. (nextpageid = 0)
1440 * @return int
1442 public function get_lastpageid() {
1443 global $DB;
1444 if ($this->lastpageid == null) {
1445 if (!$this->loadedallpages) {
1446 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1447 if (!$lastpageid) {
1448 print_error('cannotfindlastpage', 'lesson');
1450 $this->lastpageid = $lastpageid;
1451 } else {
1452 $lastpageid = $this->get_lastpage();
1453 $this->lastpageid = $lastpageid->id;
1457 return $this->lastpageid;
1461 * Gets the next page id to display after the one that is provided.
1462 * @param int $nextpageid
1463 * @return bool
1465 public function get_next_page($nextpageid) {
1466 global $USER, $DB;
1467 $allpages = $this->load_all_pages();
1468 if ($this->properties->nextpagedefault) {
1469 // in Flash Card mode...first get number of retakes
1470 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1471 shuffle($allpages);
1472 $found = false;
1473 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1474 foreach ($allpages as $nextpage) {
1475 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1476 $found = true;
1477 break;
1480 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1481 foreach ($allpages as $nextpage) {
1482 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1483 $found = true;
1484 break;
1488 if ($found) {
1489 if ($this->properties->maxpages) {
1490 // check number of pages viewed (in the lesson)
1491 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1492 return LESSON_EOL;
1495 return $nextpage->id;
1498 // In a normal lesson mode
1499 foreach ($allpages as $nextpage) {
1500 if ((int)$nextpage->id === (int)$nextpageid) {
1501 return $nextpage->id;
1504 return LESSON_EOL;
1508 * Sets a message against the session for this lesson that will displayed next
1509 * time the lesson processes messages
1511 * @param string $message
1512 * @param string $class
1513 * @param string $align
1514 * @return bool
1516 public function add_message($message, $class="notifyproblem", $align='center') {
1517 global $SESSION;
1519 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1520 $SESSION->lesson_messages = array();
1521 $SESSION->lesson_messages[$this->properties->id] = array();
1522 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1523 $SESSION->lesson_messages[$this->properties->id] = array();
1526 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1528 return true;
1532 * Check if the lesson is accessible at the present time
1533 * @return bool True if the lesson is accessible, false otherwise
1535 public function is_accessible() {
1536 $available = $this->properties->available;
1537 $deadline = $this->properties->deadline;
1538 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1542 * Starts the lesson time for the current user
1543 * @return bool Returns true
1545 public function start_timer() {
1546 global $USER, $DB;
1548 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1549 false, MUST_EXIST);
1551 // Trigger lesson started event.
1552 $event = \mod_lesson\event\lesson_started::create(array(
1553 'objectid' => $this->properties()->id,
1554 'context' => context_module::instance($cm->id),
1555 'courseid' => $this->properties()->course
1557 $event->trigger();
1559 $USER->startlesson[$this->properties->id] = true;
1560 $startlesson = new stdClass;
1561 $startlesson->lessonid = $this->properties->id;
1562 $startlesson->userid = $USER->id;
1563 $startlesson->starttime = time();
1564 $startlesson->lessontime = time();
1565 $DB->insert_record('lesson_timer', $startlesson);
1566 if ($this->properties->timelimit) {
1567 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
1569 return true;
1573 * Updates the timer to the current time and returns the new timer object
1574 * @param bool $restart If set to true the timer is restarted
1575 * @param bool $continue If set to true AND $restart=true then the timer
1576 * will continue from a previous attempt
1577 * @return stdClass The new timer
1579 public function update_timer($restart=false, $continue=false, $endreached =false) {
1580 global $USER, $DB;
1582 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1584 // clock code
1585 // get time information for this user
1586 if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
1587 $this->start_timer();
1588 $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
1590 $timer = current($timer); // This will get the latest start time record.
1592 if ($restart) {
1593 if ($continue) {
1594 // continue a previous test, need to update the clock (think this option is disabled atm)
1595 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1597 // Trigger lesson resumed event.
1598 $event = \mod_lesson\event\lesson_resumed::create(array(
1599 'objectid' => $this->properties->id,
1600 'context' => context_module::instance($cm->id),
1601 'courseid' => $this->properties->course
1603 $event->trigger();
1605 } else {
1606 // starting over, so reset the clock
1607 $timer->starttime = time();
1609 // Trigger lesson restarted event.
1610 $event = \mod_lesson\event\lesson_restarted::create(array(
1611 'objectid' => $this->properties->id,
1612 'context' => context_module::instance($cm->id),
1613 'courseid' => $this->properties->course
1615 $event->trigger();
1620 $timer->lessontime = time();
1621 $timer->completed = $endreached;
1622 $DB->update_record('lesson_timer', $timer);
1624 // Update completion state.
1625 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1626 false, MUST_EXIST);
1627 $course = get_course($cm->course);
1628 $completion = new completion_info($course);
1629 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
1630 $completion->update_state($cm, COMPLETION_COMPLETE);
1632 return $timer;
1636 * Updates the timer to the current time then stops it by unsetting the user var
1637 * @return bool Returns true
1639 public function stop_timer() {
1640 global $USER, $DB;
1641 unset($USER->startlesson[$this->properties->id]);
1643 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1644 false, MUST_EXIST);
1646 // Trigger lesson ended event.
1647 $event = \mod_lesson\event\lesson_ended::create(array(
1648 'objectid' => $this->properties()->id,
1649 'context' => context_module::instance($cm->id),
1650 'courseid' => $this->properties()->course
1652 $event->trigger();
1654 return $this->update_timer(false, false, true);
1658 * Checks to see if the lesson has pages
1660 public function has_pages() {
1661 global $DB;
1662 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1663 return ($pagecount>0);
1667 * Returns the link for the related activity
1668 * @return array|false
1670 public function link_for_activitylink() {
1671 global $DB;
1672 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1673 if ($module) {
1674 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1675 if ($modname) {
1676 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1677 if ($instancename) {
1678 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1679 get_string('activitylinkname', 'lesson', $instancename),
1680 array('class'=>'centerpadded lessonbutton standardbutton'));
1684 return '';
1688 * Loads the requested page.
1690 * This function will return the requested page id as either a specialised
1691 * lesson_page object OR as a generic lesson_page.
1692 * If the page has been loaded previously it will be returned from the pages
1693 * array, otherwise it will be loaded from the database first
1695 * @param int $pageid
1696 * @return lesson_page A lesson_page object or an object that extends it
1698 public function load_page($pageid) {
1699 if (!array_key_exists($pageid, $this->pages)) {
1700 $manager = lesson_page_type_manager::get($this);
1701 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1703 return $this->pages[$pageid];
1707 * Loads ALL of the pages for this lesson
1709 * @return array An array containing all pages from this lesson
1711 public function load_all_pages() {
1712 if (!$this->loadedallpages) {
1713 $manager = lesson_page_type_manager::get($this);
1714 $this->pages = $manager->load_all_pages($this);
1715 $this->loadedallpages = true;
1717 return $this->pages;
1721 * Duplicate the lesson page.
1723 * @param int $pageid Page ID of the page to duplicate.
1724 * @return void.
1726 public function duplicate_page($pageid) {
1727 global $PAGE;
1728 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1729 $context = context_module::instance($cm->id);
1730 // Load the page.
1731 $page = $this->load_page($pageid);
1732 $properties = $page->properties();
1733 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
1734 if (!$properties->qoption) {
1735 unset($properties->qoption);
1737 if (!$properties->layout) {
1738 unset($properties->layout);
1740 if (!$properties->display) {
1741 unset($properties->display);
1744 $properties->pageid = $pageid;
1745 // Add text and format into the format required to create a new page.
1746 $properties->contents_editor = array(
1747 'text' => $properties->contents,
1748 'format' => $properties->contentsformat
1750 $answers = $page->get_answers();
1751 // Answers need to be added to $properties.
1752 $i = 0;
1753 $answerids = array();
1754 foreach ($answers as $answer) {
1755 // Needs to be rearranged to work with the create function.
1756 $properties->answer_editor[$i] = array(
1757 'text' => $answer->answer,
1758 'format' => $answer->answerformat
1761 $properties->response_editor[$i] = array(
1762 'text' => $answer->response,
1763 'format' => $answer->responseformat
1765 $answerids[] = $answer->id;
1767 $properties->jumpto[$i] = $answer->jumpto;
1768 $properties->score[$i] = $answer->score;
1770 $i++;
1772 // Create the duplicate page.
1773 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
1774 $newanswers = $newlessonpage->get_answers();
1775 // Copy over the file areas as well.
1776 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
1777 $j = 0;
1778 foreach ($newanswers as $answer) {
1779 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
1780 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
1782 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
1783 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
1785 $j++;
1790 * Copy the files from one page to another.
1792 * @param string $filearea Area that the files are stored.
1793 * @param int $itemid Item ID.
1794 * @param int $newitemid The item ID for the new page.
1795 * @param int $contextid Context ID for this page.
1796 * @return void.
1798 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
1799 $fs = get_file_storage();
1800 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
1801 foreach ($files as $file) {
1802 $fieldupdates = array('itemid' => $newitemid);
1803 $fs->create_file_from_storedfile($fieldupdates, $file);
1808 * Determines if a jumpto value is correct or not.
1810 * returns true if jumpto page is (logically) after the pageid page or
1811 * if the jumpto value is a special value. Returns false in all other cases.
1813 * @param int $pageid Id of the page from which you are jumping from.
1814 * @param int $jumpto The jumpto number.
1815 * @return boolean True or false after a series of tests.
1817 public function jumpto_is_correct($pageid, $jumpto) {
1818 global $DB;
1820 // first test the special values
1821 if (!$jumpto) {
1822 // same page
1823 return false;
1824 } elseif ($jumpto == LESSON_NEXTPAGE) {
1825 return true;
1826 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1827 return true;
1828 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1829 return true;
1830 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1831 return true;
1832 } elseif ($jumpto == LESSON_EOL) {
1833 return true;
1836 $pages = $this->load_all_pages();
1837 $apageid = $pages[$pageid]->nextpageid;
1838 while ($apageid != 0) {
1839 if ($jumpto == $apageid) {
1840 return true;
1842 $apageid = $pages[$apageid]->nextpageid;
1844 return false;
1848 * Returns the time a user has remaining on this lesson
1849 * @param int $starttime Starttime timestamp
1850 * @return string
1852 public function time_remaining($starttime) {
1853 $timeleft = $starttime + $this->properties->timelimit - time();
1854 $hours = floor($timeleft/3600);
1855 $timeleft = $timeleft - ($hours * 3600);
1856 $minutes = floor($timeleft/60);
1857 $secs = $timeleft - ($minutes * 60);
1859 if ($minutes < 10) {
1860 $minutes = "0$minutes";
1862 if ($secs < 10) {
1863 $secs = "0$secs";
1865 $output = array();
1866 $output[] = $hours;
1867 $output[] = $minutes;
1868 $output[] = $secs;
1869 $output = implode(':', $output);
1870 return $output;
1874 * Interprets LESSON_CLUSTERJUMP jumpto value.
1876 * This will select a page randomly
1877 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1878 * and the page selected will be a page that has not been viewed already
1879 * and if any pages are within a branch table or end of branch then only 1 page within
1880 * the branch table or end of branch will be randomly selected (sub clustering).
1882 * @param int $pageid Id of the current page from which we are jumping from.
1883 * @param int $userid Id of the user.
1884 * @return int The id of the next page.
1886 public function cluster_jump($pageid, $userid=null) {
1887 global $DB, $USER;
1889 if ($userid===null) {
1890 $userid = $USER->id;
1892 // get the number of retakes
1893 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1894 $retakes = 0;
1896 // get all the lesson_attempts aka what the user has seen
1897 $seenpages = array();
1898 if ($attempts = $this->get_attempts($retakes)) {
1899 foreach ($attempts as $attempt) {
1900 $seenpages[$attempt->pageid] = $attempt->pageid;
1905 // get the lesson pages
1906 $lessonpages = $this->load_all_pages();
1907 // find the start of the cluster
1908 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1909 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1910 break;
1912 $pageid = $lessonpages[$pageid]->prevpageid;
1915 $clusterpages = array();
1916 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1917 $unseen = array();
1918 foreach ($clusterpages as $key=>$cluster) {
1919 // Remove the page if it is in a branch table or is an endofbranch.
1920 if ($this->is_sub_page_of_type($cluster->id,
1921 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
1922 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1923 unset($clusterpages[$key]);
1924 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
1925 // If branchtable, check to see if any pages inside have been viewed.
1926 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1927 $flag = true;
1928 foreach ($branchpages as $branchpage) {
1929 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
1930 $flag = false;
1933 if ($flag && count($branchpages) > 0) {
1934 // Add branch table.
1935 $unseen[] = $cluster;
1937 } elseif ($cluster->is_unseen($seenpages)) {
1938 $unseen[] = $cluster;
1942 if (count($unseen) > 0) {
1943 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1944 $nextpage = $unseen[rand(0, count($unseen)-1)];
1945 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1946 // if branch table, then pick a random page inside of it
1947 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1948 return $branchpages[rand(0, count($branchpages)-1)]->id;
1949 } else { // otherwise, return the page's id
1950 return $nextpage->id;
1952 } else {
1953 // seen all there is to see, leave the cluster
1954 if (end($clusterpages)->nextpageid == 0) {
1955 return LESSON_EOL;
1956 } else {
1957 $clusterendid = $pageid;
1958 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
1959 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1960 break;
1962 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1964 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1965 if ($exitjump == LESSON_NEXTPAGE) {
1966 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1968 if ($exitjump == 0) {
1969 return LESSON_EOL;
1970 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1971 return $exitjump;
1972 } else {
1973 if (!array_key_exists($exitjump, $lessonpages)) {
1974 $found = false;
1975 foreach ($lessonpages as $page) {
1976 if ($page->id === $clusterendid) {
1977 $found = true;
1978 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1979 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1980 if ($exitjump == LESSON_NEXTPAGE) {
1981 $exitjump = $lessonpages[$page->id]->nextpageid;
1983 break;
1987 if (!array_key_exists($exitjump, $lessonpages)) {
1988 return LESSON_EOL;
1990 return $exitjump;
1997 * Finds all pages that appear to be a subtype of the provided pageid until
1998 * an end point specified within $ends is encountered or no more pages exist
2000 * @param int $pageid
2001 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2002 * the subtype
2003 * @return array An array of specialised lesson_page objects
2005 public function get_sub_pages_of($pageid, array $ends) {
2006 $lessonpages = $this->load_all_pages();
2007 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
2008 $pages = array();
2010 while (true) {
2011 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2012 break;
2014 $pages[] = $lessonpages[$pageid];
2015 $pageid = $lessonpages[$pageid]->nextpageid;
2018 return $pages;
2022 * Checks to see if the specified page[id] is a subpage of a type specified in
2023 * the $types array, until either there are no more pages of we find a type
2024 * corresponding to that of a type specified in $ends
2026 * @param int $pageid The id of the page to check
2027 * @param array $types An array of types that would signify this page was a subpage
2028 * @param array $ends An array of types that mean this is not a subpage
2029 * @return bool
2031 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2032 $pages = $this->load_all_pages();
2033 $pageid = $pages[$pageid]->prevpageid; // move up one
2035 array_unshift($ends, 0);
2036 // go up the pages till branch table
2037 while (true) {
2038 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2039 return false;
2040 } else if (in_array($pages[$pageid]->qtype, $types)) {
2041 return true;
2043 $pageid = $pages[$pageid]->prevpageid;
2048 * Move a page resorting all other pages.
2050 * @param int $pageid
2051 * @param int $after
2052 * @return void
2054 public function resort_pages($pageid, $after) {
2055 global $CFG;
2057 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2058 $context = context_module::instance($cm->id);
2060 $pages = $this->load_all_pages();
2062 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2063 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2066 $pagetomove = clone($pages[$pageid]);
2067 unset($pages[$pageid]);
2069 $pageids = array();
2070 if ($after === 0) {
2071 $pageids['p0'] = $pageid;
2073 foreach ($pages as $page) {
2074 $pageids[] = $page->id;
2075 if ($page->id == $after) {
2076 $pageids[] = $pageid;
2080 $pageidsref = $pageids;
2081 reset($pageidsref);
2082 $prev = 0;
2083 $next = next($pageidsref);
2084 foreach ($pageids as $pid) {
2085 if ($pid === $pageid) {
2086 $page = $pagetomove;
2087 } else {
2088 $page = $pages[$pid];
2090 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2091 $page->move($next, $prev);
2093 if ($pid === $pageid) {
2094 // We will trigger an event.
2095 $pageupdated = array('next' => $next, 'prev' => $prev);
2099 $prev = $page->id;
2100 $next = next($pageidsref);
2101 if (!$next) {
2102 $next = 0;
2106 // Trigger an event: page moved.
2107 if (!empty($pageupdated)) {
2108 $eventparams = array(
2109 'context' => $context,
2110 'objectid' => $pageid,
2111 'other' => array(
2112 'pagetype' => $page->get_typestring(),
2113 'prevpageid' => $pageupdated['prev'],
2114 'nextpageid' => $pageupdated['next']
2117 $event = \mod_lesson\event\page_moved::create($eventparams);
2118 $event->trigger();
2124 * Return the lesson context object.
2126 * @return stdClass context
2127 * @since Moodle 3.3
2129 public function get_context() {
2130 if ($this->context == null) {
2131 $this->context = context_module::instance($this->get_cm()->id);
2133 return $this->context;
2137 * Set the lesson course module object.
2139 * @param stdClass $cm course module objct
2140 * @since Moodle 3.3
2142 private function set_cm($cm) {
2143 $this->cm = $cm;
2147 * Return the lesson course module object.
2149 * @return stdClass course module
2150 * @since Moodle 3.3
2152 public function get_cm() {
2153 if ($this->cm == null) {
2154 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2156 return $this->cm;
2160 * Set the lesson course object.
2162 * @param stdClass $course course objct
2163 * @since Moodle 3.3
2165 private function set_courserecord($course) {
2166 $this->courserecord = $course;
2170 * Return the lesson course object.
2172 * @return stdClass course
2173 * @since Moodle 3.3
2175 public function get_courserecord() {
2176 global $DB;
2178 if ($this->courserecord == null) {
2179 $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2181 return $this->courserecord;
2185 * Check if the user can manage the lesson activity.
2187 * @return bool true if the user can manage the lesson
2188 * @since Moodle 3.3
2190 public function can_manage() {
2191 return has_capability('mod/lesson:manage', $this->get_context());
2195 * Check if time restriction is applied.
2197 * @return mixed false if there aren't restrictions or an object with the restriction information
2198 * @since Moodle 3.3
2200 public function get_time_restriction_status() {
2201 if ($this->can_manage()) {
2202 return false;
2205 if (!$this->is_accessible()) {
2206 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2207 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2208 } else {
2209 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2211 return (object) $status;
2213 return false;
2217 * Check if password restriction is applied.
2219 * @param string $userpassword the user password to check (if the restriction is set)
2220 * @return mixed false if there aren't restrictions or an object with the restriction information
2221 * @since Moodle 3.3
2223 public function get_password_restriction_status($userpassword) {
2224 global $USER;
2225 if ($this->can_manage()) {
2226 return false;
2229 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2230 $correctpass = false;
2231 if (!empty($userpassword) &&
2232 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2233 // With or without md5 for backward compatibility (MDL-11090).
2234 $correctpass = true;
2235 $USER->lessonloggedin[$this->id] = true;
2236 } else if (isset($this->properties->extrapasswords)) {
2237 // Group overrides may have additional passwords.
2238 foreach ($this->properties->extrapasswords as $password) {
2239 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2240 $correctpass = true;
2241 $USER->lessonloggedin[$this->id] = true;
2245 return !$correctpass;
2247 return false;
2251 * Check if dependencies restrictions are applied.
2253 * @return mixed false if there aren't restrictions or an object with the restriction information
2254 * @since Moodle 3.3
2256 public function get_dependencies_restriction_status() {
2257 global $DB, $USER;
2258 if ($this->can_manage()) {
2259 return false;
2262 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2263 // Lesson exists, so we can proceed.
2264 $conditions = unserialize($this->properties->conditions);
2265 // Assume false for all.
2266 $errors = array();
2267 // Check for the timespent condition.
2268 if ($conditions->timespent) {
2269 $timespent = false;
2270 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2271 // Go through all the times and test to see if any of them satisfy the condition.
2272 foreach ($attempttimes as $attempttime) {
2273 $duration = $attempttime->lessontime - $attempttime->starttime;
2274 if ($conditions->timespent < $duration / 60) {
2275 $timespent = true;
2279 if (!$timespent) {
2280 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2283 // Check for the gradebetterthan condition.
2284 if ($conditions->gradebetterthan) {
2285 $gradebetterthan = false;
2286 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2287 // Go through all the grades and test to see if any of them satisfy the condition.
2288 foreach ($studentgrades as $studentgrade) {
2289 if ($studentgrade->grade >= $conditions->gradebetterthan) {
2290 $gradebetterthan = true;
2294 if (!$gradebetterthan) {
2295 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2298 // Check for the completed condition.
2299 if ($conditions->completed) {
2300 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2301 $errors[] = get_string('completederror', 'lesson');
2304 if (!empty($errors)) {
2305 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2308 return false;
2312 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2314 * @return bool true if is in review mode
2315 * @since Moodle 3.3
2317 public function is_in_review_mode() {
2318 global $DB, $USER;
2320 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2321 if ($userhasgrade && !$this->properties->retake) {
2322 return true;
2324 return false;
2328 * Return the last page the current user saw.
2330 * @param int $retriescount the number of retries for the lesson (the last retry number).
2331 * @return mixed false if the user didn't see the lesson or the last page id
2333 public function get_last_page_seen($retriescount) {
2334 global $DB, $USER;
2336 $lastpageseen = false;
2337 $allattempts = $this->get_attempts($retriescount);
2338 if (!empty($allattempts)) {
2339 $attempt = end($allattempts);
2340 $attemptpage = $this->load_page($attempt->pageid);
2341 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2342 // Convert the jumpto to a proper page id.
2343 if ($jumpto == 0) {
2344 // Check if a question has been incorrectly answered AND no more attempts at it are left.
2345 $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2346 if (count($nattempts) >= $this->properties->maxattempts) {
2347 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2348 } else {
2349 $lastpageseen = $attempt->pageid;
2351 } else if ($jumpto == LESSON_NEXTPAGE) {
2352 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2353 } else if ($jumpto == LESSON_CLUSTERJUMP) {
2354 $lastpageseen = $this->cluster_jump($attempt->pageid);
2355 } else {
2356 $lastpageseen = $jumpto;
2360 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
2361 // In here, user has viewed a branch table.
2362 $lastbranchtable = current($branchtables);
2363 if (count($allattempts) > 0) {
2364 if ($lastbranchtable->timeseen > $attempt->timeseen) {
2365 // This branch table was viewed more recently than the question page.
2366 if (!empty($lastbranchtable->nextpageid)) {
2367 $lastpageseen = $lastbranchtable->nextpageid;
2368 } else {
2369 // Next page ID did not exist prior to MDL-34006.
2370 $lastpageseen = $lastbranchtable->pageid;
2373 } else {
2374 // Has not answered any questions but has viewed a branch table.
2375 if (!empty($lastbranchtable->nextpageid)) {
2376 $lastpageseen = $lastbranchtable->nextpageid;
2377 } else {
2378 // Next page ID did not exist prior to MDL-34006.
2379 $lastpageseen = $lastbranchtable->pageid;
2383 return $lastpageseen;
2387 * Return the number of retries in a lesson for a given user.
2389 * @param int $userid the user id
2390 * @return int the retries count
2391 * @since Moodle 3.3
2393 public function count_user_retries($userid) {
2394 global $DB;
2396 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
2400 * Check if a user left a timed session.
2402 * @param int $retriescount the number of retries for the lesson (the last retry number).
2403 * @return true if the user left the timed session
2404 * @since Moodle 3.3
2406 public function left_during_timed_session($retriescount) {
2407 global $DB, $USER;
2409 $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
2410 return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
2414 * Trigger module viewed event and set the module viewed for completion.
2416 * @since Moodle 3.3
2418 public function set_module_viewed() {
2419 global $CFG;
2420 require_once($CFG->libdir . '/completionlib.php');
2422 // Trigger module viewed event.
2423 $event = \mod_lesson\event\course_module_viewed::create(array(
2424 'objectid' => $this->properties->id,
2425 'context' => $this->get_context()
2427 $event->add_record_snapshot('course_modules', $this->get_cm());
2428 $event->add_record_snapshot('course', $this->get_courserecord());
2429 $event->trigger();
2431 // Mark as viewed.
2432 $completion = new completion_info($this->get_courserecord());
2433 $completion->set_module_viewed($this->get_cm());
2437 * Return the timers in the current lesson for the given user.
2439 * @param int $userid the user id
2440 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
2441 * @param string $fields a comma separated list of fields to return
2442 * @param int $limitfrom return a subset of records, starting at this point (optional).
2443 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
2444 * @return array list of timers for the given user in the lesson
2445 * @since Moodle 3.3
2447 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
2448 global $DB, $USER;
2450 if ($userid === null) {
2451 $userid = $USER->id;
2454 $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
2455 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
2459 * Check if the user is out of time in a timed lesson.
2461 * @param stdClass $timer timer object
2462 * @return bool True if the user is on time, false is the user ran out of time
2463 * @since Moodle 3.3
2465 public function check_time($timer) {
2466 if ($this->properties->timelimit) {
2467 $timeleft = $timer->starttime + $this->properties->timelimit - time();
2468 if ($timeleft <= 0) {
2469 // Out of time.
2470 $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
2471 return false;
2472 } else if ($timeleft < 60) {
2473 // One minute warning.
2474 $this->add_message(get_string('studentoneminwarning', 'lesson'));
2477 return true;
2481 * Add different informative messages to the given page.
2483 * @param lesson_page $page page object
2484 * @param reviewmode $bool whether we are in review mode or not
2485 * @since Moodle 3.3
2487 public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
2488 global $DB, $USER;
2490 if (!$this->can_manage()) {
2491 if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
2492 // Tell student how many questions they have seen, how many are required and their grade.
2493 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2494 $gradeinfo = lesson_grade($this, $ntries);
2495 if ($gradeinfo->attempts) {
2496 if ($gradeinfo->nquestions < $this->properties->minquestions) {
2497 $a = new stdClass;
2498 $a->nquestions = $gradeinfo->nquestions;
2499 $a->minquestions = $this->properties->minquestions;
2500 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
2503 if (!$reviewmode && !$this->properties->retake) {
2504 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
2505 if ($this->properties->grade != GRADE_TYPE_NONE) {
2506 $a = new stdClass;
2507 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
2508 $a->total = $this->properties->grade;
2509 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
2514 } else {
2515 if ($this->properties->timelimit) {
2516 $this->add_message(get_string('teachertimerwarning', 'lesson'));
2518 if (lesson_display_teacher_warning($this)) {
2519 // This is the warning msg for teachers to inform them that cluster
2520 // and unseen does not work while logged in as a teacher.
2521 $warningvars = new stdClass();
2522 $warningvars->cluster = get_string('clusterjump', 'lesson');
2523 $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
2524 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
2530 * Get the ongoing score message for the user (depending on the user permission and lesson settings).
2532 * @return str the ongoing score message
2533 * @since Moodle 3.3
2535 public function get_ongoing_score_message() {
2536 global $USER, $DB;
2538 $context = $this->get_context();
2540 if (has_capability('mod/lesson:manage', $context)) {
2541 return get_string('teacherongoingwarning', 'lesson');
2542 } else {
2543 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2544 if (isset($USER->modattempts[$this->properties->id])) {
2545 $ntries--;
2547 $gradeinfo = lesson_grade($this, $ntries);
2548 $a = new stdClass;
2549 if ($this->properties->custom) {
2550 $a->score = $gradeinfo->earned;
2551 $a->currenthigh = $gradeinfo->total;
2552 return get_string("ongoingcustom", "lesson", $a);
2553 } else {
2554 $a->correct = $gradeinfo->earned;
2555 $a->viewed = $gradeinfo->attempts;
2556 return get_string("ongoingnormal", "lesson", $a);
2562 * Calculate the progress of the current user in the lesson.
2564 * @return int the progress (scale 0-100)
2565 * @since Moodle 3.3
2567 public function calculate_progress() {
2568 global $USER, $DB;
2570 // Check if the user is reviewing the attempt.
2571 if (isset($USER->modattempts[$this->properties->id])) {
2572 return 100;
2575 // All of the lesson pages.
2576 $pages = $this->load_all_pages();
2577 foreach ($pages as $page) {
2578 if ($page->prevpageid == 0) {
2579 $pageid = $page->id; // Find the first page id.
2580 break;
2584 // Current attempt number.
2585 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
2586 $ntries = 0; // May not be necessary.
2589 $viewedpageids = array();
2590 if ($attempts = $this->get_attempts($ntries, false)) {
2591 foreach ($attempts as $attempt) {
2592 $viewedpageids[$attempt->pageid] = $attempt;
2596 $viewedbranches = array();
2597 // Collect all of the branch tables viewed.
2598 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
2599 foreach ($branches as $branch) {
2600 $viewedbranches[$branch->pageid] = $branch;
2602 $viewedpageids = array_merge($viewedpageids, $viewedbranches);
2605 // Filter out the following pages:
2606 // - End of Cluster
2607 // - End of Branch
2608 // - Pages found inside of Clusters
2609 // Do not filter out Cluster Page(s) because we count a cluster as one.
2610 // By keeping the cluster page, we get our 1.
2611 $validpages = array();
2612 while ($pageid != 0) {
2613 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
2616 // Progress calculation as a percent.
2617 return round(count($viewedpageids) / count($validpages), 2) * 100;
2621 * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
2623 * @param int $pageid the given page id
2624 * @param mod_lesson_renderer $lessonoutput the lesson output rendered
2625 * @param bool $reviewmode whether we are in review mode or not
2626 * @return array the page object and contents
2627 * @throws moodle_exception
2628 * @since Moodle 3.3
2630 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode) {
2631 global $USER, $CFG;
2633 $page = $this->load_page($pageid);
2634 // Check if the page is of a special type and if so take any nessecary action.
2635 $newpageid = $page->callback_on_view($this->can_manage());
2636 if (is_numeric($newpageid)) {
2637 $page = $this->load_page($newpageid);
2640 // Add different informative messages to the given page.
2641 $this->add_messages_on_page_view($page, $reviewmode);
2643 if (is_array($page->answers) && count($page->answers) > 0) {
2644 // This is for modattempts option. Find the users previous answer to this page,
2645 // and then display it below in answer processing.
2646 if (isset($USER->modattempts[$this->properties->id])) {
2647 $retries = $this->count_user_retries($USER->id);
2648 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
2649 throw new moodle_exception('cannotfindpreattempt', 'lesson');
2651 $attempt = end($attempts);
2652 $USER->modattempts[$this->properties->id] = $attempt;
2653 } else {
2654 $attempt = false;
2656 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
2657 } else {
2658 require_once($CFG->dirroot . '/mod/lesson/view_form.php');
2659 $data = new stdClass;
2660 $data->id = $this->get_cm()->id;
2661 $data->pageid = $page->id;
2662 $data->newpageid = $this->get_next_page($page->nextpageid);
2664 $customdata = array(
2665 'title' => $page->title,
2666 'contents' => $page->get_contents()
2668 $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
2669 $mform->set_data($data);
2670 ob_start();
2671 $mform->display();
2672 $lessoncontent = ob_get_contents();
2673 ob_end_clean();
2676 return array($page, $lessoncontent);
2680 * Process page responses.
2682 * @param lesson_page $page page object
2683 * @since Moodle 3.3
2685 public function process_page_responses(lesson_page $page) {
2686 global $USER, $DB;
2688 $canmanage = $this->can_manage();
2689 $context = $this->get_context();
2691 // Check the page has answers [MDL-25632].
2692 if (count($page->answers) > 0) {
2693 $result = $page->record_attempt($context);
2694 } else {
2695 // The page has no answers so we will just progress to the next page in the
2696 // sequence (as set by newpageid).
2697 $result = new stdClass;
2698 $result->newpageid = optional_param('newpageid', $page->nextpageid, PARAM_INT);
2699 $result->nodefaultresponse = true;
2702 if ($result->inmediatejump) {
2703 return $result;
2704 } else if (isset($USER->modattempts[$this->properties->id])) {
2705 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
2706 if ($USER->modattempts[$lesson->id]->pageid == $page->id && $page->nextpageid == 0) {
2707 // Remember, this session variable holds the pageid of the last page that the user saw.
2708 $result->newpageid = LESSON_EOL;
2709 } else {
2710 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $lesson->id, "userid" => $USER->id));
2711 $nretakes--; // Make sure we are looking at the right try.
2712 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $lesson->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
2713 $found = false;
2714 $temppageid = 0;
2715 // Make sure that the newpageid always defaults to something valid.
2716 $result->newpageid = LESSON_EOL;
2717 foreach ($attempts as $attempt) {
2718 if ($found && $temppageid != $attempt->pageid) {
2719 // Now try to find the next page, make sure next few attempts do no belong to current page.
2720 $result->newpageid = $attempt->pageid;
2721 break;
2723 if ($attempt->pageid == $page->id) {
2724 $found = true; // If found current page.
2725 $temppageid = $attempt->pageid;
2729 } else if ($result->newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $result->newpageid > 0) {
2730 // Going to check to see if the page that the user is going to view next, is a cluster page.
2731 // If so, dont display, go into the cluster.
2732 // The $result->newpageid > 0 is used to filter out all of the negative code jumps.
2733 $newpage = $lesson->load_page($result->newpageid);
2734 if ($newpageid = $newpage->override_next_page($result->newpageid)) {
2735 $result->newpageid = $newpageid;
2737 } else if ($result->newpageid == LESSON_UNSEENBRANCHPAGE) {
2738 if ($canmanage) {
2739 if ($page->nextpageid == 0) {
2740 $result->newpageid = LESSON_EOL;
2741 } else {
2742 $result->newpageid = $page->nextpageid;
2744 } else {
2745 $result->newpageid = lesson_unseen_question_jump($lesson, $USER->id, $page->id);
2747 } else if ($result->newpageid == LESSON_PREVIOUSPAGE) {
2748 $result->newpageid = $page->prevpageid;
2749 } else if ($result->newpageid == LESSON_RANDOMPAGE) {
2750 $result->newpageid = lesson_random_question_jump($lesson, $page->id);
2751 } else if ($result->newpageid == LESSON_CLUSTERJUMP) {
2752 if ($canmanage) {
2753 if ($page->nextpageid == 0) { // If teacher, go to next page.
2754 $result->newpageid = LESSON_EOL;
2755 } else {
2756 $result->newpageid = $page->nextpageid;
2758 } else {
2759 $result->newpageid = $lesson->cluster_jump($page->id);
2762 return $result;
2766 * Add different informative messages to the given page.
2768 * @param lesson_page $page page object
2769 * @param stdClass $result the page processing result object
2770 * @param bool $reviewmode whether we are in review mode or not
2771 * @since Moodle 3.3
2773 public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
2775 if ($this->can_manage()) {
2776 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
2777 if (lesson_display_teacher_warning($this)) {
2778 $warningvars = new stdClass();
2779 $warningvars->cluster = get_string("clusterjump", "lesson");
2780 $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
2781 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
2783 // Inform teacher that s/he will not see the timer.
2784 if ($this->properties->timelimit) {
2785 $lesson->add_message(get_string("teachertimerwarning", "lesson"));
2788 // Report attempts remaining.
2789 if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
2790 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
2797 * Abstract class to provide a core functions to the all lesson classes
2799 * This class should be abstracted by ALL classes with the lesson module to ensure
2800 * that all classes within this module can be interacted with in the same way.
2802 * This class provides the user with a basic properties array that can be fetched
2803 * or set via magic methods, or alternatively by defining methods get_blah() or
2804 * set_blah() within the extending object.
2806 * @copyright 2009 Sam Hemelryk
2807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2809 abstract class lesson_base {
2812 * An object containing properties
2813 * @var stdClass
2815 protected $properties;
2818 * The constructor
2819 * @param stdClass $properties
2821 public function __construct($properties) {
2822 $this->properties = (object)$properties;
2826 * Magic property method
2828 * Attempts to call a set_$key method if one exists otherwise falls back
2829 * to simply set the property
2831 * @param string $key
2832 * @param mixed $value
2834 public function __set($key, $value) {
2835 if (method_exists($this, 'set_'.$key)) {
2836 $this->{'set_'.$key}($value);
2838 $this->properties->{$key} = $value;
2842 * Magic get method
2844 * Attempts to call a get_$key method to return the property and ralls over
2845 * to return the raw property
2847 * @param str $key
2848 * @return mixed
2850 public function __get($key) {
2851 if (method_exists($this, 'get_'.$key)) {
2852 return $this->{'get_'.$key}();
2854 return $this->properties->{$key};
2858 * Stupid PHP needs an isset magic method if you use the get magic method and
2859 * still want empty calls to work.... blah ~!
2861 * @param string $key
2862 * @return bool
2864 public function __isset($key) {
2865 if (method_exists($this, 'get_'.$key)) {
2866 $val = $this->{'get_'.$key}();
2867 return !empty($val);
2869 return !empty($this->properties->{$key});
2872 //NOTE: E_STRICT does not allow to change function signature!
2875 * If implemented should create a new instance, save it in the DB and return it
2877 //public static function create() {}
2879 * If implemented should load an instance from the DB and return it
2881 //public static function load() {}
2883 * Fetches all of the properties of the object
2884 * @return stdClass
2886 public function properties() {
2887 return $this->properties;
2893 * Abstract class representation of a page associated with a lesson.
2895 * This class should MUST be extended by all specialised page types defined in
2896 * mod/lesson/pagetypes/.
2897 * There are a handful of abstract methods that need to be defined as well as
2898 * severl methods that can optionally be defined in order to make the page type
2899 * operate in the desired way
2901 * Database properties
2902 * @property int $id The id of this lesson page
2903 * @property int $lessonid The id of the lesson this page belongs to
2904 * @property int $prevpageid The id of the page before this one
2905 * @property int $nextpageid The id of the next page in the page sequence
2906 * @property int $qtype Identifies the page type of this page
2907 * @property int $qoption Used to record page type specific options
2908 * @property int $layout Used to record page specific layout selections
2909 * @property int $display Used to record page specific display selections
2910 * @property int $timecreated Timestamp for when the page was created
2911 * @property int $timemodified Timestamp for when the page was last modified
2912 * @property string $title The title of this page
2913 * @property string $contents The rich content shown to describe the page
2914 * @property int $contentsformat The format of the contents field
2916 * Calculated properties
2917 * @property-read array $answers An array of answers for this page
2918 * @property-read bool $displayinmenublock Toggles display in the left menu block
2919 * @property-read array $jumps An array containing all the jumps this page uses
2920 * @property-read lesson $lesson The lesson this page belongs to
2921 * @property-read int $type The type of the page [question | structure]
2922 * @property-read typeid The unique identifier for the page type
2923 * @property-read typestring The string that describes this page type
2925 * @abstract
2926 * @copyright 2009 Sam Hemelryk
2927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2929 abstract class lesson_page extends lesson_base {
2932 * A reference to the lesson this page belongs to
2933 * @var lesson
2935 protected $lesson = null;
2937 * Contains the answers to this lesson_page once loaded
2938 * @var null|array
2940 protected $answers = null;
2942 * This sets the type of the page, can be one of the constants defined below
2943 * @var int
2945 protected $type = 0;
2948 * Constants used to identify the type of the page
2950 const TYPE_QUESTION = 0;
2951 const TYPE_STRUCTURE = 1;
2954 * This method should return the integer used to identify the page type within
2955 * the database and throughout code. This maps back to the defines used in 1.x
2956 * @abstract
2957 * @return int
2959 abstract protected function get_typeid();
2961 * This method should return the string that describes the pagetype
2962 * @abstract
2963 * @return string
2965 abstract protected function get_typestring();
2968 * This method gets called to display the page to the user taking the lesson
2969 * @abstract
2970 * @param object $renderer
2971 * @param object $attempt
2972 * @return string
2974 abstract public function display($renderer, $attempt);
2977 * Creates a new lesson_page within the database and returns the correct pagetype
2978 * object to use to interact with the new lesson
2980 * @final
2981 * @static
2982 * @param object $properties
2983 * @param lesson $lesson
2984 * @return lesson_page Specialised object that extends lesson_page
2986 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
2987 global $DB;
2988 $newpage = new stdClass;
2989 $newpage->title = $properties->title;
2990 $newpage->contents = $properties->contents_editor['text'];
2991 $newpage->contentsformat = $properties->contents_editor['format'];
2992 $newpage->lessonid = $lesson->id;
2993 $newpage->timecreated = time();
2994 $newpage->qtype = $properties->qtype;
2995 $newpage->qoption = (isset($properties->qoption))?1:0;
2996 $newpage->layout = (isset($properties->layout))?1:0;
2997 $newpage->display = (isset($properties->display))?1:0;
2998 $newpage->prevpageid = 0; // this is a first page
2999 $newpage->nextpageid = 0; // this is the only page
3001 if ($properties->pageid) {
3002 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
3003 if (!$prevpage) {
3004 print_error('cannotfindpages', 'lesson');
3006 $newpage->prevpageid = $prevpage->id;
3007 $newpage->nextpageid = $prevpage->nextpageid;
3008 } else {
3009 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
3010 if ($nextpage) {
3011 // This is the first page, there are existing pages put this at the start
3012 $newpage->nextpageid = $nextpage->id;
3016 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
3018 $editor = new stdClass;
3019 $editor->id = $newpage->id;
3020 $editor->contents_editor = $properties->contents_editor;
3021 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
3022 $DB->update_record("lesson_pages", $editor);
3024 if ($newpage->prevpageid > 0) {
3025 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
3027 if ($newpage->nextpageid > 0) {
3028 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
3031 $page = lesson_page::load($newpage, $lesson);
3032 $page->create_answers($properties);
3034 // Trigger an event: page created.
3035 $eventparams = array(
3036 'context' => $context,
3037 'objectid' => $newpage->id,
3038 'other' => array(
3039 'pagetype' => $page->get_typestring()
3042 $event = \mod_lesson\event\page_created::create($eventparams);
3043 $snapshot = clone($newpage);
3044 $snapshot->timemodified = 0;
3045 $event->add_record_snapshot('lesson_pages', $snapshot);
3046 $event->trigger();
3048 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
3050 return $page;
3054 * This method loads a page object from the database and returns it as a
3055 * specialised object that extends lesson_page
3057 * @final
3058 * @static
3059 * @param int $id
3060 * @param lesson $lesson
3061 * @return lesson_page Specialised lesson_page object
3063 final public static function load($id, lesson $lesson) {
3064 global $DB;
3066 if (is_object($id) && !empty($id->qtype)) {
3067 $page = $id;
3068 } else {
3069 $page = $DB->get_record("lesson_pages", array("id" => $id));
3070 if (!$page) {
3071 print_error('cannotfindpages', 'lesson');
3074 $manager = lesson_page_type_manager::get($lesson);
3076 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
3077 if (!class_exists($class)) {
3078 $class = 'lesson_page';
3081 return new $class($page, $lesson);
3085 * Deletes a lesson_page from the database as well as any associated records.
3086 * @final
3087 * @return bool
3089 final public function delete() {
3090 global $DB;
3092 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3093 $context = context_module::instance($cm->id);
3095 // Delete files associated with attempts.
3096 $fs = get_file_storage();
3097 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
3098 foreach ($attempts as $attempt) {
3099 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
3103 // Then delete all the associated records...
3104 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
3106 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
3107 // ...now delete the answers...
3108 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
3109 // ..and the page itself
3110 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
3112 // Trigger an event: page deleted.
3113 $eventparams = array(
3114 'context' => $context,
3115 'objectid' => $this->properties->id,
3116 'other' => array(
3117 'pagetype' => $this->get_typestring()
3120 $event = \mod_lesson\event\page_deleted::create($eventparams);
3121 $event->add_record_snapshot('lesson_pages', $this->properties);
3122 $event->trigger();
3124 // Delete files associated with this page.
3125 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
3126 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $this->properties->id);
3127 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $this->properties->id);
3129 // repair the hole in the linkage
3130 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
3131 //This is the only page, no repair needed
3132 } elseif (!$this->properties->prevpageid) {
3133 // this is the first page...
3134 $page = $this->lesson->load_page($this->properties->nextpageid);
3135 $page->move(null, 0);
3136 } elseif (!$this->properties->nextpageid) {
3137 // this is the last page...
3138 $page = $this->lesson->load_page($this->properties->prevpageid);
3139 $page->move(0);
3140 } else {
3141 // page is in the middle...
3142 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
3143 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
3145 $prevpage->move($nextpage->id);
3146 $nextpage->move(null, $prevpage->id);
3148 return true;
3152 * Moves a page by updating its nextpageid and prevpageid values within
3153 * the database
3155 * @final
3156 * @param int $nextpageid
3157 * @param int $prevpageid
3159 final public function move($nextpageid=null, $prevpageid=null) {
3160 global $DB;
3161 if ($nextpageid === null) {
3162 $nextpageid = $this->properties->nextpageid;
3164 if ($prevpageid === null) {
3165 $prevpageid = $this->properties->prevpageid;
3167 $obj = new stdClass;
3168 $obj->id = $this->properties->id;
3169 $obj->prevpageid = $prevpageid;
3170 $obj->nextpageid = $nextpageid;
3171 $DB->update_record('lesson_pages', $obj);
3175 * Returns the answers that are associated with this page in the database
3177 * @final
3178 * @return array
3180 final public function get_answers() {
3181 global $DB;
3182 if ($this->answers === null) {
3183 $this->answers = array();
3184 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
3185 if (!$answers) {
3186 // It is possible that a lesson upgraded from Moodle 1.9 still
3187 // contains questions without any answers [MDL-25632].
3188 // debugging(get_string('cannotfindanswer', 'lesson'));
3189 return array();
3191 foreach ($answers as $answer) {
3192 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
3195 return $this->answers;
3199 * Returns the lesson this page is associated with
3200 * @final
3201 * @return lesson
3203 final protected function get_lesson() {
3204 return $this->lesson;
3208 * Returns the type of page this is. Not to be confused with page type
3209 * @final
3210 * @return int
3212 final protected function get_type() {
3213 return $this->type;
3217 * Records an attempt at this page
3219 * @final
3220 * @global moodle_database $DB
3221 * @param stdClass $context
3222 * @return stdClass Returns the result of the attempt
3224 final public function record_attempt($context) {
3225 global $DB, $USER, $OUTPUT, $PAGE;
3228 * This should be overridden by each page type to actually check the response
3229 * against what ever custom criteria they have defined
3231 $result = $this->check_answer();
3233 // Processes inmediate jumps.
3234 if ($result->inmediatejump) {
3235 return $result;
3238 $result->attemptsremaining = 0;
3239 $result->maxattemptsreached = false;
3241 if ($result->noanswer) {
3242 $result->newpageid = $this->properties->id; // display same page again
3243 $result->feedback = get_string('noanswer', 'lesson');
3244 } else {
3245 if (!has_capability('mod/lesson:manage', $context)) {
3246 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
3248 // Get the number of attempts that have been made on this question for this student and retake,
3249 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
3250 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
3252 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
3253 if ($nattempts >= $this->lesson->maxattempts) {
3254 $result->maxattemptsreached = true;
3255 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
3256 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
3257 return $result;
3260 // record student's attempt
3261 $attempt = new stdClass;
3262 $attempt->lessonid = $this->lesson->id;
3263 $attempt->pageid = $this->properties->id;
3264 $attempt->userid = $USER->id;
3265 $attempt->answerid = $result->answerid;
3266 $attempt->retry = $nretakes;
3267 $attempt->correct = $result->correctanswer;
3268 if($result->userresponse !== null) {
3269 $attempt->useranswer = $result->userresponse;
3272 $attempt->timeseen = time();
3273 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
3274 $userisreviewing = false;
3275 if (isset($USER->modattempts[$this->lesson->id])) {
3276 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
3277 $userisreviewing = true;
3280 // Only insert a record if we are not reviewing the lesson.
3281 if (!$userisreviewing) {
3282 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
3283 $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
3284 // Trigger an event: question answered.
3285 $eventparams = array(
3286 'context' => context_module::instance($PAGE->cm->id),
3287 'objectid' => $this->properties->id,
3288 'other' => array(
3289 'pagetype' => $this->get_typestring()
3292 $event = \mod_lesson\event\question_answered::create($eventparams);
3293 $event->add_record_snapshot('lesson_attempts', $attempt);
3294 $event->trigger();
3296 // Increase the number of attempts made.
3297 $nattempts++;
3300 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
3301 // displaying of message(s) is at the end of page for more ergonomic display
3302 if (!$result->correctanswer && ($result->newpageid == 0)) {
3303 // retreive the number of attempts left counter for displaying at bottom of feedback page
3304 if ($nattempts >= $this->lesson->maxattempts) {
3305 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
3306 $result->maxattemptsreached = true;
3308 $result->newpageid = LESSON_NEXTPAGE;
3309 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
3310 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
3314 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
3315 if ($result->newpageid == 0) {
3316 $result->newpageid = $this->properties->id;
3317 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
3318 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
3321 // Determine default feedback if necessary
3322 if (empty($result->response)) {
3323 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
3324 // These conditions have been met:
3325 // 1. The lesson manager has not supplied feedback to the student
3326 // 2. Not displaying default feedback
3327 // 3. The user did provide an answer
3328 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
3330 $result->nodefaultresponse = true; // This will cause a redirect below
3331 } else if ($result->isessayquestion) {
3332 $result->response = get_string('defaultessayresponse', 'lesson');
3333 } else if ($result->correctanswer) {
3334 $result->response = get_string('thatsthecorrectanswer', 'lesson');
3335 } else {
3336 $result->response = get_string('thatsthewronganswer', 'lesson');
3340 if ($result->response) {
3341 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
3342 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
3343 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
3344 if ($qattempts == 1) {
3345 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
3346 } else {
3347 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
3349 } else {
3350 $result->feedback = '';
3352 $class = 'response';
3353 if ($result->correctanswer) {
3354 $class .= ' correct'; // CSS over-ride this if they exist (!important).
3355 } else if (!$result->isessayquestion) {
3356 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
3358 $options = new stdClass;
3359 $options->noclean = true;
3360 $options->para = true;
3361 $options->overflowdiv = true;
3362 $options->context = $context;
3364 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
3365 'generalbox boxaligncenter');
3366 if (isset($result->studentanswerformat)) {
3367 // This is the student's answer so it should be cleaned.
3368 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
3369 array('context' => $context, 'para' => true));
3370 } else {
3371 $studentanswer = format_string($result->studentanswer);
3373 $result->feedback .= '<div class="correctanswer generalbox"><em>'
3374 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
3375 if (isset($result->responseformat)) {
3376 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
3377 'mod_lesson', 'page_responses', $result->answerid);
3378 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
3379 , $class);
3380 } else {
3381 $result->feedback .= $OUTPUT->box($result->response, $class);
3383 $result->feedback .= '</div>';
3387 return $result;
3391 * Returns the string for a jump name
3393 * @final
3394 * @param int $jumpto Jump code or page ID
3395 * @return string
3397 final protected function get_jump_name($jumpto) {
3398 global $DB;
3399 static $jumpnames = array();
3401 if (!array_key_exists($jumpto, $jumpnames)) {
3402 if ($jumpto == LESSON_THISPAGE) {
3403 $jumptitle = get_string('thispage', 'lesson');
3404 } elseif ($jumpto == LESSON_NEXTPAGE) {
3405 $jumptitle = get_string('nextpage', 'lesson');
3406 } elseif ($jumpto == LESSON_EOL) {
3407 $jumptitle = get_string('endoflesson', 'lesson');
3408 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
3409 $jumptitle = get_string('unseenpageinbranch', 'lesson');
3410 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
3411 $jumptitle = get_string('previouspage', 'lesson');
3412 } elseif ($jumpto == LESSON_RANDOMPAGE) {
3413 $jumptitle = get_string('randompageinbranch', 'lesson');
3414 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
3415 $jumptitle = get_string('randombranch', 'lesson');
3416 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
3417 $jumptitle = get_string('clusterjump', 'lesson');
3418 } else {
3419 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
3420 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
3423 $jumpnames[$jumpto] = format_string($jumptitle,true);
3426 return $jumpnames[$jumpto];
3430 * Constructor method
3431 * @param object $properties
3432 * @param lesson $lesson
3434 public function __construct($properties, lesson $lesson) {
3435 parent::__construct($properties);
3436 $this->lesson = $lesson;
3440 * Returns the score for the attempt
3441 * This may be overridden by page types that require manual grading
3442 * @param array $answers
3443 * @param object $attempt
3444 * @return int
3446 public function earned_score($answers, $attempt) {
3447 return $answers[$attempt->answerid]->score;
3451 * This is a callback method that can be override and gets called when ever a page
3452 * is viewed
3454 * @param bool $canmanage True if the user has the manage cap
3455 * @return mixed
3457 public function callback_on_view($canmanage) {
3458 return true;
3462 * save editor answers files and update answer record
3464 * @param object $context
3465 * @param int $maxbytes
3466 * @param object $answer
3467 * @param object $answereditor
3468 * @param object $responseeditor
3470 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
3471 global $DB;
3472 if (isset($answereditor['itemid'])) {
3473 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
3474 $context->id, 'mod_lesson', 'page_answers', $answer->id,
3475 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
3476 $answer->answer, null);
3477 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
3479 if (isset($responseeditor['itemid'])) {
3480 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
3481 $context->id, 'mod_lesson', 'page_responses', $answer->id,
3482 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
3483 $answer->response, null);
3484 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
3489 * Rewrite urls in response and optionality answer of a question answer
3491 * @param object $answer
3492 * @param bool $rewriteanswer must rewrite answer
3493 * @return object answer with rewritten urls
3495 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
3496 global $PAGE;
3498 $context = context_module::instance($PAGE->cm->id);
3499 if ($rewriteanswer) {
3500 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
3501 'mod_lesson', 'page_answers', $answer->id);
3503 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
3504 'mod_lesson', 'page_responses', $answer->id);
3506 return $answer;
3510 * Updates a lesson page and its answers within the database
3512 * @param object $properties
3513 * @return bool
3515 public function update($properties, $context = null, $maxbytes = null) {
3516 global $DB, $PAGE;
3517 $answers = $this->get_answers();
3518 $properties->id = $this->properties->id;
3519 $properties->lessonid = $this->lesson->id;
3520 if (empty($properties->qoption)) {
3521 $properties->qoption = '0';
3523 if (empty($context)) {
3524 $context = $PAGE->context;
3526 if ($maxbytes === null) {
3527 $maxbytes = get_user_max_upload_file_size($context);
3529 $properties->timemodified = time();
3530 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
3531 $DB->update_record("lesson_pages", $properties);
3533 // Trigger an event: page updated.
3534 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
3536 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
3537 // These page types have only one answer to save the jump and score.
3538 if (count($answers) > 1) {
3539 $answer = array_shift($answers);
3540 foreach ($answers as $a) {
3541 $DB->delete_record('lesson_answers', array('id' => $a->id));
3543 } else if (count($answers) == 1) {
3544 $answer = array_shift($answers);
3545 } else {
3546 $answer = new stdClass;
3547 $answer->lessonid = $properties->lessonid;
3548 $answer->pageid = $properties->id;
3549 $answer->timecreated = time();
3552 $answer->timemodified = time();
3553 if (isset($properties->jumpto[0])) {
3554 $answer->jumpto = $properties->jumpto[0];
3556 if (isset($properties->score[0])) {
3557 $answer->score = $properties->score[0];
3559 if (!empty($answer->id)) {
3560 $DB->update_record("lesson_answers", $answer->properties());
3561 } else {
3562 $DB->insert_record("lesson_answers", $answer);
3564 } else {
3565 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
3566 if (!array_key_exists($i, $this->answers)) {
3567 $this->answers[$i] = new stdClass;
3568 $this->answers[$i]->lessonid = $this->lesson->id;
3569 $this->answers[$i]->pageid = $this->id;
3570 $this->answers[$i]->timecreated = $this->timecreated;
3573 if (isset($properties->answer_editor[$i])) {
3574 if (is_array($properties->answer_editor[$i])) {
3575 // Multichoice and true/false pages have an HTML editor.
3576 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
3577 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
3578 } else {
3579 // Branch tables, shortanswer and mumerical pages have only a text field.
3580 $this->answers[$i]->answer = $properties->answer_editor[$i];
3581 $this->answers[$i]->answerformat = FORMAT_MOODLE;
3585 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
3586 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
3587 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
3590 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
3591 if (isset($properties->jumpto[$i])) {
3592 $this->answers[$i]->jumpto = $properties->jumpto[$i];
3594 if ($this->lesson->custom && isset($properties->score[$i])) {
3595 $this->answers[$i]->score = $properties->score[$i];
3597 if (!isset($this->answers[$i]->id)) {
3598 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
3599 } else {
3600 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
3603 // Save files in answers and responses.
3604 if (isset($properties->response_editor[$i])) {
3605 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
3606 $properties->answer_editor[$i], $properties->response_editor[$i]);
3607 } else {
3608 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
3609 $properties->answer_editor[$i]);
3612 } else if (isset($this->answers[$i]->id)) {
3613 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
3614 unset($this->answers[$i]);
3618 return true;
3622 * Can be set to true if the page requires a static link to create a new instance
3623 * instead of simply being included in the dropdown
3624 * @param int $previd
3625 * @return bool
3627 public function add_page_link($previd) {
3628 return false;
3632 * Returns true if a page has been viewed before
3634 * @param array|int $param Either an array of pages that have been seen or the
3635 * number of retakes a user has had
3636 * @return bool
3638 public function is_unseen($param) {
3639 global $USER, $DB;
3640 if (is_array($param)) {
3641 $seenpages = $param;
3642 return (!array_key_exists($this->properties->id, $seenpages));
3643 } else {
3644 $nretakes = $param;
3645 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
3646 return true;
3649 return false;
3653 * Checks to see if a page has been answered previously
3654 * @param int $nretakes
3655 * @return bool
3657 public function is_unanswered($nretakes) {
3658 global $DB, $USER;
3659 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
3660 return true;
3662 return false;
3666 * Creates answers within the database for this lesson_page. Usually only ever
3667 * called when creating a new page instance
3668 * @param object $properties
3669 * @return array
3671 public function create_answers($properties) {
3672 global $DB, $PAGE;
3673 // now add the answers
3674 $newanswer = new stdClass;
3675 $newanswer->lessonid = $this->lesson->id;
3676 $newanswer->pageid = $this->properties->id;
3677 $newanswer->timecreated = $this->properties->timecreated;
3679 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3680 $context = context_module::instance($cm->id);
3682 $answers = array();
3684 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
3685 $answer = clone($newanswer);
3687 if (isset($properties->answer_editor[$i])) {
3688 if (is_array($properties->answer_editor[$i])) {
3689 // Multichoice and true/false pages have an HTML editor.
3690 $answer->answer = $properties->answer_editor[$i]['text'];
3691 $answer->answerformat = $properties->answer_editor[$i]['format'];
3692 } else {
3693 // Branch tables, shortanswer and mumerical pages have only a text field.
3694 $answer->answer = $properties->answer_editor[$i];
3695 $answer->answerformat = FORMAT_MOODLE;
3698 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
3699 $answer->response = $properties->response_editor[$i]['text'];
3700 $answer->responseformat = $properties->response_editor[$i]['format'];
3703 if (isset($answer->answer) && $answer->answer != '') {
3704 if (isset($properties->jumpto[$i])) {
3705 $answer->jumpto = $properties->jumpto[$i];
3707 if ($this->lesson->custom && isset($properties->score[$i])) {
3708 $answer->score = $properties->score[$i];
3710 $answer->id = $DB->insert_record("lesson_answers", $answer);
3711 if (isset($properties->response_editor[$i])) {
3712 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
3713 $properties->answer_editor[$i], $properties->response_editor[$i]);
3714 } else {
3715 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
3716 $properties->answer_editor[$i]);
3718 $answers[$answer->id] = new lesson_page_answer($answer);
3719 } else {
3720 break;
3724 $this->answers = $answers;
3725 return $answers;
3729 * This method MUST be overridden by all question page types, or page types that
3730 * wish to score a page.
3732 * The structure of result should always be the same so it is a good idea when
3733 * overriding this method on a page type to call
3734 * <code>
3735 * $result = parent::check_answer();
3736 * </code>
3737 * before modifying it as required.
3739 * @return stdClass
3741 public function check_answer() {
3742 $result = new stdClass;
3743 $result->answerid = 0;
3744 $result->noanswer = false;
3745 $result->correctanswer = false;
3746 $result->isessayquestion = false; // use this to turn off review button on essay questions
3747 $result->response = '';
3748 $result->newpageid = 0; // stay on the page
3749 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
3750 $result->userresponse = null;
3751 $result->feedback = '';
3752 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
3753 $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing.
3754 return $result;
3758 * True if the page uses a custom option
3760 * Should be override and set to true if the page uses a custom option.
3762 * @return bool
3764 public function has_option() {
3765 return false;
3769 * Returns the maximum number of answers for this page given the maximum number
3770 * of answers permitted by the lesson.
3772 * @param int $default
3773 * @return int
3775 public function max_answers($default) {
3776 return $default;
3780 * Returns the properties of this lesson page as an object
3781 * @return stdClass;
3783 public function properties() {
3784 $properties = clone($this->properties);
3785 if ($this->answers === null) {
3786 $this->get_answers();
3788 if (count($this->answers)>0) {
3789 $count = 0;
3790 $qtype = $properties->qtype;
3791 foreach ($this->answers as $answer) {
3792 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
3793 if ($qtype != LESSON_PAGE_MATCHING) {
3794 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
3795 } else {
3796 $properties->{'response_editor['.$count.']'} = $answer->response;
3798 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
3799 $properties->{'score['.$count.']'} = $answer->score;
3800 $count++;
3803 return $properties;
3807 * Returns an array of options to display when choosing the jumpto for a page/answer
3808 * @static
3809 * @param int $pageid
3810 * @param lesson $lesson
3811 * @return array
3813 public static function get_jumptooptions($pageid, lesson $lesson) {
3814 global $DB;
3815 $jump = array();
3816 $jump[0] = get_string("thispage", "lesson");
3817 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
3818 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
3819 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
3821 if ($pageid == 0) {
3822 return $jump;
3825 $pages = $lesson->load_all_pages();
3826 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))) {
3827 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
3828 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
3830 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
3831 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
3833 if (!optional_param('firstpage', 0, PARAM_INT)) {
3834 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
3835 while (true) {
3836 if ($apageid) {
3837 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
3838 $jump[$apageid] = strip_tags(format_string($title,true));
3839 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
3840 } else {
3841 // last page reached
3842 break;
3846 return $jump;
3849 * Returns the contents field for the page properly formatted and with plugin
3850 * file url's converted
3851 * @return string
3853 public function get_contents() {
3854 global $PAGE;
3855 if (!empty($this->properties->contents)) {
3856 if (!isset($this->properties->contentsformat)) {
3857 $this->properties->contentsformat = FORMAT_HTML;
3859 $context = context_module::instance($PAGE->cm->id);
3860 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
3861 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
3862 return format_text($contents, $this->properties->contentsformat,
3863 array('context' => $context, 'noclean' => true,
3864 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
3865 } else {
3866 return '';
3871 * Set to true if this page should display in the menu block
3872 * @return bool
3874 protected function get_displayinmenublock() {
3875 return false;
3879 * Get the string that describes the options of this page type
3880 * @return string
3882 public function option_description_string() {
3883 return '';
3887 * Updates a table with the answers for this page
3888 * @param html_table $table
3889 * @return html_table
3891 public function display_answers(html_table $table) {
3892 $answers = $this->get_answers();
3893 $i = 1;
3894 foreach ($answers as $answer) {
3895 $cells = array();
3896 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
3897 $cells[] = $this->get_jump_name($answer->jumpto);
3898 $table->data[] = new html_table_row($cells);
3899 if ($i === 1){
3900 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
3902 $i++;
3904 return $table;
3908 * Determines if this page should be grayed out on the management/report screens
3909 * @return int 0 or 1
3911 protected function get_grayout() {
3912 return 0;
3916 * Adds stats for this page to the &pagestats object. This should be defined
3917 * for all page types that grade
3918 * @param array $pagestats
3919 * @param int $tries
3920 * @return bool
3922 public function stats(array &$pagestats, $tries) {
3923 return true;
3927 * Formats the answers of this page for a report
3929 * @param object $answerpage
3930 * @param object $answerdata
3931 * @param object $useranswer
3932 * @param array $pagestats
3933 * @param int $i Count of first level answers
3934 * @param int $n Count of second level answers
3935 * @return object The answer page for this
3937 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
3938 $answers = $this->get_answers();
3939 $formattextdefoptions = new stdClass;
3940 $formattextdefoptions->para = false; //I'll use it widely in this page
3941 foreach ($answers as $answer) {
3942 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
3943 $answerdata->answers[] = array($data, "");
3944 $answerpage->answerdata = $answerdata;
3946 return $answerpage;
3950 * Gets an array of the jumps used by the answers of this page
3952 * @return array
3954 public function get_jumps() {
3955 global $DB;
3956 $jumps = array();
3957 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
3958 if ($answers = $this->get_answers()) {
3959 foreach ($answers as $answer) {
3960 $jumps[] = $this->get_jump_name($answer->jumpto);
3962 } else {
3963 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
3965 return $jumps;
3968 * Informs whether this page type require manual grading or not
3969 * @return bool
3971 public function requires_manual_grading() {
3972 return false;
3976 * A callback method that allows a page to override the next page a user will
3977 * see during when this page is being completed.
3978 * @return false|int
3980 public function override_next_page() {
3981 return false;
3985 * This method is used to determine if this page is a valid page
3987 * @param array $validpages
3988 * @param array $pageviews
3989 * @return int The next page id to check
3991 public function valid_page_and_view(&$validpages, &$pageviews) {
3992 $validpages[$this->properties->id] = 1;
3993 return $this->properties->nextpageid;
3997 * Get files from the page area file.
3999 * @param bool $includedirs whether or not include directories
4000 * @param int $updatedsince return files updated since this time
4001 * @return array list of stored_file objects
4002 * @since Moodle 3.2
4004 public function get_files($includedirs = true, $updatedsince = 0) {
4005 $fs = get_file_storage();
4006 return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id,
4007 'itemid, filepath, filename', $includedirs, $updatedsince);
4014 * Class used to represent an answer to a page
4016 * @property int $id The ID of this answer in the database
4017 * @property int $lessonid The ID of the lesson this answer belongs to
4018 * @property int $pageid The ID of the page this answer belongs to
4019 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
4020 * @property int $grade The grade this answer is worth
4021 * @property int $score The score this answer will give
4022 * @property int $flags Used to store options for the answer
4023 * @property int $timecreated A timestamp of when the answer was created
4024 * @property int $timemodified A timestamp of when the answer was modified
4025 * @property string $answer The answer itself
4026 * @property string $response The response the user sees if selecting this answer
4028 * @copyright 2009 Sam Hemelryk
4029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4031 class lesson_page_answer extends lesson_base {
4034 * Loads an page answer from the DB
4036 * @param int $id
4037 * @return lesson_page_answer
4039 public static function load($id) {
4040 global $DB;
4041 $answer = $DB->get_record("lesson_answers", array("id" => $id));
4042 return new lesson_page_answer($answer);
4046 * Given an object of properties and a page created answer(s) and saves them
4047 * in the database.
4049 * @param stdClass $properties
4050 * @param lesson_page $page
4051 * @return array
4053 public static function create($properties, lesson_page $page) {
4054 return $page->create_answers($properties);
4058 * Get files from the answer area file.
4060 * @param bool $includedirs whether or not include directories
4061 * @param int $updatedsince return files updated since this time
4062 * @return array list of stored_file objects
4063 * @since Moodle 3.2
4065 public function get_files($includedirs = true, $updatedsince = 0) {
4067 $lesson = lesson::load($this->properties->lessonid);
4068 $fs = get_file_storage();
4069 $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
4070 'itemid, filepath, filename', $includedirs, $updatedsince);
4071 $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
4072 'itemid, filepath, filename', $includedirs, $updatedsince);
4073 return array_merge($answerfiles, $responsefiles);
4079 * A management class for page types
4081 * This class is responsible for managing the different pages. A manager object can
4082 * be retrieved by calling the following line of code:
4083 * <code>
4084 * $manager = lesson_page_type_manager::get($lesson);
4085 * </code>
4086 * The first time the page type manager is retrieved the it includes all of the
4087 * different page types located in mod/lesson/pagetypes.
4089 * @copyright 2009 Sam Hemelryk
4090 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4092 class lesson_page_type_manager {
4095 * An array of different page type classes
4096 * @var array
4098 protected $types = array();
4101 * Retrieves the lesson page type manager object
4103 * If the object hasn't yet been created it is created here.
4105 * @staticvar lesson_page_type_manager $pagetypemanager
4106 * @param lesson $lesson
4107 * @return lesson_page_type_manager
4109 public static function get(lesson $lesson) {
4110 static $pagetypemanager;
4111 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
4112 $pagetypemanager = new lesson_page_type_manager();
4113 $pagetypemanager->load_lesson_types($lesson);
4115 return $pagetypemanager;
4119 * Finds and loads all lesson page types in mod/lesson/pagetypes
4121 * @param lesson $lesson
4123 public function load_lesson_types(lesson $lesson) {
4124 global $CFG;
4125 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
4126 $dir = dir($basedir);
4127 while (false !== ($entry = $dir->read())) {
4128 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
4129 continue;
4131 require_once($basedir.$entry);
4132 $class = 'lesson_page_type_'.strtok($entry,'.');
4133 if (class_exists($class)) {
4134 $pagetype = new $class(new stdClass, $lesson);
4135 $this->types[$pagetype->typeid] = $pagetype;
4142 * Returns an array of strings to describe the loaded page types
4144 * @param int $type Can be used to return JUST the string for the requested type
4145 * @return array
4147 public function get_page_type_strings($type=null, $special=true) {
4148 $types = array();
4149 foreach ($this->types as $pagetype) {
4150 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
4151 $types[$pagetype->typeid] = $pagetype->typestring;
4154 return $types;
4158 * Returns the basic string used to identify a page type provided with an id
4160 * This string can be used to instantiate or identify the page type class.
4161 * If the page type id is unknown then 'unknown' is returned
4163 * @param int $id
4164 * @return string
4166 public function get_page_type_idstring($id) {
4167 foreach ($this->types as $pagetype) {
4168 if ((int)$pagetype->typeid === (int)$id) {
4169 return $pagetype->idstring;
4172 return 'unknown';
4176 * Loads a page for the provided lesson given it's id
4178 * This function loads a page from the lesson when given both the lesson it belongs
4179 * to as well as the page's id.
4180 * If the page doesn't exist an error is thrown
4182 * @param int $pageid The id of the page to load
4183 * @param lesson $lesson The lesson the page belongs to
4184 * @return lesson_page A class that extends lesson_page
4186 public function load_page($pageid, lesson $lesson) {
4187 global $DB;
4188 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
4189 print_error('cannotfindpages', 'lesson');
4191 $pagetype = get_class($this->types[$page->qtype]);
4192 $page = new $pagetype($page, $lesson);
4193 return $page;
4197 * This function detects errors in the ordering between 2 pages and updates the page records.
4199 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
4200 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
4202 protected function check_page_order($page1, $page2) {
4203 global $DB;
4204 if (empty($page1)) {
4205 if ($page2->prevpageid != 0) {
4206 debugging("***prevpageid of page " . $page2->id . " set to 0***");
4207 $page2->prevpageid = 0;
4208 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
4210 } else if (empty($page2)) {
4211 if ($page1->nextpageid != 0) {
4212 debugging("***nextpageid of page " . $page1->id . " set to 0***");
4213 $page1->nextpageid = 0;
4214 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
4216 } else {
4217 if ($page1->nextpageid != $page2->id) {
4218 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
4219 $page1->nextpageid = $page2->id;
4220 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
4222 if ($page2->prevpageid != $page1->id) {
4223 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
4224 $page2->prevpageid = $page1->id;
4225 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
4231 * This function loads ALL pages that belong to the lesson.
4233 * @param lesson $lesson
4234 * @return array An array of lesson_page_type_*
4236 public function load_all_pages(lesson $lesson) {
4237 global $DB;
4238 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
4239 return array(); // Records returned empty.
4241 foreach ($pages as $key=>$page) {
4242 $pagetype = get_class($this->types[$page->qtype]);
4243 $pages[$key] = new $pagetype($page, $lesson);
4246 $orderedpages = array();
4247 $lastpageid = 0;
4248 $morepages = true;
4249 while ($morepages) {
4250 $morepages = false;
4251 foreach ($pages as $page) {
4252 if ((int)$page->prevpageid === (int)$lastpageid) {
4253 // Check for errors in page ordering and fix them on the fly.
4254 $prevpage = null;
4255 if ($lastpageid !== 0) {
4256 $prevpage = $orderedpages[$lastpageid];
4258 $this->check_page_order($prevpage, $page);
4259 $morepages = true;
4260 $orderedpages[$page->id] = $page;
4261 unset($pages[$page->id]);
4262 $lastpageid = $page->id;
4263 if ((int)$page->nextpageid===0) {
4264 break 2;
4265 } else {
4266 break 1;
4272 // Add remaining pages and fix the nextpageid links for each page.
4273 foreach ($pages as $page) {
4274 // Check for errors in page ordering and fix them on the fly.
4275 $prevpage = null;
4276 if ($lastpageid !== 0) {
4277 $prevpage = $orderedpages[$lastpageid];
4279 $this->check_page_order($prevpage, $page);
4280 $orderedpages[$page->id] = $page;
4281 unset($pages[$page->id]);
4282 $lastpageid = $page->id;
4285 if ($lastpageid !== 0) {
4286 $this->check_page_order($orderedpages[$lastpageid], null);
4289 return $orderedpages;
4293 * Fetches an mform that can be used to create/edit an page
4295 * @param int $type The id for the page type
4296 * @param array $arguments Any arguments to pass to the mform
4297 * @return lesson_add_page_form_base
4299 public function get_page_form($type, $arguments) {
4300 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
4301 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
4302 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
4303 $class = 'lesson_add_page_form_selection';
4304 } else if ($class === 'lesson_add_page_form_unknown') {
4305 $class = 'lesson_add_page_form_selection';
4307 return new $class(null, $arguments);
4311 * Returns an array of links to use as add page links
4312 * @param int $previd The id of the previous page
4313 * @return array
4315 public function get_add_page_type_links($previd) {
4316 global $OUTPUT;
4318 $links = array();
4320 foreach ($this->types as $key=>$type) {
4321 if ($link = $type->add_page_link($previd)) {
4322 $links[$key] = $link;
4326 return $links;