MDL-58415 mod_lesson: Avoid API http redirections
[moodle.git] / mod / lesson / locallib.php
blob5a707a40806c36cc5fc48a28e854a21a11e44a14
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 // Event types.
65 define('LESSON_EVENT_TYPE_OPEN', 'open');
66 define('LESSON_EVENT_TYPE_CLOSE', 'close');
68 //////////////////////////////////////////////////////////////////////////////////////
69 /// Any other lesson functions go here. Each of them must have a name that
70 /// starts with lesson_
72 /**
73 * Checks to see if a LESSON_CLUSTERJUMP or
74 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
76 * This function is only executed when a teacher is
77 * checking the navigation for a lesson.
79 * @param stdClass $lesson Id of the lesson that is to be checked.
80 * @return boolean True or false.
81 **/
82 function lesson_display_teacher_warning($lesson) {
83 global $DB;
85 // get all of the lesson answers
86 $params = array ("lessonid" => $lesson->id);
87 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
88 // no answers, then not using cluster or unseen
89 return false;
91 // just check for the first one that fulfills the requirements
92 foreach ($lessonanswers as $lessonanswer) {
93 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
94 return true;
98 // if no answers use either of the two jumps
99 return false;
103 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
105 * will return the pageid of a random unseen page that is within a branch
107 * @param lesson $lesson
108 * @param int $userid Id of the user.
109 * @param int $pageid Id of the page from which we are jumping.
110 * @return int Id of the next page.
112 function lesson_unseen_question_jump($lesson, $user, $pageid) {
113 global $DB;
115 // get the number of retakes
116 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
117 $retakes = 0;
120 // get all the lesson_attempts aka what the user has seen
121 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
122 foreach($viewedpages as $viewed) {
123 $seenpages[] = $viewed->pageid;
125 } else {
126 $seenpages = array();
129 // get the lesson pages
130 $lessonpages = $lesson->load_all_pages();
132 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
133 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
136 // go up the pages till branch table
137 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
138 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
139 break;
141 $pageid = $lessonpages[$pageid]->prevpageid;
144 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
146 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
147 $unseen = array();
148 foreach($pagesinbranch as $page) {
149 if (!in_array($page->id, $seenpages)) {
150 $unseen[] = $page->id;
154 if(count($unseen) == 0) {
155 if(isset($pagesinbranch)) {
156 $temp = end($pagesinbranch);
157 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
158 } else {
159 // there are no pages inside the branch, so return the next page
160 $nextpage = $lessonpages[$pageid]->nextpageid;
162 if ($nextpage == 0) {
163 return LESSON_EOL;
164 } else {
165 return $nextpage;
167 } else {
168 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
173 * Handles the unseen branch table jump.
175 * @param lesson $lesson
176 * @param int $userid User id.
177 * @return int Will return the page id of a branch table or end of lesson
179 function lesson_unseen_branch_jump($lesson, $userid) {
180 global $DB;
182 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
183 $retakes = 0;
186 if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
187 print_error('cannotfindrecords', 'lesson');
190 // get the lesson pages
191 $lessonpages = $lesson->load_all_pages();
193 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
194 // which is the branch table that starts the unseenbranch function
195 $seen = array();
196 foreach ($seenbranches as $seenbranch) {
197 if (!$seenbranch->flag) {
198 $seen[$seenbranch->pageid] = $seenbranch->pageid;
199 } else {
200 $start = $seenbranch->pageid;
201 break;
204 // this function searches through the lesson pages to find all the branch tables
205 // that follow the flagged branch table
206 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
207 $branchtables = array();
208 while ($pageid != 0) { // grab all of the branch table till eol
209 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
210 $branchtables[] = $lessonpages[$pageid]->id;
212 $pageid = $lessonpages[$pageid]->nextpageid;
214 $unseen = array();
215 foreach ($branchtables as $branchtable) {
216 // load all of the unseen branch tables into unseen
217 if (!array_key_exists($branchtable, $seen)) {
218 $unseen[] = $branchtable;
221 if (count($unseen) > 0) {
222 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
223 } else {
224 return LESSON_EOL; // has viewed all of the branch tables
229 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
231 * @param lesson $lesson
232 * @param int $pageid The id of the page that we are jumping from (?)
233 * @return int The pageid of a random page that is within a branch table
235 function lesson_random_question_jump($lesson, $pageid) {
236 global $DB;
238 // get the lesson pages
239 $params = array ("lessonid" => $lesson->id);
240 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
241 print_error('cannotfindpages', 'lesson');
244 // go up the pages till branch table
245 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
247 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
248 break;
250 $pageid = $lessonpages[$pageid]->prevpageid;
253 // get the pages within the branch
254 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
256 if(count($pagesinbranch) == 0) {
257 // there are no pages inside the branch, so return the next page
258 return $lessonpages[$pageid]->nextpageid;
259 } else {
260 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
265 * Calculates a user's grade for a lesson.
267 * @param object $lesson The lesson that the user is taking.
268 * @param int $retries The attempt number.
269 * @param int $userid Id of the user (optional, default current user).
270 * @return object { nquestions => number of questions answered
271 attempts => number of question attempts
272 total => max points possible
273 earned => points earned by student
274 grade => calculated percentage grade
275 nmanual => number of manually graded questions
276 manualpoints => point value for manually graded questions }
278 function lesson_grade($lesson, $ntries, $userid = 0) {
279 global $USER, $DB;
281 if (empty($userid)) {
282 $userid = $USER->id;
285 // Zero out everything
286 $ncorrect = 0;
287 $nviewed = 0;
288 $score = 0;
289 $nmanual = 0;
290 $manualpoints = 0;
291 $thegrade = 0;
292 $nquestions = 0;
293 $total = 0;
294 $earned = 0;
296 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
297 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
298 userid = :userid AND retry = :retry", $params, "timeseen")) {
299 // group each try with its page
300 $attemptset = array();
301 foreach ($useranswers as $useranswer) {
302 $attemptset[$useranswer->pageid][] = $useranswer;
305 // Drop all attempts that go beyond max attempts for the lesson
306 foreach ($attemptset as $key => $set) {
307 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
310 // get only the pages and their answers that the user answered
311 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
312 array_unshift($parameters, $lesson->id);
313 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
314 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
316 // Number of pages answered
317 $nquestions = count($pages);
319 foreach ($attemptset as $attempts) {
320 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
321 if ($lesson->custom) {
322 $attempt = end($attempts);
323 // If essay question, handle it, otherwise add to score
324 if ($page->requires_manual_grading()) {
325 $useranswerobj = unserialize($attempt->useranswer);
326 if (isset($useranswerobj->score)) {
327 $earned += $useranswerobj->score;
329 $nmanual++;
330 $manualpoints += $answers[$attempt->answerid]->score;
331 } else if (!empty($attempt->answerid)) {
332 $earned += $page->earned_score($answers, $attempt);
334 } else {
335 foreach ($attempts as $attempt) {
336 $earned += $attempt->correct;
338 $attempt = end($attempts); // doesn't matter which one
339 // If essay question, increase numbers
340 if ($page->requires_manual_grading()) {
341 $nmanual++;
342 $manualpoints++;
345 // Number of times answered
346 $nviewed += count($attempts);
349 if ($lesson->custom) {
350 $bestscores = array();
351 // Find the highest possible score per page to get our total
352 foreach ($answers as $answer) {
353 if(!isset($bestscores[$answer->pageid])) {
354 $bestscores[$answer->pageid] = $answer->score;
355 } else if ($bestscores[$answer->pageid] < $answer->score) {
356 $bestscores[$answer->pageid] = $answer->score;
359 $total = array_sum($bestscores);
360 } else {
361 // Check to make sure the student has answered the minimum questions
362 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
363 // Nope, increase number viewed by the amount of unanswered questions
364 $total = $nviewed + ($lesson->minquestions - $nquestions);
365 } else {
366 $total = $nviewed;
371 if ($total) { // not zero
372 $thegrade = round(100 * $earned / $total, 5);
375 // Build the grade information object
376 $gradeinfo = new stdClass;
377 $gradeinfo->nquestions = $nquestions;
378 $gradeinfo->attempts = $nviewed;
379 $gradeinfo->total = $total;
380 $gradeinfo->earned = $earned;
381 $gradeinfo->grade = $thegrade;
382 $gradeinfo->nmanual = $nmanual;
383 $gradeinfo->manualpoints = $manualpoints;
385 return $gradeinfo;
389 * Determines if a user can view the left menu. The determining factor
390 * is whether a user has a grade greater than or equal to the lesson setting
391 * of displayleftif
393 * @param object $lesson Lesson object of the current lesson
394 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
396 function lesson_displayleftif($lesson) {
397 global $CFG, $USER, $DB;
399 if (!empty($lesson->displayleftif)) {
400 // get the current user's max grade for this lesson
401 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
402 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)) {
403 if ($maxgrade->maxgrade < $lesson->displayleftif) {
404 return 0; // turn off the displayleft
406 } else {
407 return 0; // no grades
411 // if we get to here, keep the original state of displayleft lesson setting
412 return $lesson->displayleft;
417 * @param $cm
418 * @param $lesson
419 * @param $page
420 * @return unknown_type
422 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
423 $bc = lesson_menu_block_contents($cm->id, $lesson);
424 if (!empty($bc)) {
425 $regions = $page->blocks->get_regions();
426 $firstregion = reset($regions);
427 $page->blocks->add_fake_block($bc, $firstregion);
430 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
431 if (!empty($bc)) {
432 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
435 if (!empty($timer)) {
436 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
437 if (!empty($bc)) {
438 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
444 * If there is a media file associated with this
445 * lesson, return a block_contents that displays it.
447 * @param int $cmid Course Module ID for this lesson
448 * @param object $lesson Full lesson record object
449 * @return block_contents
451 function lesson_mediafile_block_contents($cmid, $lesson) {
452 global $OUTPUT;
453 if (empty($lesson->mediafile)) {
454 return null;
457 $options = array();
458 $options['menubar'] = 0;
459 $options['location'] = 0;
460 $options['left'] = 5;
461 $options['top'] = 5;
462 $options['scrollbars'] = 1;
463 $options['resizable'] = 1;
464 $options['width'] = $lesson->mediawidth;
465 $options['height'] = $lesson->mediaheight;
467 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
468 $action = new popup_action('click', $link, 'lessonmediafile', $options);
469 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
471 $bc = new block_contents();
472 $bc->title = get_string('linkedmedia', 'lesson');
473 $bc->attributes['class'] = 'mediafile block';
474 $bc->content = $content;
476 return $bc;
480 * If a timed lesson and not a teacher, then
481 * return a block_contents containing the clock.
483 * @param int $cmid Course Module ID for this lesson
484 * @param object $lesson Full lesson record object
485 * @param object $timer Full timer record object
486 * @return block_contents
488 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
489 // Display for timed lessons and for students only
490 $context = context_module::instance($cmid);
491 if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
492 return null;
495 $content = '<div id="lesson-timer">';
496 $content .= $lesson->time_remaining($timer->starttime);
497 $content .= '</div>';
499 $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
500 $page->requires->data_for_js('clocksettings', $clocksettings, true);
501 $page->requires->strings_for_js(array('timeisup'), 'lesson');
502 $page->requires->js('/mod/lesson/timer.js');
503 $page->requires->js_init_call('show_clock');
505 $bc = new block_contents();
506 $bc->title = get_string('timeremaining', 'lesson');
507 $bc->attributes['class'] = 'clock block';
508 $bc->content = $content;
510 return $bc;
514 * If left menu is turned on, then this will
515 * print the menu in a block
517 * @param int $cmid Course Module ID for this lesson
518 * @param lesson $lesson Full lesson record object
519 * @return void
521 function lesson_menu_block_contents($cmid, $lesson) {
522 global $CFG, $DB;
524 if (!$lesson->displayleft) {
525 return null;
528 $pages = $lesson->load_all_pages();
529 foreach ($pages as $page) {
530 if ((int)$page->prevpageid === 0) {
531 $pageid = $page->id;
532 break;
535 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
537 if (!$pageid || !$pages) {
538 return null;
541 $content = '<a href="#maincontent" class="accesshide">' .
542 get_string('skip', 'lesson') .
543 "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
545 while ($pageid != 0) {
546 $page = $pages[$pageid];
548 // Only process branch tables with display turned on
549 if ($page->displayinmenublock && $page->display) {
550 if ($page->id == $currentpageid) {
551 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
552 } else {
553 $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";
557 $pageid = $page->nextpageid;
559 $content .= "</ul>\n</div>\n";
561 $bc = new block_contents();
562 $bc->title = get_string('lessonmenu', 'lesson');
563 $bc->attributes['class'] = 'menu block';
564 $bc->content = $content;
566 return $bc;
570 * Adds header buttons to the page for the lesson
572 * @param object $cm
573 * @param object $context
574 * @param bool $extraeditbuttons
575 * @param int $lessonpageid
577 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
578 global $CFG, $PAGE, $OUTPUT;
579 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
580 if ($lessonpageid === null) {
581 print_error('invalidpageid', 'lesson');
583 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
584 $url = new moodle_url('/mod/lesson/editpage.php', array(
585 'id' => $cm->id,
586 'pageid' => $lessonpageid,
587 'edit' => 1,
588 'returnto' => $PAGE->url->out(false)
590 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
596 * This is a function used to detect media types and generate html code.
598 * @global object $CFG
599 * @global object $PAGE
600 * @param object $lesson
601 * @param object $context
602 * @return string $code the html code of media
604 function lesson_get_media_html($lesson, $context) {
605 global $CFG, $PAGE, $OUTPUT;
606 require_once("$CFG->libdir/resourcelib.php");
608 // get the media file link
609 if (strpos($lesson->mediafile, '://') !== false) {
610 $url = new moodle_url($lesson->mediafile);
611 } else {
612 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
613 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
615 $title = $lesson->mediafile;
617 $clicktoopen = html_writer::link($url, get_string('download'));
619 $mimetype = resourcelib_guess_url_mimetype($url);
621 $extension = resourcelib_get_extension($url->out(false));
623 $mediamanager = core_media_manager::instance($PAGE);
624 $embedoptions = array(
625 core_media_manager::OPTION_TRUSTED => true,
626 core_media_manager::OPTION_BLOCK => true
629 // find the correct type and print it out
630 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
631 $code = resourcelib_embed_image($url, $title);
633 } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
634 // Media (audio/video) file.
635 $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
637 } else {
638 // anything else - just try object tag enlarged as much as possible
639 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
642 return $code;
646 * Logic to happen when a/some group(s) has/have been deleted in a course.
648 * @param int $courseid The course ID.
649 * @param int $groupid The group id if it is known
650 * @return void
652 function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
653 global $DB;
655 $params = array('courseid' => $courseid);
656 if ($groupid) {
657 $params['groupid'] = $groupid;
658 // We just update the group that was deleted.
659 $sql = "SELECT o.id, o.lessonid
660 FROM {lesson_overrides} o
661 JOIN {lesson} lesson ON lesson.id = o.lessonid
662 WHERE lesson.course = :courseid
663 AND o.groupid = :groupid";
664 } else {
665 // No groupid, we update all orphaned group overrides for all lessons in course.
666 $sql = "SELECT o.id, o.lessonid
667 FROM {lesson_overrides} o
668 JOIN {lesson} lesson ON lesson.id = o.lessonid
669 LEFT JOIN {groups} grp ON grp.id = o.groupid
670 WHERE lesson.course = :courseid
671 AND o.groupid IS NOT NULL
672 AND grp.id IS NULL";
674 $records = $DB->get_records_sql_menu($sql, $params);
675 if (!$records) {
676 return; // Nothing to do.
678 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
682 * Return the overview report table and data.
684 * @param lesson $lesson lesson instance
685 * @param mixed $currentgroup false if not group used, 0 for all groups, group id (int) to filter by that groups
686 * @return mixed false if there is no information otherwise html_table and stdClass with the table and data
687 * @since Moodle 3.3
689 function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) {
690 global $DB, $CFG;
691 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
693 $context = $lesson->context;
694 $cm = $lesson->cm;
695 // Count the number of branch and question pages in this lesson.
696 $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE));
697 $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount);
699 // Only load students if there attempts for this lesson.
700 $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id));
701 $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id));
702 $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id));
703 if ($attempts or $branches or $timer) {
704 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
705 list($sort, $sortparams) = users_order_by_sql('u');
707 $params['a1lessonid'] = $lesson->id;
708 $params['b1lessonid'] = $lesson->id;
709 $params['c1lessonid'] = $lesson->id;
710 $ufields = user_picture::fields('u');
711 $sql = "SELECT DISTINCT $ufields
712 FROM {user} u
713 JOIN (
714 SELECT userid, lessonid FROM {lesson_attempts} a1
715 WHERE a1.lessonid = :a1lessonid
716 UNION
717 SELECT userid, lessonid FROM {lesson_branch} b1
718 WHERE b1.lessonid = :b1lessonid
719 UNION
720 SELECT userid, lessonid FROM {lesson_timer} c1
721 WHERE c1.lessonid = :c1lessonid
722 ) a ON u.id = a.userid
723 JOIN ($esql) ue ON ue.id = a.userid
724 ORDER BY $sort";
726 $students = $DB->get_recordset_sql($sql, $params);
727 if (!$students->valid()) {
728 $students->close();
729 return array(false, false);
731 } else {
732 return array(false, false);
735 if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) {
736 $grades = array();
739 if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) {
740 $times = array();
743 // Build an array for output.
744 $studentdata = array();
746 $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen');
747 foreach ($attempts as $attempt) {
748 // if the user is not in the array or if the retry number is not in the sub array, add the data for that try.
749 if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) {
750 // restore/setup defaults
751 $n = 0;
752 $timestart = 0;
753 $timeend = 0;
754 $usergrade = null;
755 $eol = false;
757 // search for the grade record for this try. if not there, the nulls defined above will be used.
758 foreach($grades as $grade) {
759 // check to see if the grade matches the correct user
760 if ($grade->userid == $attempt->userid) {
761 // see if n is = to the retry
762 if ($n == $attempt->retry) {
763 // get grade info
764 $usergrade = round($grade->grade, 2); // round it here so we only have to do it once
765 break;
767 $n++; // if not equal, then increment n
770 $n = 0;
771 // search for the time record for this try. if not there, the nulls defined above will be used.
772 foreach($times as $time) {
773 // check to see if the grade matches the correct user
774 if ($time->userid == $attempt->userid) {
775 // see if n is = to the retry
776 if ($n == $attempt->retry) {
777 // get grade info
778 $timeend = $time->lessontime;
779 $timestart = $time->starttime;
780 $eol = $time->completed;
781 break;
783 $n++; // if not equal, then increment n
787 // build up the array.
788 // this array represents each student and all of their tries at the lesson
789 $studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart,
790 "timeend" => $timeend,
791 "grade" => $usergrade,
792 "end" => $eol,
793 "try" => $attempt->retry,
794 "userid" => $attempt->userid);
797 $attempts->close();
799 $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen');
800 foreach ($branches as $branch) {
801 // If the user is not in the array or if the retry number is not in the sub array, add the data for that try.
802 if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) {
803 // Restore/setup defaults.
804 $n = 0;
805 $timestart = 0;
806 $timeend = 0;
807 $usergrade = null;
808 $eol = false;
809 // Search for the time record for this try. if not there, the nulls defined above will be used.
810 foreach ($times as $time) {
811 // Check to see if the grade matches the correct user.
812 if ($time->userid == $branch->userid) {
813 // See if n is = to the retry.
814 if ($n == $branch->retry) {
815 // Get grade info.
816 $timeend = $time->lessontime;
817 $timestart = $time->starttime;
818 $eol = $time->completed;
819 break;
821 $n++; // If not equal, then increment n.
825 // Build up the array.
826 // This array represents each student and all of their tries at the lesson.
827 $studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart,
828 "timeend" => $timeend,
829 "grade" => $usergrade,
830 "end" => $eol,
831 "try" => $branch->retry,
832 "userid" => $branch->userid);
835 $branches->close();
837 // Need the same thing for timed entries that were not completed.
838 foreach ($times as $time) {
839 $endoflesson = $time->completed;
840 // If the time start is the same with another record then we shouldn't be adding another item to this array.
841 if (isset($studentdata[$time->userid])) {
842 $foundmatch = false;
843 $n = 0;
844 foreach ($studentdata[$time->userid] as $key => $value) {
845 if ($value['timestart'] == $time->starttime) {
846 // Don't add this to the array.
847 $foundmatch = true;
848 break;
851 $n = count($studentdata[$time->userid]) + 1;
852 if (!$foundmatch) {
853 // Add a record.
854 $studentdata[$time->userid][] = array(
855 "timestart" => $time->starttime,
856 "timeend" => $time->lessontime,
857 "grade" => null,
858 "end" => $endoflesson,
859 "try" => $n,
860 "userid" => $time->userid
863 } else {
864 $studentdata[$time->userid][] = array(
865 "timestart" => $time->starttime,
866 "timeend" => $time->lessontime,
867 "grade" => null,
868 "end" => $endoflesson,
869 "try" => 0,
870 "userid" => $time->userid
875 // To store all the data to be returned by the function.
876 $data = new stdClass();
878 // Determine if lesson should have a score.
879 if ($branchcount > 0 AND $questioncount == 0) {
880 // This lesson only contains content pages and is not graded.
881 $data->lessonscored = false;
882 } else {
883 // This lesson is graded.
884 $data->lessonscored = true;
886 // set all the stats variables
887 $data->numofattempts = 0;
888 $data->avescore = 0;
889 $data->avetime = 0;
890 $data->highscore = null;
891 $data->lowscore = null;
892 $data->hightime = null;
893 $data->lowtime = null;
894 $data->students = array();
896 $table = new html_table();
898 // Set up the table object.
899 if ($data->lessonscored) {
900 $table->head = array(get_string('name'), get_string('attempts', 'lesson'), get_string('highscore', 'lesson'));
901 } else {
902 $table->head = array(get_string('name'), get_string('attempts', 'lesson'));
904 $table->align = array('center', 'left', 'left');
905 $table->wrap = array('nowrap', 'nowrap', 'nowrap');
906 $table->attributes['class'] = 'standardtable generaltable';
907 $table->size = array(null, '70%', null);
909 // print out the $studentdata array
910 // going through each student that has attempted the lesson, so, each student should have something to be displayed
911 foreach ($students as $student) {
912 // check to see if the student has attempts to print out
913 if (array_key_exists($student->id, $studentdata)) {
914 // set/reset some variables
915 $attempts = array();
916 $dataforstudent = new stdClass;
917 $dataforstudent->attempts = array();
918 // gather the data for each user attempt
919 $bestgrade = 0;
920 $bestgradefound = false;
921 // $tries holds all the tries/retries a student has done
922 $tries = $studentdata[$student->id];
923 $studentname = fullname($student, true);
925 foreach ($tries as $try) {
926 $dataforstudent->attempts[] = $try;
928 // Start to build up the checkbox and link.
929 if (has_capability('mod/lesson:edit', $context)) {
930 $temp = '<input type="checkbox" id="attempts" name="attempts['.$try['userid'].']['.$try['try'].']" /> ';
931 } else {
932 $temp = '';
935 $temp .= "<a href=\"report.php?id=$cm->id&amp;action=reportdetail&amp;userid=".$try['userid']
936 .'&amp;try='.$try['try'].'" class="lesson-attempt-link">';
937 if ($try["grade"] !== null) { // if null then not done yet
938 // this is what the link does when the user has completed the try
939 $timetotake = $try["timeend"] - $try["timestart"];
941 $temp .= $try["grade"]."%";
942 $bestgradefound = true;
943 if ($try["grade"] > $bestgrade) {
944 $bestgrade = $try["grade"];
946 $temp .= "&nbsp;".userdate($try["timestart"]);
947 $temp .= ",&nbsp;(".format_time($timetotake).")</a>";
948 } else {
949 if ($try["end"]) {
950 // User finished the lesson but has no grade. (Happens when there are only content pages).
951 $temp .= "&nbsp;".userdate($try["timestart"]);
952 $timetotake = $try["timeend"] - $try["timestart"];
953 $temp .= ",&nbsp;(".format_time($timetotake).")</a>";
954 } else {
955 // This is what the link does/looks like when the user has not completed the attempt.
956 $temp .= get_string("notcompleted", "lesson");
957 if ($try['timestart'] !== 0) {
958 // Teacher previews do not track time spent.
959 $temp .= "&nbsp;".userdate($try["timestart"]);
961 $temp .= "</a>";
962 $timetotake = null;
965 // build up the attempts array
966 $attempts[] = $temp;
968 // Run these lines for the stats only if the user finnished the lesson.
969 if ($try["end"]) {
970 // User has completed the lesson.
971 $data->numofattempts++;
972 $data->avetime += $timetotake;
973 if ($timetotake > $data->hightime || $data->hightime == null) {
974 $data->hightime = $timetotake;
976 if ($timetotake < $data->lowtime || $data->lowtime == null) {
977 $data->lowtime = $timetotake;
979 if ($try["grade"] !== null) {
980 // The lesson was scored.
981 $data->avescore += $try["grade"];
982 if ($try["grade"] > $data->highscore || $data->highscore === null) {
983 $data->highscore = $try["grade"];
985 if ($try["grade"] < $data->lowscore || $data->lowscore === null) {
986 $data->lowscore = $try["grade"];
992 // get line breaks in after each attempt
993 $attempts = implode("<br />\n", $attempts);
995 if ($data->lessonscored) {
996 // Add the grade if the lesson is graded.
997 $table->data[] = array($studentname, $attempts, $bestgrade . "%");
998 } else {
999 // This lesson does not have a grade.
1000 $table->data[] = array($studentname, $attempts);
1002 // Add the student data.
1003 $dataforstudent->id = $student->id;
1004 $dataforstudent->fullname = $studentname;
1005 $dataforstudent->bestgrade = $bestgrade;
1006 $data->students[] = $dataforstudent;
1009 $students->close();
1010 if ($data->numofattempts > 0) {
1011 $data->avescore = $data->avescore / $data->numofattempts;
1014 return array($table, $data);
1018 * Return information about one user attempt (including answers)
1019 * @param lesson $lesson lesson instance
1020 * @param int $userid the user id
1021 * @param int $attempt the attempt number
1022 * @return array the user answers (array) and user data stats (object)
1023 * @since Moodle 3.3
1025 function lesson_get_user_detailed_report_data(lesson $lesson, $userid, $attempt) {
1026 global $DB;
1028 $context = $lesson->context;
1029 if (!empty($userid)) {
1030 // Apply overrides.
1031 $lesson->update_effective_access($userid);
1034 $lessonpages = $lesson->load_all_pages();
1035 foreach ($lessonpages as $lessonpage) {
1036 if ($lessonpage->prevpageid == 0) {
1037 $pageid = $lessonpage->id;
1041 // now gather the stats into an object
1042 $firstpageid = $pageid;
1043 $pagestats = array();
1044 while ($pageid != 0) { // EOL
1045 $page = $lessonpages[$pageid];
1046 $params = array ("lessonid" => $lesson->id, "pageid" => $page->id);
1047 if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) {
1048 // get them ready for processing
1049 $orderedanswers = array();
1050 foreach ($allanswers as $singleanswer) {
1051 // ordering them like this, will help to find the single attempt record that we want to keep.
1052 $orderedanswers[$singleanswer->userid][$singleanswer->retry][] = $singleanswer;
1054 // this is foreach user and for each try for that user, keep one attempt record
1055 foreach ($orderedanswers as $orderedanswer) {
1056 foreach($orderedanswer as $tries) {
1057 $page->stats($pagestats, $tries);
1060 } else {
1061 // no one answered yet...
1063 //unset($orderedanswers); initialized above now
1064 $pageid = $page->nextpageid;
1067 $manager = lesson_page_type_manager::get($lesson);
1068 $qtypes = $manager->get_page_type_strings();
1070 $answerpages = array();
1071 $answerpage = "";
1072 $pageid = $firstpageid;
1073 // cycle through all the pages
1074 // foreach page, add to the $answerpages[] array all the data that is needed
1075 // from the question, the users attempt, and the statistics
1076 // grayout pages that the user did not answer and Branch, end of branch, cluster
1077 // and end of cluster pages
1078 while ($pageid != 0) { // EOL
1079 $page = $lessonpages[$pageid];
1080 $answerpage = new stdClass;
1081 $data ='';
1083 $answerdata = new stdClass;
1084 // Set some defaults for the answer data.
1085 $answerdata->score = null;
1086 $answerdata->response = null;
1087 $answerdata->responseformat = FORMAT_PLAIN;
1089 $answerpage->title = format_string($page->title);
1091 $options = new stdClass;
1092 $options->noclean = true;
1093 $options->overflowdiv = true;
1094 $options->context = $context;
1095 $answerpage->contents = format_text($page->contents, $page->contentsformat, $options);
1097 $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string();
1098 $answerpage->grayout = $page->grayout;
1099 $answerpage->context = $context;
1101 if (empty($userid)) {
1102 // there is no userid, so set these vars and display stats.
1103 $answerpage->grayout = 0;
1104 $useranswer = null;
1105 } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) {
1106 // get the user's answer for this page
1107 // need to find the right one
1108 $i = 0;
1109 foreach ($useranswers as $userattempt) {
1110 $useranswer = $userattempt;
1111 $i++;
1112 if ($lesson->maxattempts == $i) {
1113 break; // reached maxattempts, break out
1116 } else {
1117 // user did not answer this page, gray it out and set some nulls
1118 $answerpage->grayout = 1;
1119 $useranswer = null;
1121 $i = 0;
1122 $n = 0;
1123 $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
1124 $pageid = $page->nextpageid;
1127 $userstats = new stdClass;
1128 if (!empty($userid)) {
1129 $params = array("lessonid"=>$lesson->id, "userid"=>$userid);
1131 $alreadycompleted = true;
1133 if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
1134 $userstats->grade = -1;
1135 $userstats->completed = -1;
1136 $alreadycompleted = false;
1137 } else {
1138 $userstats->grade = current($grades);
1139 $userstats->completed = $userstats->grade->completed;
1140 $userstats->grade = round($userstats->grade->grade, 2);
1143 if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
1144 $userstats->timetotake = -1;
1145 $alreadycompleted = false;
1146 } else {
1147 $userstats->timetotake = current($times);
1148 $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime;
1151 if ($alreadycompleted) {
1152 $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid);
1156 return array($answerpages, $userstats);
1161 * Abstract class that page type's MUST inherit from.
1163 * This is the abstract class that ALL add page type forms must extend.
1164 * You will notice that all but two of the methods this class contains are final.
1165 * Essentially the only thing that extending classes can do is extend custom_definition.
1166 * OR if it has a special requirement on creation it can extend construction_override
1168 * @abstract
1169 * @copyright 2009 Sam Hemelryk
1170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1172 abstract class lesson_add_page_form_base extends moodleform {
1175 * This is the classic define that is used to identify this pagetype.
1176 * Will be one of LESSON_*
1177 * @var int
1179 public $qtype;
1182 * The simple string that describes the page type e.g. truefalse, multichoice
1183 * @var string
1185 public $qtypestring;
1188 * An array of options used in the htmleditor
1189 * @var array
1191 protected $editoroptions = array();
1194 * True if this is a standard page of false if it does something special.
1195 * Questions are standard pages, branch tables are not
1196 * @var bool
1198 protected $standard = true;
1201 * Answer format supported by question type.
1203 protected $answerformat = '';
1206 * Response format supported by question type.
1208 protected $responseformat = '';
1211 * Each page type can and should override this to add any custom elements to
1212 * the basic form that they want
1214 public function custom_definition() {}
1217 * Returns answer format used by question type.
1219 public function get_answer_format() {
1220 return $this->answerformat;
1224 * Returns response format used by question type.
1226 public function get_response_format() {
1227 return $this->responseformat;
1231 * Used to determine if this is a standard page or a special page
1232 * @return bool
1234 public final function is_standard() {
1235 return (bool)$this->standard;
1239 * Add the required basic elements to the form.
1241 * This method adds the basic elements to the form including title and contents
1242 * and then calls custom_definition();
1244 public final function definition() {
1245 $mform = $this->_form;
1246 $editoroptions = $this->_customdata['editoroptions'];
1248 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
1250 if (!empty($this->_customdata['returnto'])) {
1251 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
1252 $mform->setType('returnto', PARAM_URL);
1255 $mform->addElement('hidden', 'id');
1256 $mform->setType('id', PARAM_INT);
1258 $mform->addElement('hidden', 'pageid');
1259 $mform->setType('pageid', PARAM_INT);
1261 if ($this->standard === true) {
1262 $mform->addElement('hidden', 'qtype');
1263 $mform->setType('qtype', PARAM_INT);
1265 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1266 $mform->setType('title', PARAM_TEXT);
1267 $mform->addRule('title', get_string('required'), 'required', null, 'client');
1269 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
1270 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
1271 $mform->setType('contents_editor', PARAM_RAW);
1272 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1275 $this->custom_definition();
1277 if ($this->_customdata['edit'] === true) {
1278 $mform->addElement('hidden', 'edit', 1);
1279 $mform->setType('edit', PARAM_BOOL);
1280 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1281 } else if ($this->qtype === 'questiontype') {
1282 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1283 } else {
1284 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1289 * Convenience function: Adds a jumpto select element
1291 * @param string $name
1292 * @param string|null $label
1293 * @param int $selected The page to select by default
1295 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
1296 $title = get_string("jump", "lesson");
1297 if ($label === null) {
1298 $label = $title;
1300 if (is_int($name)) {
1301 $name = "jumpto[$name]";
1303 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
1304 $this->_form->setDefault($name, $selected);
1305 $this->_form->addHelpButton($name, 'jumps', 'lesson');
1309 * Convenience function: Adds a score input element
1311 * @param string $name
1312 * @param string|null $label
1313 * @param mixed $value The default value
1315 protected final function add_score($name, $label=null, $value=null) {
1316 if ($label === null) {
1317 $label = get_string("score", "lesson");
1320 if (is_int($name)) {
1321 $name = "score[$name]";
1323 $this->_form->addElement('text', $name, $label, array('size'=>5));
1324 $this->_form->setType($name, PARAM_INT);
1325 if ($value !== null) {
1326 $this->_form->setDefault($name, $value);
1328 $this->_form->addHelpButton($name, 'score', 'lesson');
1330 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1331 if (!$this->_customdata['lesson']->custom) {
1332 $this->_form->freeze($name);
1337 * Convenience function: Adds an answer editor
1339 * @param int $count The count of the element to add
1340 * @param string $label, null means default
1341 * @param bool $required
1342 * @param string $format
1343 * @return void
1345 protected final function add_answer($count, $label = null, $required = false, $format= '') {
1346 if ($label === null) {
1347 $label = get_string('answer', 'lesson');
1350 if ($format == LESSON_ANSWER_HTML) {
1351 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
1352 array('rows' => '4', 'columns' => '80'),
1353 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1354 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
1355 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1356 } else {
1357 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
1358 array('size' => '50', 'maxlength' => '200'));
1359 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
1362 if ($required) {
1363 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1367 * Convenience function: Adds an response editor
1369 * @param int $count The count of the element to add
1370 * @param string $label, null means default
1371 * @param bool $required
1372 * @return void
1374 protected final function add_response($count, $label = null, $required = false) {
1375 if ($label === null) {
1376 $label = get_string('response', 'lesson');
1378 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
1379 array('rows' => '4', 'columns' => '80'),
1380 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1381 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
1382 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1384 if ($required) {
1385 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1390 * A function that gets called upon init of this object by the calling script.
1392 * This can be used to process an immediate action if required. Currently it
1393 * is only used in special cases by non-standard page types.
1395 * @return bool
1397 public function construction_override($pageid, lesson $lesson) {
1398 return true;
1405 * Class representation of a lesson
1407 * This class is used the interact with, and manage a lesson once instantiated.
1408 * If you need to fetch a lesson object you can do so by calling
1410 * <code>
1411 * lesson::load($lessonid);
1412 * // or
1413 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1414 * $lesson = new lesson($lessonrecord);
1415 * </code>
1417 * The class itself extends lesson_base as all classes within the lesson module should
1419 * These properties are from the database
1420 * @property int $id The id of this lesson
1421 * @property int $course The ID of the course this lesson belongs to
1422 * @property string $name The name of this lesson
1423 * @property int $practice Flag to toggle this as a practice lesson
1424 * @property int $modattempts Toggle to allow the user to go back and review answers
1425 * @property int $usepassword Toggle the use of a password for entry
1426 * @property string $password The password to require users to enter
1427 * @property int $dependency ID of another lesson this lesson is dependent on
1428 * @property string $conditions Conditions of the lesson dependency
1429 * @property int $grade The maximum grade a user can achieve (%)
1430 * @property int $custom Toggle custom scoring on or off
1431 * @property int $ongoing Toggle display of an ongoing score
1432 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1433 * @property int $maxanswers The max number of answers or branches
1434 * @property int $maxattempts The maximum number of attempts a user can record
1435 * @property int $review Toggle use or wrong answer review button
1436 * @property int $nextpagedefault Override the default next page
1437 * @property int $feedback Toggles display of default feedback
1438 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1439 * @property int $maxpages Maximum number of pages this lesson can contain
1440 * @property int $retake Flag to allow users to retake a lesson
1441 * @property int $activitylink Relate this lesson to another lesson
1442 * @property string $mediafile File to pop up to or webpage to display
1443 * @property int $mediaheight Sets the height of the media file popup
1444 * @property int $mediawidth Sets the width of the media file popup
1445 * @property int $mediaclose Toggle display of a media close button
1446 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1447 * @property int $width Width of slideshow
1448 * @property int $height Height of slideshow
1449 * @property string $bgcolor Background colour of slideshow
1450 * @property int $displayleft Display a left menu
1451 * @property int $displayleftif Sets the condition on which the left menu is displayed
1452 * @property int $progressbar Flag to toggle display of a lesson progress bar
1453 * @property int $available Timestamp of when this lesson becomes available
1454 * @property int $deadline Timestamp of when this lesson is no longer available
1455 * @property int $timemodified Timestamp when lesson was last modified
1456 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1458 * These properties are calculated
1459 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1460 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1462 * @copyright 2009 Sam Hemelryk
1463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1465 class lesson extends lesson_base {
1468 * The id of the first page (where prevpageid = 0) gets set and retrieved by
1469 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1470 * @var int
1472 protected $firstpageid = null;
1474 * The id of the last page (where nextpageid = 0) gets set and retrieved by
1475 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1476 * @var int
1478 protected $lastpageid = null;
1480 * An array used to cache the pages associated with this lesson after the first
1481 * time they have been loaded.
1482 * A note to developers: If you are going to be working with MORE than one or
1483 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1484 * in order to save excess database queries.
1485 * @var array An array of lesson_page objects
1487 protected $pages = array();
1489 * Flag that gets set to true once all of the pages associated with the lesson
1490 * have been loaded.
1491 * @var bool
1493 protected $loadedallpages = false;
1496 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1497 * @see get_cm()
1498 * @var stdClass
1500 protected $cm = null;
1503 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1504 * @see get_courserecord()
1505 * @var stdClass
1507 protected $courserecord = null;
1510 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1511 * @see get_context()
1512 * @var stdClass
1514 protected $context = null;
1517 * Constructor method
1519 * @param object $properties
1520 * @param stdClass $cm course module object
1521 * @param stdClass $course course object
1522 * @since Moodle 3.3
1524 public function __construct($properties, $cm = null, $course = null) {
1525 parent::__construct($properties);
1526 $this->cm = $cm;
1527 $this->courserecord = $course;
1531 * Simply generates a lesson object given an array/object of properties
1532 * Overrides {@see lesson_base->create()}
1533 * @static
1534 * @param object|array $properties
1535 * @return lesson
1537 public static function create($properties) {
1538 return new lesson($properties);
1542 * Generates a lesson object from the database given its id
1543 * @static
1544 * @param int $lessonid
1545 * @return lesson
1547 public static function load($lessonid) {
1548 global $DB;
1550 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1551 print_error('invalidcoursemodule');
1553 return new lesson($lesson);
1557 * Deletes this lesson from the database
1559 public function delete() {
1560 global $CFG, $DB;
1561 require_once($CFG->libdir.'/gradelib.php');
1562 require_once($CFG->dirroot.'/calendar/lib.php');
1564 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1565 $context = context_module::instance($cm->id);
1567 $this->delete_all_overrides();
1569 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1570 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1571 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1572 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1573 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1574 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1575 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1576 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1577 foreach($events as $event) {
1578 $event = calendar_event::load($event);
1579 $event->delete();
1583 // Delete files associated with this module.
1584 $fs = get_file_storage();
1585 $fs->delete_area_files($context->id);
1587 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1588 return true;
1592 * Deletes a lesson override from the database and clears any corresponding calendar events
1594 * @param int $overrideid The id of the override being deleted
1595 * @return bool true on success
1597 public function delete_override($overrideid) {
1598 global $CFG, $DB;
1600 require_once($CFG->dirroot . '/calendar/lib.php');
1602 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1604 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1606 // Delete the events.
1607 $conds = array('modulename' => 'lesson',
1608 'instance' => $this->properties->id);
1609 if (isset($override->userid)) {
1610 $conds['userid'] = $override->userid;
1611 } else {
1612 $conds['groupid'] = $override->groupid;
1614 $events = $DB->get_records('event', $conds);
1615 foreach ($events as $event) {
1616 $eventold = calendar_event::load($event);
1617 $eventold->delete();
1620 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1622 // Set the common parameters for one of the events we will be triggering.
1623 $params = array(
1624 'objectid' => $override->id,
1625 'context' => context_module::instance($cm->id),
1626 'other' => array(
1627 'lessonid' => $override->lessonid
1630 // Determine which override deleted event to fire.
1631 if (!empty($override->userid)) {
1632 $params['relateduserid'] = $override->userid;
1633 $event = \mod_lesson\event\user_override_deleted::create($params);
1634 } else {
1635 $params['other']['groupid'] = $override->groupid;
1636 $event = \mod_lesson\event\group_override_deleted::create($params);
1639 // Trigger the override deleted event.
1640 $event->add_record_snapshot('lesson_overrides', $override);
1641 $event->trigger();
1643 return true;
1647 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1649 public function delete_all_overrides() {
1650 global $DB;
1652 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1653 foreach ($overrides as $override) {
1654 $this->delete_override($override->id);
1659 * Updates the lesson properties with override information for a user.
1661 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1662 * then use that otherwise, if there are group-specific overrides, return the most
1663 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1665 * Special case: if there is more than one password that applies to the user, then
1666 * lesson->extrapasswords will contain an array of strings giving the remaining
1667 * passwords.
1669 * @param int $userid The userid.
1671 public function update_effective_access($userid) {
1672 global $DB;
1674 // Check for user override.
1675 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1677 if (!$override) {
1678 $override = new stdClass();
1679 $override->available = null;
1680 $override->deadline = null;
1681 $override->timelimit = null;
1682 $override->review = null;
1683 $override->maxattempts = null;
1684 $override->retake = null;
1685 $override->password = null;
1688 // Check for group overrides.
1689 $groupings = groups_get_user_groups($this->properties->course, $userid);
1691 if (!empty($groupings[0])) {
1692 // Select all overrides that apply to the User's groups.
1693 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1694 $sql = "SELECT * FROM {lesson_overrides}
1695 WHERE groupid $extra AND lessonid = ?";
1696 $params[] = $this->properties->id;
1697 $records = $DB->get_records_sql($sql, $params);
1699 // Combine the overrides.
1700 $availables = array();
1701 $deadlines = array();
1702 $timelimits = array();
1703 $reviews = array();
1704 $attempts = array();
1705 $retakes = array();
1706 $passwords = array();
1708 foreach ($records as $gpoverride) {
1709 if (isset($gpoverride->available)) {
1710 $availables[] = $gpoverride->available;
1712 if (isset($gpoverride->deadline)) {
1713 $deadlines[] = $gpoverride->deadline;
1715 if (isset($gpoverride->timelimit)) {
1716 $timelimits[] = $gpoverride->timelimit;
1718 if (isset($gpoverride->review)) {
1719 $reviews[] = $gpoverride->review;
1721 if (isset($gpoverride->maxattempts)) {
1722 $attempts[] = $gpoverride->maxattempts;
1724 if (isset($gpoverride->retake)) {
1725 $retakes[] = $gpoverride->retake;
1727 if (isset($gpoverride->password)) {
1728 $passwords[] = $gpoverride->password;
1731 // If there is a user override for a setting, ignore the group override.
1732 if (is_null($override->available) && count($availables)) {
1733 $override->available = min($availables);
1735 if (is_null($override->deadline) && count($deadlines)) {
1736 if (in_array(0, $deadlines)) {
1737 $override->deadline = 0;
1738 } else {
1739 $override->deadline = max($deadlines);
1742 if (is_null($override->timelimit) && count($timelimits)) {
1743 if (in_array(0, $timelimits)) {
1744 $override->timelimit = 0;
1745 } else {
1746 $override->timelimit = max($timelimits);
1749 if (is_null($override->review) && count($reviews)) {
1750 $override->review = max($reviews);
1752 if (is_null($override->maxattempts) && count($attempts)) {
1753 $override->maxattempts = max($attempts);
1755 if (is_null($override->retake) && count($retakes)) {
1756 $override->retake = max($retakes);
1758 if (is_null($override->password) && count($passwords)) {
1759 $override->password = array_shift($passwords);
1760 if (count($passwords)) {
1761 $override->extrapasswords = $passwords;
1767 // Merge with lesson defaults.
1768 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1769 foreach ($keys as $key) {
1770 if (isset($override->{$key})) {
1771 $this->properties->{$key} = $override->{$key};
1775 // Special handling of lesson usepassword and password.
1776 if (isset($override->password)) {
1777 if ($override->password == '') {
1778 $this->properties->usepassword = 0;
1779 } else {
1780 $this->properties->usepassword = 1;
1781 $this->properties->password = $override->password;
1782 if (isset($override->extrapasswords)) {
1783 $this->properties->extrapasswords = $override->extrapasswords;
1790 * Fetches messages from the session that may have been set in previous page
1791 * actions.
1793 * <code>
1794 * // Do not call this method directly instead use
1795 * $lesson->messages;
1796 * </code>
1798 * @return array
1800 protected function get_messages() {
1801 global $SESSION;
1803 $messages = array();
1804 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1805 $messages = $SESSION->lesson_messages[$this->properties->id];
1806 unset($SESSION->lesson_messages[$this->properties->id]);
1809 return $messages;
1813 * Get all of the attempts for the current user.
1815 * @param int $retries
1816 * @param bool $correct Optional: only fetch correct attempts
1817 * @param int $pageid Optional: only fetch attempts at the given page
1818 * @param int $userid Optional: defaults to the current user if not set
1819 * @return array|false
1821 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1822 global $USER, $DB;
1823 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1824 if ($correct) {
1825 $params['correct'] = 1;
1827 if ($pageid !== null) {
1828 $params['pageid'] = $pageid;
1830 if ($userid === null) {
1831 $params['userid'] = $USER->id;
1833 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1838 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1840 * @param int $lessonattempt the lesson attempt number (also known as retries)
1841 * @param int $userid the user id to retrieve the data from
1842 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter)
1843 * @param string $fields a comma separated list of fields to return
1844 * @return array of pages
1845 * @since Moodle 3.3
1847 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1848 global $USER, $DB;
1850 if ($userid === null) {
1851 $userid = $USER->id;
1853 $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
1854 return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1858 * Returns the first page for the lesson or false if there isn't one.
1860 * This method should be called via the magic method __get();
1861 * <code>
1862 * $firstpage = $lesson->firstpage;
1863 * </code>
1865 * @return lesson_page|bool Returns the lesson_page specialised object or false
1867 protected function get_firstpage() {
1868 $pages = $this->load_all_pages();
1869 if (count($pages) > 0) {
1870 foreach ($pages as $page) {
1871 if ((int)$page->prevpageid === 0) {
1872 return $page;
1876 return false;
1880 * Returns the last page for the lesson or false if there isn't one.
1882 * This method should be called via the magic method __get();
1883 * <code>
1884 * $lastpage = $lesson->lastpage;
1885 * </code>
1887 * @return lesson_page|bool Returns the lesson_page specialised object or false
1889 protected function get_lastpage() {
1890 $pages = $this->load_all_pages();
1891 if (count($pages) > 0) {
1892 foreach ($pages as $page) {
1893 if ((int)$page->nextpageid === 0) {
1894 return $page;
1898 return false;
1902 * Returns the id of the first page of this lesson. (prevpageid = 0)
1903 * @return int
1905 protected function get_firstpageid() {
1906 global $DB;
1907 if ($this->firstpageid == null) {
1908 if (!$this->loadedallpages) {
1909 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1910 if (!$firstpageid) {
1911 print_error('cannotfindfirstpage', 'lesson');
1913 $this->firstpageid = $firstpageid;
1914 } else {
1915 $firstpage = $this->get_firstpage();
1916 $this->firstpageid = $firstpage->id;
1919 return $this->firstpageid;
1923 * Returns the id of the last page of this lesson. (nextpageid = 0)
1924 * @return int
1926 public function get_lastpageid() {
1927 global $DB;
1928 if ($this->lastpageid == null) {
1929 if (!$this->loadedallpages) {
1930 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1931 if (!$lastpageid) {
1932 print_error('cannotfindlastpage', 'lesson');
1934 $this->lastpageid = $lastpageid;
1935 } else {
1936 $lastpageid = $this->get_lastpage();
1937 $this->lastpageid = $lastpageid->id;
1941 return $this->lastpageid;
1945 * Gets the next page id to display after the one that is provided.
1946 * @param int $nextpageid
1947 * @return bool
1949 public function get_next_page($nextpageid) {
1950 global $USER, $DB;
1951 $allpages = $this->load_all_pages();
1952 if ($this->properties->nextpagedefault) {
1953 // in Flash Card mode...first get number of retakes
1954 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1955 shuffle($allpages);
1956 $found = false;
1957 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1958 foreach ($allpages as $nextpage) {
1959 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1960 $found = true;
1961 break;
1964 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1965 foreach ($allpages as $nextpage) {
1966 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1967 $found = true;
1968 break;
1972 if ($found) {
1973 if ($this->properties->maxpages) {
1974 // check number of pages viewed (in the lesson)
1975 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1976 return LESSON_EOL;
1979 return $nextpage->id;
1982 // In a normal lesson mode
1983 foreach ($allpages as $nextpage) {
1984 if ((int)$nextpage->id === (int)$nextpageid) {
1985 return $nextpage->id;
1988 return LESSON_EOL;
1992 * Sets a message against the session for this lesson that will displayed next
1993 * time the lesson processes messages
1995 * @param string $message
1996 * @param string $class
1997 * @param string $align
1998 * @return bool
2000 public function add_message($message, $class="notifyproblem", $align='center') {
2001 global $SESSION;
2003 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
2004 $SESSION->lesson_messages = array();
2005 $SESSION->lesson_messages[$this->properties->id] = array();
2006 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
2007 $SESSION->lesson_messages[$this->properties->id] = array();
2010 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
2012 return true;
2016 * Check if the lesson is accessible at the present time
2017 * @return bool True if the lesson is accessible, false otherwise
2019 public function is_accessible() {
2020 $available = $this->properties->available;
2021 $deadline = $this->properties->deadline;
2022 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
2026 * Starts the lesson time for the current user
2027 * @return bool Returns true
2029 public function start_timer() {
2030 global $USER, $DB;
2032 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2033 false, MUST_EXIST);
2035 // Trigger lesson started event.
2036 $event = \mod_lesson\event\lesson_started::create(array(
2037 'objectid' => $this->properties()->id,
2038 'context' => context_module::instance($cm->id),
2039 'courseid' => $this->properties()->course
2041 $event->trigger();
2043 $USER->startlesson[$this->properties->id] = true;
2045 $timenow = time();
2046 $startlesson = new stdClass;
2047 $startlesson->lessonid = $this->properties->id;
2048 $startlesson->userid = $USER->id;
2049 $startlesson->starttime = $timenow;
2050 $startlesson->lessontime = $timenow;
2051 if (WS_SERVER) {
2052 $startlesson->timemodifiedoffline = $timenow;
2054 $DB->insert_record('lesson_timer', $startlesson);
2055 if ($this->properties->timelimit) {
2056 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
2058 return true;
2062 * Updates the timer to the current time and returns the new timer object
2063 * @param bool $restart If set to true the timer is restarted
2064 * @param bool $continue If set to true AND $restart=true then the timer
2065 * will continue from a previous attempt
2066 * @return stdClass The new timer
2068 public function update_timer($restart=false, $continue=false, $endreached =false) {
2069 global $USER, $DB;
2071 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2073 // clock code
2074 // get time information for this user
2075 if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
2076 $this->start_timer();
2077 $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
2079 $timer = current($timer); // This will get the latest start time record.
2081 if ($restart) {
2082 if ($continue) {
2083 // continue a previous test, need to update the clock (think this option is disabled atm)
2084 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
2086 // Trigger lesson resumed event.
2087 $event = \mod_lesson\event\lesson_resumed::create(array(
2088 'objectid' => $this->properties->id,
2089 'context' => context_module::instance($cm->id),
2090 'courseid' => $this->properties->course
2092 $event->trigger();
2094 } else {
2095 // starting over, so reset the clock
2096 $timer->starttime = time();
2098 // Trigger lesson restarted event.
2099 $event = \mod_lesson\event\lesson_restarted::create(array(
2100 'objectid' => $this->properties->id,
2101 'context' => context_module::instance($cm->id),
2102 'courseid' => $this->properties->course
2104 $event->trigger();
2109 $timenow = time();
2110 $timer->lessontime = $timenow;
2111 if (WS_SERVER) {
2112 $timer->timemodifiedoffline = $timenow;
2114 $timer->completed = $endreached;
2115 $DB->update_record('lesson_timer', $timer);
2117 // Update completion state.
2118 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2119 false, MUST_EXIST);
2120 $course = get_course($cm->course);
2121 $completion = new completion_info($course);
2122 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
2123 $completion->update_state($cm, COMPLETION_COMPLETE);
2125 return $timer;
2129 * Updates the timer to the current time then stops it by unsetting the user var
2130 * @return bool Returns true
2132 public function stop_timer() {
2133 global $USER, $DB;
2134 unset($USER->startlesson[$this->properties->id]);
2136 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2137 false, MUST_EXIST);
2139 // Trigger lesson ended event.
2140 $event = \mod_lesson\event\lesson_ended::create(array(
2141 'objectid' => $this->properties()->id,
2142 'context' => context_module::instance($cm->id),
2143 'courseid' => $this->properties()->course
2145 $event->trigger();
2147 return $this->update_timer(false, false, true);
2151 * Checks to see if the lesson has pages
2153 public function has_pages() {
2154 global $DB;
2155 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
2156 return ($pagecount>0);
2160 * Returns the link for the related activity
2161 * @return array|false
2163 public function link_for_activitylink() {
2164 global $DB;
2165 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
2166 if ($module) {
2167 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
2168 if ($modname) {
2169 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
2170 if ($instancename) {
2171 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
2172 get_string('activitylinkname', 'lesson', $instancename),
2173 array('class'=>'centerpadded lessonbutton standardbutton'));
2177 return '';
2181 * Loads the requested page.
2183 * This function will return the requested page id as either a specialised
2184 * lesson_page object OR as a generic lesson_page.
2185 * If the page has been loaded previously it will be returned from the pages
2186 * array, otherwise it will be loaded from the database first
2188 * @param int $pageid
2189 * @return lesson_page A lesson_page object or an object that extends it
2191 public function load_page($pageid) {
2192 if (!array_key_exists($pageid, $this->pages)) {
2193 $manager = lesson_page_type_manager::get($this);
2194 $this->pages[$pageid] = $manager->load_page($pageid, $this);
2196 return $this->pages[$pageid];
2200 * Loads ALL of the pages for this lesson
2202 * @return array An array containing all pages from this lesson
2204 public function load_all_pages() {
2205 if (!$this->loadedallpages) {
2206 $manager = lesson_page_type_manager::get($this);
2207 $this->pages = $manager->load_all_pages($this);
2208 $this->loadedallpages = true;
2210 return $this->pages;
2214 * Duplicate the lesson page.
2216 * @param int $pageid Page ID of the page to duplicate.
2217 * @return void.
2219 public function duplicate_page($pageid) {
2220 global $PAGE;
2221 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2222 $context = context_module::instance($cm->id);
2223 // Load the page.
2224 $page = $this->load_page($pageid);
2225 $properties = $page->properties();
2226 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2227 if (!$properties->qoption) {
2228 unset($properties->qoption);
2230 if (!$properties->layout) {
2231 unset($properties->layout);
2233 if (!$properties->display) {
2234 unset($properties->display);
2237 $properties->pageid = $pageid;
2238 // Add text and format into the format required to create a new page.
2239 $properties->contents_editor = array(
2240 'text' => $properties->contents,
2241 'format' => $properties->contentsformat
2243 $answers = $page->get_answers();
2244 // Answers need to be added to $properties.
2245 $i = 0;
2246 $answerids = array();
2247 foreach ($answers as $answer) {
2248 // Needs to be rearranged to work with the create function.
2249 $properties->answer_editor[$i] = array(
2250 'text' => $answer->answer,
2251 'format' => $answer->answerformat
2254 $properties->response_editor[$i] = array(
2255 'text' => $answer->response,
2256 'format' => $answer->responseformat
2258 $answerids[] = $answer->id;
2260 $properties->jumpto[$i] = $answer->jumpto;
2261 $properties->score[$i] = $answer->score;
2263 $i++;
2265 // Create the duplicate page.
2266 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
2267 $newanswers = $newlessonpage->get_answers();
2268 // Copy over the file areas as well.
2269 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
2270 $j = 0;
2271 foreach ($newanswers as $answer) {
2272 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
2273 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
2275 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
2276 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
2278 $j++;
2283 * Copy the files from one page to another.
2285 * @param string $filearea Area that the files are stored.
2286 * @param int $itemid Item ID.
2287 * @param int $newitemid The item ID for the new page.
2288 * @param int $contextid Context ID for this page.
2289 * @return void.
2291 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2292 $fs = get_file_storage();
2293 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2294 foreach ($files as $file) {
2295 $fieldupdates = array('itemid' => $newitemid);
2296 $fs->create_file_from_storedfile($fieldupdates, $file);
2301 * Determines if a jumpto value is correct or not.
2303 * returns true if jumpto page is (logically) after the pageid page or
2304 * if the jumpto value is a special value. Returns false in all other cases.
2306 * @param int $pageid Id of the page from which you are jumping from.
2307 * @param int $jumpto The jumpto number.
2308 * @return boolean True or false after a series of tests.
2310 public function jumpto_is_correct($pageid, $jumpto) {
2311 global $DB;
2313 // first test the special values
2314 if (!$jumpto) {
2315 // same page
2316 return false;
2317 } elseif ($jumpto == LESSON_NEXTPAGE) {
2318 return true;
2319 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2320 return true;
2321 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2322 return true;
2323 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2324 return true;
2325 } elseif ($jumpto == LESSON_EOL) {
2326 return true;
2329 $pages = $this->load_all_pages();
2330 $apageid = $pages[$pageid]->nextpageid;
2331 while ($apageid != 0) {
2332 if ($jumpto == $apageid) {
2333 return true;
2335 $apageid = $pages[$apageid]->nextpageid;
2337 return false;
2341 * Returns the time a user has remaining on this lesson
2342 * @param int $starttime Starttime timestamp
2343 * @return string
2345 public function time_remaining($starttime) {
2346 $timeleft = $starttime + $this->properties->timelimit - time();
2347 $hours = floor($timeleft/3600);
2348 $timeleft = $timeleft - ($hours * 3600);
2349 $minutes = floor($timeleft/60);
2350 $secs = $timeleft - ($minutes * 60);
2352 if ($minutes < 10) {
2353 $minutes = "0$minutes";
2355 if ($secs < 10) {
2356 $secs = "0$secs";
2358 $output = array();
2359 $output[] = $hours;
2360 $output[] = $minutes;
2361 $output[] = $secs;
2362 $output = implode(':', $output);
2363 return $output;
2367 * Interprets LESSON_CLUSTERJUMP jumpto value.
2369 * This will select a page randomly
2370 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
2371 * and the page selected will be a page that has not been viewed already
2372 * and if any pages are within a branch table or end of branch then only 1 page within
2373 * the branch table or end of branch will be randomly selected (sub clustering).
2375 * @param int $pageid Id of the current page from which we are jumping from.
2376 * @param int $userid Id of the user.
2377 * @return int The id of the next page.
2379 public function cluster_jump($pageid, $userid=null) {
2380 global $DB, $USER;
2382 if ($userid===null) {
2383 $userid = $USER->id;
2385 // get the number of retakes
2386 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
2387 $retakes = 0;
2389 // get all the lesson_attempts aka what the user has seen
2390 $seenpages = array();
2391 if ($attempts = $this->get_attempts($retakes)) {
2392 foreach ($attempts as $attempt) {
2393 $seenpages[$attempt->pageid] = $attempt->pageid;
2398 // get the lesson pages
2399 $lessonpages = $this->load_all_pages();
2400 // find the start of the cluster
2401 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2402 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
2403 break;
2405 $pageid = $lessonpages[$pageid]->prevpageid;
2408 $clusterpages = array();
2409 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
2410 $unseen = array();
2411 foreach ($clusterpages as $key=>$cluster) {
2412 // Remove the page if it is in a branch table or is an endofbranch.
2413 if ($this->is_sub_page_of_type($cluster->id,
2414 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
2415 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
2416 unset($clusterpages[$key]);
2417 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
2418 // If branchtable, check to see if any pages inside have been viewed.
2419 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2420 $flag = true;
2421 foreach ($branchpages as $branchpage) {
2422 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
2423 $flag = false;
2426 if ($flag && count($branchpages) > 0) {
2427 // Add branch table.
2428 $unseen[] = $cluster;
2430 } elseif ($cluster->is_unseen($seenpages)) {
2431 $unseen[] = $cluster;
2435 if (count($unseen) > 0) {
2436 // it does not contain elements, then use exitjump, otherwise find out next page/branch
2437 $nextpage = $unseen[rand(0, count($unseen)-1)];
2438 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
2439 // if branch table, then pick a random page inside of it
2440 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2441 return $branchpages[rand(0, count($branchpages)-1)]->id;
2442 } else { // otherwise, return the page's id
2443 return $nextpage->id;
2445 } else {
2446 // seen all there is to see, leave the cluster
2447 if (end($clusterpages)->nextpageid == 0) {
2448 return LESSON_EOL;
2449 } else {
2450 $clusterendid = $pageid;
2451 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2452 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2453 break;
2455 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
2457 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
2458 if ($exitjump == LESSON_NEXTPAGE) {
2459 $exitjump = $lessonpages[$clusterendid]->nextpageid;
2461 if ($exitjump == 0) {
2462 return LESSON_EOL;
2463 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
2464 return $exitjump;
2465 } else {
2466 if (!array_key_exists($exitjump, $lessonpages)) {
2467 $found = false;
2468 foreach ($lessonpages as $page) {
2469 if ($page->id === $clusterendid) {
2470 $found = true;
2471 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2472 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
2473 if ($exitjump == LESSON_NEXTPAGE) {
2474 $exitjump = $lessonpages[$page->id]->nextpageid;
2476 break;
2480 if (!array_key_exists($exitjump, $lessonpages)) {
2481 return LESSON_EOL;
2483 return $exitjump;
2490 * Finds all pages that appear to be a subtype of the provided pageid until
2491 * an end point specified within $ends is encountered or no more pages exist
2493 * @param int $pageid
2494 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2495 * the subtype
2496 * @return array An array of specialised lesson_page objects
2498 public function get_sub_pages_of($pageid, array $ends) {
2499 $lessonpages = $this->load_all_pages();
2500 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
2501 $pages = array();
2503 while (true) {
2504 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2505 break;
2507 $pages[] = $lessonpages[$pageid];
2508 $pageid = $lessonpages[$pageid]->nextpageid;
2511 return $pages;
2515 * Checks to see if the specified page[id] is a subpage of a type specified in
2516 * the $types array, until either there are no more pages of we find a type
2517 * corresponding to that of a type specified in $ends
2519 * @param int $pageid The id of the page to check
2520 * @param array $types An array of types that would signify this page was a subpage
2521 * @param array $ends An array of types that mean this is not a subpage
2522 * @return bool
2524 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2525 $pages = $this->load_all_pages();
2526 $pageid = $pages[$pageid]->prevpageid; // move up one
2528 array_unshift($ends, 0);
2529 // go up the pages till branch table
2530 while (true) {
2531 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2532 return false;
2533 } else if (in_array($pages[$pageid]->qtype, $types)) {
2534 return true;
2536 $pageid = $pages[$pageid]->prevpageid;
2541 * Move a page resorting all other pages.
2543 * @param int $pageid
2544 * @param int $after
2545 * @return void
2547 public function resort_pages($pageid, $after) {
2548 global $CFG;
2550 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2551 $context = context_module::instance($cm->id);
2553 $pages = $this->load_all_pages();
2555 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2556 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2559 $pagetomove = clone($pages[$pageid]);
2560 unset($pages[$pageid]);
2562 $pageids = array();
2563 if ($after === 0) {
2564 $pageids['p0'] = $pageid;
2566 foreach ($pages as $page) {
2567 $pageids[] = $page->id;
2568 if ($page->id == $after) {
2569 $pageids[] = $pageid;
2573 $pageidsref = $pageids;
2574 reset($pageidsref);
2575 $prev = 0;
2576 $next = next($pageidsref);
2577 foreach ($pageids as $pid) {
2578 if ($pid === $pageid) {
2579 $page = $pagetomove;
2580 } else {
2581 $page = $pages[$pid];
2583 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2584 $page->move($next, $prev);
2586 if ($pid === $pageid) {
2587 // We will trigger an event.
2588 $pageupdated = array('next' => $next, 'prev' => $prev);
2592 $prev = $page->id;
2593 $next = next($pageidsref);
2594 if (!$next) {
2595 $next = 0;
2599 // Trigger an event: page moved.
2600 if (!empty($pageupdated)) {
2601 $eventparams = array(
2602 'context' => $context,
2603 'objectid' => $pageid,
2604 'other' => array(
2605 'pagetype' => $page->get_typestring(),
2606 'prevpageid' => $pageupdated['prev'],
2607 'nextpageid' => $pageupdated['next']
2610 $event = \mod_lesson\event\page_moved::create($eventparams);
2611 $event->trigger();
2617 * Return the lesson context object.
2619 * @return stdClass context
2620 * @since Moodle 3.3
2622 public function get_context() {
2623 if ($this->context == null) {
2624 $this->context = context_module::instance($this->get_cm()->id);
2626 return $this->context;
2630 * Set the lesson course module object.
2632 * @param stdClass $cm course module objct
2633 * @since Moodle 3.3
2635 private function set_cm($cm) {
2636 $this->cm = $cm;
2640 * Return the lesson course module object.
2642 * @return stdClass course module
2643 * @since Moodle 3.3
2645 public function get_cm() {
2646 if ($this->cm == null) {
2647 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2649 return $this->cm;
2653 * Set the lesson course object.
2655 * @param stdClass $course course objct
2656 * @since Moodle 3.3
2658 private function set_courserecord($course) {
2659 $this->courserecord = $course;
2663 * Return the lesson course object.
2665 * @return stdClass course
2666 * @since Moodle 3.3
2668 public function get_courserecord() {
2669 global $DB;
2671 if ($this->courserecord == null) {
2672 $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2674 return $this->courserecord;
2678 * Check if the user can manage the lesson activity.
2680 * @return bool true if the user can manage the lesson
2681 * @since Moodle 3.3
2683 public function can_manage() {
2684 return has_capability('mod/lesson:manage', $this->get_context());
2688 * Check if time restriction is applied.
2690 * @return mixed false if there aren't restrictions or an object with the restriction information
2691 * @since Moodle 3.3
2693 public function get_time_restriction_status() {
2694 if ($this->can_manage()) {
2695 return false;
2698 if (!$this->is_accessible()) {
2699 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2700 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2701 } else {
2702 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2704 return (object) $status;
2706 return false;
2710 * Check if password restriction is applied.
2712 * @param string $userpassword the user password to check (if the restriction is set)
2713 * @return mixed false if there aren't restrictions or an object with the restriction information
2714 * @since Moodle 3.3
2716 public function get_password_restriction_status($userpassword) {
2717 global $USER;
2718 if ($this->can_manage()) {
2719 return false;
2722 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2723 $correctpass = false;
2724 if (!empty($userpassword) &&
2725 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2726 // With or without md5 for backward compatibility (MDL-11090).
2727 $correctpass = true;
2728 $USER->lessonloggedin[$this->id] = true;
2729 } else if (isset($this->properties->extrapasswords)) {
2730 // Group overrides may have additional passwords.
2731 foreach ($this->properties->extrapasswords as $password) {
2732 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2733 $correctpass = true;
2734 $USER->lessonloggedin[$this->id] = true;
2738 return !$correctpass;
2740 return false;
2744 * Check if dependencies restrictions are applied.
2746 * @return mixed false if there aren't restrictions or an object with the restriction information
2747 * @since Moodle 3.3
2749 public function get_dependencies_restriction_status() {
2750 global $DB, $USER;
2751 if ($this->can_manage()) {
2752 return false;
2755 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2756 // Lesson exists, so we can proceed.
2757 $conditions = unserialize($this->properties->conditions);
2758 // Assume false for all.
2759 $errors = array();
2760 // Check for the timespent condition.
2761 if ($conditions->timespent) {
2762 $timespent = false;
2763 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2764 // Go through all the times and test to see if any of them satisfy the condition.
2765 foreach ($attempttimes as $attempttime) {
2766 $duration = $attempttime->lessontime - $attempttime->starttime;
2767 if ($conditions->timespent < $duration / 60) {
2768 $timespent = true;
2772 if (!$timespent) {
2773 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2776 // Check for the gradebetterthan condition.
2777 if ($conditions->gradebetterthan) {
2778 $gradebetterthan = false;
2779 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2780 // Go through all the grades and test to see if any of them satisfy the condition.
2781 foreach ($studentgrades as $studentgrade) {
2782 if ($studentgrade->grade >= $conditions->gradebetterthan) {
2783 $gradebetterthan = true;
2787 if (!$gradebetterthan) {
2788 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2791 // Check for the completed condition.
2792 if ($conditions->completed) {
2793 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2794 $errors[] = get_string('completederror', 'lesson');
2797 if (!empty($errors)) {
2798 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2801 return false;
2805 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2807 * @return bool true if is in review mode
2808 * @since Moodle 3.3
2810 public function is_in_review_mode() {
2811 global $DB, $USER;
2813 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2814 if ($userhasgrade && !$this->properties->retake) {
2815 return true;
2817 return false;
2821 * Return the last page the current user saw.
2823 * @param int $retriescount the number of retries for the lesson (the last retry number).
2824 * @return mixed false if the user didn't see the lesson or the last page id
2826 public function get_last_page_seen($retriescount) {
2827 global $DB, $USER;
2829 $lastpageseen = false;
2830 $allattempts = $this->get_attempts($retriescount);
2831 if (!empty($allattempts)) {
2832 $attempt = end($allattempts);
2833 $attemptpage = $this->load_page($attempt->pageid);
2834 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2835 // Convert the jumpto to a proper page id.
2836 if ($jumpto == 0) {
2837 // Check if a question has been incorrectly answered AND no more attempts at it are left.
2838 $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2839 if (count($nattempts) >= $this->properties->maxattempts) {
2840 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2841 } else {
2842 $lastpageseen = $attempt->pageid;
2844 } else if ($jumpto == LESSON_NEXTPAGE) {
2845 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2846 } else if ($jumpto == LESSON_CLUSTERJUMP) {
2847 $lastpageseen = $this->cluster_jump($attempt->pageid);
2848 } else {
2849 $lastpageseen = $jumpto;
2853 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
2854 // In here, user has viewed a branch table.
2855 $lastbranchtable = current($branchtables);
2856 if (count($allattempts) > 0) {
2857 if ($lastbranchtable->timeseen > $attempt->timeseen) {
2858 // This branch table was viewed more recently than the question page.
2859 if (!empty($lastbranchtable->nextpageid)) {
2860 $lastpageseen = $lastbranchtable->nextpageid;
2861 } else {
2862 // Next page ID did not exist prior to MDL-34006.
2863 $lastpageseen = $lastbranchtable->pageid;
2866 } else {
2867 // Has not answered any questions but has viewed a branch table.
2868 if (!empty($lastbranchtable->nextpageid)) {
2869 $lastpageseen = $lastbranchtable->nextpageid;
2870 } else {
2871 // Next page ID did not exist prior to MDL-34006.
2872 $lastpageseen = $lastbranchtable->pageid;
2876 return $lastpageseen;
2880 * Return the number of retries in a lesson for a given user.
2882 * @param int $userid the user id
2883 * @return int the retries count
2884 * @since Moodle 3.3
2886 public function count_user_retries($userid) {
2887 global $DB;
2889 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
2893 * Check if a user left a timed session.
2895 * @param int $retriescount the number of retries for the lesson (the last retry number).
2896 * @return true if the user left the timed session
2897 * @since Moodle 3.3
2899 public function left_during_timed_session($retriescount) {
2900 global $DB, $USER;
2902 $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
2903 return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
2907 * Trigger module viewed event and set the module viewed for completion.
2909 * @since Moodle 3.3
2911 public function set_module_viewed() {
2912 global $CFG;
2913 require_once($CFG->libdir . '/completionlib.php');
2915 // Trigger module viewed event.
2916 $event = \mod_lesson\event\course_module_viewed::create(array(
2917 'objectid' => $this->properties->id,
2918 'context' => $this->get_context()
2920 $event->add_record_snapshot('course_modules', $this->get_cm());
2921 $event->add_record_snapshot('course', $this->get_courserecord());
2922 $event->trigger();
2924 // Mark as viewed.
2925 $completion = new completion_info($this->get_courserecord());
2926 $completion->set_module_viewed($this->get_cm());
2930 * Return the timers in the current lesson for the given user.
2932 * @param int $userid the user id
2933 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
2934 * @param string $fields a comma separated list of fields to return
2935 * @param int $limitfrom return a subset of records, starting at this point (optional).
2936 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
2937 * @return array list of timers for the given user in the lesson
2938 * @since Moodle 3.3
2940 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
2941 global $DB, $USER;
2943 if ($userid === null) {
2944 $userid = $USER->id;
2947 $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
2948 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
2952 * Check if the user is out of time in a timed lesson.
2954 * @param stdClass $timer timer object
2955 * @return bool True if the user is on time, false is the user ran out of time
2956 * @since Moodle 3.3
2958 public function check_time($timer) {
2959 if ($this->properties->timelimit) {
2960 $timeleft = $timer->starttime + $this->properties->timelimit - time();
2961 if ($timeleft <= 0) {
2962 // Out of time.
2963 $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
2964 return false;
2965 } else if ($timeleft < 60) {
2966 // One minute warning.
2967 $this->add_message(get_string('studentoneminwarning', 'lesson'));
2970 return true;
2974 * Add different informative messages to the given page.
2976 * @param lesson_page $page page object
2977 * @param reviewmode $bool whether we are in review mode or not
2978 * @since Moodle 3.3
2980 public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
2981 global $DB, $USER;
2983 if (!$this->can_manage()) {
2984 if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
2985 // Tell student how many questions they have seen, how many are required and their grade.
2986 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2987 $gradeinfo = lesson_grade($this, $ntries);
2988 if ($gradeinfo->attempts) {
2989 if ($gradeinfo->nquestions < $this->properties->minquestions) {
2990 $a = new stdClass;
2991 $a->nquestions = $gradeinfo->nquestions;
2992 $a->minquestions = $this->properties->minquestions;
2993 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
2996 if (!$reviewmode && !$this->properties->retake) {
2997 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
2998 if ($this->properties->grade != GRADE_TYPE_NONE) {
2999 $a = new stdClass;
3000 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3001 $a->total = $this->properties->grade;
3002 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3007 } else {
3008 if ($this->properties->timelimit) {
3009 $this->add_message(get_string('teachertimerwarning', 'lesson'));
3011 if (lesson_display_teacher_warning($this)) {
3012 // This is the warning msg for teachers to inform them that cluster
3013 // and unseen does not work while logged in as a teacher.
3014 $warningvars = new stdClass();
3015 $warningvars->cluster = get_string('clusterjump', 'lesson');
3016 $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
3017 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3023 * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3025 * @return str the ongoing score message
3026 * @since Moodle 3.3
3028 public function get_ongoing_score_message() {
3029 global $USER, $DB;
3031 $context = $this->get_context();
3033 if (has_capability('mod/lesson:manage', $context)) {
3034 return get_string('teacherongoingwarning', 'lesson');
3035 } else {
3036 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3037 if (isset($USER->modattempts[$this->properties->id])) {
3038 $ntries--;
3040 $gradeinfo = lesson_grade($this, $ntries);
3041 $a = new stdClass;
3042 if ($this->properties->custom) {
3043 $a->score = $gradeinfo->earned;
3044 $a->currenthigh = $gradeinfo->total;
3045 return get_string("ongoingcustom", "lesson", $a);
3046 } else {
3047 $a->correct = $gradeinfo->earned;
3048 $a->viewed = $gradeinfo->attempts;
3049 return get_string("ongoingnormal", "lesson", $a);
3055 * Calculate the progress of the current user in the lesson.
3057 * @return int the progress (scale 0-100)
3058 * @since Moodle 3.3
3060 public function calculate_progress() {
3061 global $USER, $DB;
3063 // Check if the user is reviewing the attempt.
3064 if (isset($USER->modattempts[$this->properties->id])) {
3065 return 100;
3068 // All of the lesson pages.
3069 $pages = $this->load_all_pages();
3070 foreach ($pages as $page) {
3071 if ($page->prevpageid == 0) {
3072 $pageid = $page->id; // Find the first page id.
3073 break;
3077 // Current attempt number.
3078 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
3079 $ntries = 0; // May not be necessary.
3082 $viewedpageids = array();
3083 if ($attempts = $this->get_attempts($ntries, false)) {
3084 foreach ($attempts as $attempt) {
3085 $viewedpageids[$attempt->pageid] = $attempt;
3089 $viewedbranches = array();
3090 // Collect all of the branch tables viewed.
3091 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
3092 foreach ($branches as $branch) {
3093 $viewedbranches[$branch->pageid] = $branch;
3095 $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3098 // Filter out the following pages:
3099 // - End of Cluster
3100 // - End of Branch
3101 // - Pages found inside of Clusters
3102 // Do not filter out Cluster Page(s) because we count a cluster as one.
3103 // By keeping the cluster page, we get our 1.
3104 $validpages = array();
3105 while ($pageid != 0) {
3106 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3109 // Progress calculation as a percent.
3110 $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3111 return (int) $progress;
3115 * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3117 * @param int $pageid the given page id
3118 * @param mod_lesson_renderer $lessonoutput the lesson output rendered
3119 * @param bool $reviewmode whether we are in review mode or not
3120 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
3121 * @return array the page object and contents
3122 * @throws moodle_exception
3123 * @since Moodle 3.3
3125 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
3126 global $USER, $CFG;
3128 $page = $this->load_page($pageid);
3129 // Check if the page is of a special type and if so take any nessecary action.
3130 $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3132 // Avoid redirections returning the jump to special page id.
3133 if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3134 return array($newpageid, null, null);
3137 if (is_numeric($newpageid)) {
3138 $page = $this->load_page($newpageid);
3141 // Add different informative messages to the given page.
3142 $this->add_messages_on_page_view($page, $reviewmode);
3144 if (is_array($page->answers) && count($page->answers) > 0) {
3145 // This is for modattempts option. Find the users previous answer to this page,
3146 // and then display it below in answer processing.
3147 if (isset($USER->modattempts[$this->properties->id])) {
3148 $retries = $this->count_user_retries($USER->id);
3149 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
3150 throw new moodle_exception('cannotfindpreattempt', 'lesson');
3152 $attempt = end($attempts);
3153 $USER->modattempts[$this->properties->id] = $attempt;
3154 } else {
3155 $attempt = false;
3157 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3158 } else {
3159 require_once($CFG->dirroot . '/mod/lesson/view_form.php');
3160 $data = new stdClass;
3161 $data->id = $this->get_cm()->id;
3162 $data->pageid = $page->id;
3163 $data->newpageid = $this->get_next_page($page->nextpageid);
3165 $customdata = array(
3166 'title' => $page->title,
3167 'contents' => $page->get_contents()
3169 $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
3170 $mform->set_data($data);
3171 ob_start();
3172 $mform->display();
3173 $lessoncontent = ob_get_contents();
3174 ob_end_clean();
3177 return array($page->id, $page, $lessoncontent);
3181 * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
3183 * @param lesson_page $page lesson page
3184 * @param int $newpageid the new page id
3185 * @return int the real page to jump to (or end of lesson)
3186 * @since Moodle 3.3
3188 public function calculate_new_page_on_jump(lesson_page $page, $newpageid) {
3189 global $USER, $DB;
3191 $canmanage = $this->can_manage();
3193 if (isset($USER->modattempts[$this->properties->id])) {
3194 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
3195 if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) {
3196 // Remember, this session variable holds the pageid of the last page that the user saw.
3197 $newpageid = LESSON_EOL;
3198 } else {
3199 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3200 $nretakes--; // Make sure we are looking at the right try.
3201 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
3202 $found = false;
3203 $temppageid = 0;
3204 // Make sure that the newpageid always defaults to something valid.
3205 $newpageid = LESSON_EOL;
3206 foreach ($attempts as $attempt) {
3207 if ($found && $temppageid != $attempt->pageid) {
3208 // Now try to find the next page, make sure next few attempts do no belong to current page.
3209 $newpageid = $attempt->pageid;
3210 break;
3212 if ($attempt->pageid == $page->id) {
3213 $found = true; // If found current page.
3214 $temppageid = $attempt->pageid;
3218 } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) {
3219 // Going to check to see if the page that the user is going to view next, is a cluster page.
3220 // If so, dont display, go into the cluster.
3221 // The $newpageid > 0 is used to filter out all of the negative code jumps.
3222 $newpage = $this->load_page($newpageid);
3223 if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3224 $newpageid = $overridenewpageid;
3226 } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) {
3227 if ($canmanage) {
3228 if ($page->nextpageid == 0) {
3229 $newpageid = LESSON_EOL;
3230 } else {
3231 $newpageid = $page->nextpageid;
3233 } else {
3234 $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id);
3236 } else if ($newpageid == LESSON_PREVIOUSPAGE) {
3237 $newpageid = $page->prevpageid;
3238 } else if ($newpageid == LESSON_RANDOMPAGE) {
3239 $newpageid = lesson_random_question_jump($this, $page->id);
3240 } else if ($newpageid == LESSON_CLUSTERJUMP) {
3241 if ($canmanage) {
3242 if ($page->nextpageid == 0) { // If teacher, go to next page.
3243 $newpageid = LESSON_EOL;
3244 } else {
3245 $newpageid = $page->nextpageid;
3247 } else {
3248 $newpageid = $this->cluster_jump($page->id);
3250 } else if ($newpageid == 0) {
3251 $newpageid = $page->id;
3252 } else if ($newpageid == LESSON_NEXTPAGE) {
3253 $newpageid = $this->get_next_page($page->nextpageid);
3256 return $newpageid;
3260 * Process page responses.
3262 * @param lesson_page $page page object
3263 * @since Moodle 3.3
3265 public function process_page_responses(lesson_page $page) {
3266 $context = $this->get_context();
3268 // Check the page has answers [MDL-25632].
3269 if (count($page->answers) > 0) {
3270 $result = $page->record_attempt($context);
3271 } else {
3272 // The page has no answers so we will just progress to the next page in the
3273 // sequence (as set by newpageid).
3274 $result = new stdClass;
3275 $result->newpageid = optional_param('newpageid', $page->nextpageid, PARAM_INT);
3276 $result->nodefaultresponse = true;
3279 if ($result->inmediatejump) {
3280 return $result;
3283 $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);
3285 return $result;
3289 * Add different informative messages to the given page.
3291 * @param lesson_page $page page object
3292 * @param stdClass $result the page processing result object
3293 * @param bool $reviewmode whether we are in review mode or not
3294 * @since Moodle 3.3
3296 public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
3298 if ($this->can_manage()) {
3299 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3300 if (lesson_display_teacher_warning($this)) {
3301 $warningvars = new stdClass();
3302 $warningvars->cluster = get_string("clusterjump", "lesson");
3303 $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
3304 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3306 // Inform teacher that s/he will not see the timer.
3307 if ($this->properties->timelimit) {
3308 $lesson->add_message(get_string("teachertimerwarning", "lesson"));
3311 // Report attempts remaining.
3312 if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
3313 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
3318 * Process and return all the information for the end of lesson page.
3320 * @param string $outoftime used to check to see if the student ran out of time
3321 * @return stdclass an object with all the page data ready for rendering
3322 * @since Moodle 3.3
3324 public function process_eol_page($outoftime) {
3325 global $DB, $USER;
3327 $course = $this->get_courserecord();
3328 $cm = $this->get_cm();
3329 $canmanage = $this->can_manage();
3331 // Init all the possible fields and values.
3332 $data = (object) array(
3333 'gradelesson' => true,
3334 'notenoughtimespent' => false,
3335 'numberofpagesviewed' => false,
3336 'youshouldview' => false,
3337 'numberofcorrectanswers' => false,
3338 'displayscorewithessays' => false,
3339 'displayscorewithoutessays' => false,
3340 'yourcurrentgradeisoutof' => false,
3341 'eolstudentoutoftimenoanswers' => false,
3342 'welldone' => false,
3343 'progressbar' => false,
3344 'displayofgrade' => false,
3345 'reviewlesson' => false,
3346 'modattemptsnoteacher' => false,
3347 'activitylink' => false,
3348 'progresscompleted' => false,
3351 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3352 if (isset($USER->modattempts[$this->properties->id])) {
3353 $ntries--; // Need to look at the old attempts :).
3356 $gradeinfo = lesson_grade($this, $ntries);
3357 $data->gradeinfo = $gradeinfo;
3358 if ($this->properties->custom && !$canmanage) {
3359 // Before we calculate the custom score make sure they answered the minimum
3360 // number of questions. We only need to do this for custom scoring as we can
3361 // not get the miniumum score the user should achieve. If we are not using
3362 // custom scoring (so all questions are valued as 1) then we simply check if
3363 // they answered more than the minimum questions, if not, we mark it out of the
3364 // number specified in the minimum questions setting - which is done in lesson_grade().
3365 // Get the number of answers given.
3366 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3367 $data->gradelesson = false;
3368 $a = new stdClass;
3369 $a->nquestions = $gradeinfo->nquestions;
3370 $a->minquestions = $this->properties->minquestions;
3371 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3375 if (!$canmanage) {
3376 if ($data->gradelesson) {
3377 // Store this now before any modifications to pages viewed.
3378 $progresscompleted = $this->calculate_progress();
3380 // Update the clock / get time information for this user.
3381 $this->stop_timer();
3383 // Update completion state.
3384 $completion = new completion_info($course);
3385 if ($completion->is_enabled($cm) && $this->properties->completionendreached) {
3386 $completion->update_state($cm, COMPLETION_COMPLETE);
3389 if ($this->properties->completiontimespent > 0) {
3390 $duration = $DB->get_field_sql(
3391 "SELECT SUM(lessontime - starttime)
3392 FROM {lesson_timer}
3393 WHERE lessonid = :lessonid
3394 AND userid = :userid",
3395 array('userid' => $USER->id, 'lessonid' => $this->properties->id));
3396 if (!$duration) {
3397 $duration = 0;
3400 // If student has not spend enough time in the lesson, display a message.
3401 if ($duration < $this->properties->completiontimespent) {
3402 $a = new stdClass;
3403 $a->timespentraw = $duration;
3404 $a->timespent = format_time($duration);
3405 $a->timerequiredraw = $this->properties->completiontimespent;
3406 $a->timerequired = format_time($this->properties->completiontimespent);
3407 $data->notenoughtimespent = $a;
3411 if ($gradeinfo->attempts) {
3412 if (!$this->properties->custom) {
3413 $data->numberofpagesviewed = $gradeinfo->nquestions;
3414 if ($this->properties->minquestions) {
3415 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3416 $data->youshouldview = $this->properties->minquestions;
3419 $data->numberofcorrectanswers = $gradeinfo->earned;
3421 $a = new stdClass;
3422 $a->score = $gradeinfo->earned;
3423 $a->grade = $gradeinfo->total;
3424 if ($gradeinfo->nmanual) {
3425 $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
3426 $a->essayquestions = $gradeinfo->nmanual;
3427 $data->displayscorewithessays = $a;
3428 } else {
3429 $data->displayscorewithoutessays = $a;
3431 if ($this->properties->grade != GRADE_TYPE_NONE) {
3432 $a = new stdClass;
3433 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3434 $a->total = $this->properties->grade;
3435 $data->yourcurrentgradeisoutof = $a;
3438 $grade = new stdClass();
3439 $grade->lessonid = $this->properties->id;
3440 $grade->userid = $USER->id;
3441 $grade->grade = $gradeinfo->grade;
3442 $grade->completed = time();
3443 if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record.
3444 if (!$grades = $DB->get_records("lesson_grades",
3445 array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
3446 throw new moodle_exception('cannotfindgrade', 'lesson');
3448 $oldgrade = array_shift($grades);
3449 $grade->id = $oldgrade->id;
3450 $DB->update_record("lesson_grades", $grade);
3451 } else {
3452 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3454 } else {
3455 if ($this->properties->timelimit) {
3456 if ($outoftime == 'normal') {
3457 $grade = new stdClass();
3458 $grade->lessonid = $this->properties->id;
3459 $grade->userid = $USER->id;
3460 $grade->grade = 0;
3461 $grade->completed = time();
3462 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3463 $data->eolstudentoutoftimenoanswers = true;
3465 } else {
3466 $data->welldone = true;
3470 // Update central gradebook.
3471 lesson_update_grades($this, $USER->id);
3472 $data->progresscompleted = $progresscompleted;
3474 } else {
3475 // Display for teacher.
3476 if ($this->properties->grade != GRADE_TYPE_NONE) {
3477 $data->displayofgrade = true;
3481 if ($this->properties->modattempts && !$canmanage) {
3482 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3483 // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3484 // to pass to view again. This is slick cause it wont call the empty($pageid) code
3485 // $ntries is decremented above.
3486 if (!$attempts = $this->get_attempts($ntries)) {
3487 $attempts = array();
3488 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id));
3489 } else {
3490 $firstattempt = current($attempts);
3491 $pageid = $firstattempt->pageid;
3492 // If the student wishes to review, need to know the last question page that the student answered.
3493 // This will help to make sure that the student can leave the lesson via pushing the continue button.
3494 $lastattempt = end($attempts);
3495 $USER->modattempts[$this->properties->id] = $lastattempt->pageid;
3497 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid));
3499 $data->reviewlesson = $url;
3500 } else if ($this->properties->modattempts && $canmanage) {
3501 $data->modattemptsnoteacher = true;
3504 if ($this->properties->activitylink) {
3505 $data->activitylink = $this->link_for_activitylink();
3507 return $data;
3513 * Abstract class to provide a core functions to the all lesson classes
3515 * This class should be abstracted by ALL classes with the lesson module to ensure
3516 * that all classes within this module can be interacted with in the same way.
3518 * This class provides the user with a basic properties array that can be fetched
3519 * or set via magic methods, or alternatively by defining methods get_blah() or
3520 * set_blah() within the extending object.
3522 * @copyright 2009 Sam Hemelryk
3523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3525 abstract class lesson_base {
3528 * An object containing properties
3529 * @var stdClass
3531 protected $properties;
3534 * The constructor
3535 * @param stdClass $properties
3537 public function __construct($properties) {
3538 $this->properties = (object)$properties;
3542 * Magic property method
3544 * Attempts to call a set_$key method if one exists otherwise falls back
3545 * to simply set the property
3547 * @param string $key
3548 * @param mixed $value
3550 public function __set($key, $value) {
3551 if (method_exists($this, 'set_'.$key)) {
3552 $this->{'set_'.$key}($value);
3554 $this->properties->{$key} = $value;
3558 * Magic get method
3560 * Attempts to call a get_$key method to return the property and ralls over
3561 * to return the raw property
3563 * @param str $key
3564 * @return mixed
3566 public function __get($key) {
3567 if (method_exists($this, 'get_'.$key)) {
3568 return $this->{'get_'.$key}();
3570 return $this->properties->{$key};
3574 * Stupid PHP needs an isset magic method if you use the get magic method and
3575 * still want empty calls to work.... blah ~!
3577 * @param string $key
3578 * @return bool
3580 public function __isset($key) {
3581 if (method_exists($this, 'get_'.$key)) {
3582 $val = $this->{'get_'.$key}();
3583 return !empty($val);
3585 return !empty($this->properties->{$key});
3588 //NOTE: E_STRICT does not allow to change function signature!
3591 * If implemented should create a new instance, save it in the DB and return it
3593 //public static function create() {}
3595 * If implemented should load an instance from the DB and return it
3597 //public static function load() {}
3599 * Fetches all of the properties of the object
3600 * @return stdClass
3602 public function properties() {
3603 return $this->properties;
3609 * Abstract class representation of a page associated with a lesson.
3611 * This class should MUST be extended by all specialised page types defined in
3612 * mod/lesson/pagetypes/.
3613 * There are a handful of abstract methods that need to be defined as well as
3614 * severl methods that can optionally be defined in order to make the page type
3615 * operate in the desired way
3617 * Database properties
3618 * @property int $id The id of this lesson page
3619 * @property int $lessonid The id of the lesson this page belongs to
3620 * @property int $prevpageid The id of the page before this one
3621 * @property int $nextpageid The id of the next page in the page sequence
3622 * @property int $qtype Identifies the page type of this page
3623 * @property int $qoption Used to record page type specific options
3624 * @property int $layout Used to record page specific layout selections
3625 * @property int $display Used to record page specific display selections
3626 * @property int $timecreated Timestamp for when the page was created
3627 * @property int $timemodified Timestamp for when the page was last modified
3628 * @property string $title The title of this page
3629 * @property string $contents The rich content shown to describe the page
3630 * @property int $contentsformat The format of the contents field
3632 * Calculated properties
3633 * @property-read array $answers An array of answers for this page
3634 * @property-read bool $displayinmenublock Toggles display in the left menu block
3635 * @property-read array $jumps An array containing all the jumps this page uses
3636 * @property-read lesson $lesson The lesson this page belongs to
3637 * @property-read int $type The type of the page [question | structure]
3638 * @property-read typeid The unique identifier for the page type
3639 * @property-read typestring The string that describes this page type
3641 * @abstract
3642 * @copyright 2009 Sam Hemelryk
3643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3645 abstract class lesson_page extends lesson_base {
3648 * A reference to the lesson this page belongs to
3649 * @var lesson
3651 protected $lesson = null;
3653 * Contains the answers to this lesson_page once loaded
3654 * @var null|array
3656 protected $answers = null;
3658 * This sets the type of the page, can be one of the constants defined below
3659 * @var int
3661 protected $type = 0;
3664 * Constants used to identify the type of the page
3666 const TYPE_QUESTION = 0;
3667 const TYPE_STRUCTURE = 1;
3670 * This method should return the integer used to identify the page type within
3671 * the database and throughout code. This maps back to the defines used in 1.x
3672 * @abstract
3673 * @return int
3675 abstract protected function get_typeid();
3677 * This method should return the string that describes the pagetype
3678 * @abstract
3679 * @return string
3681 abstract protected function get_typestring();
3684 * This method gets called to display the page to the user taking the lesson
3685 * @abstract
3686 * @param object $renderer
3687 * @param object $attempt
3688 * @return string
3690 abstract public function display($renderer, $attempt);
3693 * Creates a new lesson_page within the database and returns the correct pagetype
3694 * object to use to interact with the new lesson
3696 * @final
3697 * @static
3698 * @param object $properties
3699 * @param lesson $lesson
3700 * @return lesson_page Specialised object that extends lesson_page
3702 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
3703 global $DB;
3704 $newpage = new stdClass;
3705 $newpage->title = $properties->title;
3706 $newpage->contents = $properties->contents_editor['text'];
3707 $newpage->contentsformat = $properties->contents_editor['format'];
3708 $newpage->lessonid = $lesson->id;
3709 $newpage->timecreated = time();
3710 $newpage->qtype = $properties->qtype;
3711 $newpage->qoption = (isset($properties->qoption))?1:0;
3712 $newpage->layout = (isset($properties->layout))?1:0;
3713 $newpage->display = (isset($properties->display))?1:0;
3714 $newpage->prevpageid = 0; // this is a first page
3715 $newpage->nextpageid = 0; // this is the only page
3717 if ($properties->pageid) {
3718 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
3719 if (!$prevpage) {
3720 print_error('cannotfindpages', 'lesson');
3722 $newpage->prevpageid = $prevpage->id;
3723 $newpage->nextpageid = $prevpage->nextpageid;
3724 } else {
3725 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
3726 if ($nextpage) {
3727 // This is the first page, there are existing pages put this at the start
3728 $newpage->nextpageid = $nextpage->id;
3732 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
3734 $editor = new stdClass;
3735 $editor->id = $newpage->id;
3736 $editor->contents_editor = $properties->contents_editor;
3737 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
3738 $DB->update_record("lesson_pages", $editor);
3740 if ($newpage->prevpageid > 0) {
3741 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
3743 if ($newpage->nextpageid > 0) {
3744 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
3747 $page = lesson_page::load($newpage, $lesson);
3748 $page->create_answers($properties);
3750 // Trigger an event: page created.
3751 $eventparams = array(
3752 'context' => $context,
3753 'objectid' => $newpage->id,
3754 'other' => array(
3755 'pagetype' => $page->get_typestring()
3758 $event = \mod_lesson\event\page_created::create($eventparams);
3759 $snapshot = clone($newpage);
3760 $snapshot->timemodified = 0;
3761 $event->add_record_snapshot('lesson_pages', $snapshot);
3762 $event->trigger();
3764 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
3766 return $page;
3770 * This method loads a page object from the database and returns it as a
3771 * specialised object that extends lesson_page
3773 * @final
3774 * @static
3775 * @param int $id
3776 * @param lesson $lesson
3777 * @return lesson_page Specialised lesson_page object
3779 final public static function load($id, lesson $lesson) {
3780 global $DB;
3782 if (is_object($id) && !empty($id->qtype)) {
3783 $page = $id;
3784 } else {
3785 $page = $DB->get_record("lesson_pages", array("id" => $id));
3786 if (!$page) {
3787 print_error('cannotfindpages', 'lesson');
3790 $manager = lesson_page_type_manager::get($lesson);
3792 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
3793 if (!class_exists($class)) {
3794 $class = 'lesson_page';
3797 return new $class($page, $lesson);
3801 * Deletes a lesson_page from the database as well as any associated records.
3802 * @final
3803 * @return bool
3805 final public function delete() {
3806 global $DB;
3808 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3809 $context = context_module::instance($cm->id);
3811 // Delete files associated with attempts.
3812 $fs = get_file_storage();
3813 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
3814 foreach ($attempts as $attempt) {
3815 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
3819 // Then delete all the associated records...
3820 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
3822 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
3823 // ...now delete the answers...
3824 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
3825 // ..and the page itself
3826 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
3828 // Trigger an event: page deleted.
3829 $eventparams = array(
3830 'context' => $context,
3831 'objectid' => $this->properties->id,
3832 'other' => array(
3833 'pagetype' => $this->get_typestring()
3836 $event = \mod_lesson\event\page_deleted::create($eventparams);
3837 $event->add_record_snapshot('lesson_pages', $this->properties);
3838 $event->trigger();
3840 // Delete files associated with this page.
3841 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
3842 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $this->properties->id);
3843 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $this->properties->id);
3845 // repair the hole in the linkage
3846 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
3847 //This is the only page, no repair needed
3848 } elseif (!$this->properties->prevpageid) {
3849 // this is the first page...
3850 $page = $this->lesson->load_page($this->properties->nextpageid);
3851 $page->move(null, 0);
3852 } elseif (!$this->properties->nextpageid) {
3853 // this is the last page...
3854 $page = $this->lesson->load_page($this->properties->prevpageid);
3855 $page->move(0);
3856 } else {
3857 // page is in the middle...
3858 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
3859 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
3861 $prevpage->move($nextpage->id);
3862 $nextpage->move(null, $prevpage->id);
3864 return true;
3868 * Moves a page by updating its nextpageid and prevpageid values within
3869 * the database
3871 * @final
3872 * @param int $nextpageid
3873 * @param int $prevpageid
3875 final public function move($nextpageid=null, $prevpageid=null) {
3876 global $DB;
3877 if ($nextpageid === null) {
3878 $nextpageid = $this->properties->nextpageid;
3880 if ($prevpageid === null) {
3881 $prevpageid = $this->properties->prevpageid;
3883 $obj = new stdClass;
3884 $obj->id = $this->properties->id;
3885 $obj->prevpageid = $prevpageid;
3886 $obj->nextpageid = $nextpageid;
3887 $DB->update_record('lesson_pages', $obj);
3891 * Returns the answers that are associated with this page in the database
3893 * @final
3894 * @return array
3896 final public function get_answers() {
3897 global $DB;
3898 if ($this->answers === null) {
3899 $this->answers = array();
3900 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
3901 if (!$answers) {
3902 // It is possible that a lesson upgraded from Moodle 1.9 still
3903 // contains questions without any answers [MDL-25632].
3904 // debugging(get_string('cannotfindanswer', 'lesson'));
3905 return array();
3907 foreach ($answers as $answer) {
3908 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
3911 return $this->answers;
3915 * Returns the lesson this page is associated with
3916 * @final
3917 * @return lesson
3919 final protected function get_lesson() {
3920 return $this->lesson;
3924 * Returns the type of page this is. Not to be confused with page type
3925 * @final
3926 * @return int
3928 final protected function get_type() {
3929 return $this->type;
3933 * Records an attempt at this page
3935 * @final
3936 * @global moodle_database $DB
3937 * @param stdClass $context
3938 * @return stdClass Returns the result of the attempt
3940 final public function record_attempt($context) {
3941 global $DB, $USER, $OUTPUT, $PAGE;
3944 * This should be overridden by each page type to actually check the response
3945 * against what ever custom criteria they have defined
3947 $result = $this->check_answer();
3949 // Processes inmediate jumps.
3950 if ($result->inmediatejump) {
3951 return $result;
3954 $result->attemptsremaining = 0;
3955 $result->maxattemptsreached = false;
3957 if ($result->noanswer) {
3958 $result->newpageid = $this->properties->id; // display same page again
3959 $result->feedback = get_string('noanswer', 'lesson');
3960 } else {
3961 if (!has_capability('mod/lesson:manage', $context)) {
3962 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
3964 // Get the number of attempts that have been made on this question for this student and retake,
3965 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
3966 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
3968 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
3969 if ($nattempts >= $this->lesson->maxattempts) {
3970 $result->maxattemptsreached = true;
3971 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
3972 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
3973 return $result;
3976 // record student's attempt
3977 $attempt = new stdClass;
3978 $attempt->lessonid = $this->lesson->id;
3979 $attempt->pageid = $this->properties->id;
3980 $attempt->userid = $USER->id;
3981 $attempt->answerid = $result->answerid;
3982 $attempt->retry = $nretakes;
3983 $attempt->correct = $result->correctanswer;
3984 if($result->userresponse !== null) {
3985 $attempt->useranswer = $result->userresponse;
3988 $attempt->timeseen = time();
3989 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
3990 $userisreviewing = false;
3991 if (isset($USER->modattempts[$this->lesson->id])) {
3992 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
3993 $userisreviewing = true;
3996 // Only insert a record if we are not reviewing the lesson.
3997 if (!$userisreviewing) {
3998 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
3999 $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
4000 // Trigger an event: question answered.
4001 $eventparams = array(
4002 'context' => context_module::instance($PAGE->cm->id),
4003 'objectid' => $this->properties->id,
4004 'other' => array(
4005 'pagetype' => $this->get_typestring()
4008 $event = \mod_lesson\event\question_answered::create($eventparams);
4009 $event->add_record_snapshot('lesson_attempts', $attempt);
4010 $event->trigger();
4012 // Increase the number of attempts made.
4013 $nattempts++;
4016 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
4017 // displaying of message(s) is at the end of page for more ergonomic display
4018 if (!$result->correctanswer && ($result->newpageid == 0)) {
4019 // retreive the number of attempts left counter for displaying at bottom of feedback page
4020 if ($nattempts >= $this->lesson->maxattempts) {
4021 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4022 $result->maxattemptsreached = true;
4024 $result->newpageid = LESSON_NEXTPAGE;
4025 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4026 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
4031 // Determine default feedback if necessary
4032 if (empty($result->response)) {
4033 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
4034 // These conditions have been met:
4035 // 1. The lesson manager has not supplied feedback to the student
4036 // 2. Not displaying default feedback
4037 // 3. The user did provide an answer
4038 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
4040 $result->nodefaultresponse = true; // This will cause a redirect below
4041 } else if ($result->isessayquestion) {
4042 $result->response = get_string('defaultessayresponse', 'lesson');
4043 } else if ($result->correctanswer) {
4044 $result->response = get_string('thatsthecorrectanswer', 'lesson');
4045 } else {
4046 $result->response = get_string('thatsthewronganswer', 'lesson');
4050 if ($result->response) {
4051 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
4052 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4053 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
4054 if ($qattempts == 1) {
4055 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
4056 } else {
4057 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
4059 } else {
4060 $result->feedback = '';
4062 $class = 'response';
4063 if ($result->correctanswer) {
4064 $class .= ' correct'; // CSS over-ride this if they exist (!important).
4065 } else if (!$result->isessayquestion) {
4066 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
4068 $options = new stdClass;
4069 $options->noclean = true;
4070 $options->para = true;
4071 $options->overflowdiv = true;
4072 $options->context = $context;
4074 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
4075 'generalbox boxaligncenter');
4076 if (isset($result->studentanswerformat)) {
4077 // This is the student's answer so it should be cleaned.
4078 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
4079 array('context' => $context, 'para' => true));
4080 } else {
4081 $studentanswer = format_string($result->studentanswer);
4083 $result->feedback .= '<div class="correctanswer generalbox"><em>'
4084 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
4085 if (isset($result->responseformat)) {
4086 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
4087 'mod_lesson', 'page_responses', $result->answerid);
4088 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
4089 , $class);
4090 } else {
4091 $result->feedback .= $OUTPUT->box($result->response, $class);
4093 $result->feedback .= '</div>';
4097 return $result;
4101 * Returns the string for a jump name
4103 * @final
4104 * @param int $jumpto Jump code or page ID
4105 * @return string
4107 final protected function get_jump_name($jumpto) {
4108 global $DB;
4109 static $jumpnames = array();
4111 if (!array_key_exists($jumpto, $jumpnames)) {
4112 if ($jumpto == LESSON_THISPAGE) {
4113 $jumptitle = get_string('thispage', 'lesson');
4114 } elseif ($jumpto == LESSON_NEXTPAGE) {
4115 $jumptitle = get_string('nextpage', 'lesson');
4116 } elseif ($jumpto == LESSON_EOL) {
4117 $jumptitle = get_string('endoflesson', 'lesson');
4118 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
4119 $jumptitle = get_string('unseenpageinbranch', 'lesson');
4120 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
4121 $jumptitle = get_string('previouspage', 'lesson');
4122 } elseif ($jumpto == LESSON_RANDOMPAGE) {
4123 $jumptitle = get_string('randompageinbranch', 'lesson');
4124 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
4125 $jumptitle = get_string('randombranch', 'lesson');
4126 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
4127 $jumptitle = get_string('clusterjump', 'lesson');
4128 } else {
4129 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
4130 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
4133 $jumpnames[$jumpto] = format_string($jumptitle,true);
4136 return $jumpnames[$jumpto];
4140 * Constructor method
4141 * @param object $properties
4142 * @param lesson $lesson
4144 public function __construct($properties, lesson $lesson) {
4145 parent::__construct($properties);
4146 $this->lesson = $lesson;
4150 * Returns the score for the attempt
4151 * This may be overridden by page types that require manual grading
4152 * @param array $answers
4153 * @param object $attempt
4154 * @return int
4156 public function earned_score($answers, $attempt) {
4157 return $answers[$attempt->answerid]->score;
4161 * This is a callback method that can be override and gets called when ever a page
4162 * is viewed
4164 * @param bool $canmanage True if the user has the manage cap
4165 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
4166 * @return mixed
4168 public function callback_on_view($canmanage, $redirect = true) {
4169 return true;
4173 * save editor answers files and update answer record
4175 * @param object $context
4176 * @param int $maxbytes
4177 * @param object $answer
4178 * @param object $answereditor
4179 * @param object $responseeditor
4181 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
4182 global $DB;
4183 if (isset($answereditor['itemid'])) {
4184 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
4185 $context->id, 'mod_lesson', 'page_answers', $answer->id,
4186 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4187 $answer->answer, null);
4188 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
4190 if (isset($responseeditor['itemid'])) {
4191 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
4192 $context->id, 'mod_lesson', 'page_responses', $answer->id,
4193 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4194 $answer->response, null);
4195 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
4200 * Rewrite urls in response and optionality answer of a question answer
4202 * @param object $answer
4203 * @param bool $rewriteanswer must rewrite answer
4204 * @return object answer with rewritten urls
4206 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
4207 global $PAGE;
4209 $context = context_module::instance($PAGE->cm->id);
4210 if ($rewriteanswer) {
4211 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
4212 'mod_lesson', 'page_answers', $answer->id);
4214 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
4215 'mod_lesson', 'page_responses', $answer->id);
4217 return $answer;
4221 * Updates a lesson page and its answers within the database
4223 * @param object $properties
4224 * @return bool
4226 public function update($properties, $context = null, $maxbytes = null) {
4227 global $DB, $PAGE;
4228 $answers = $this->get_answers();
4229 $properties->id = $this->properties->id;
4230 $properties->lessonid = $this->lesson->id;
4231 if (empty($properties->qoption)) {
4232 $properties->qoption = '0';
4234 if (empty($context)) {
4235 $context = $PAGE->context;
4237 if ($maxbytes === null) {
4238 $maxbytes = get_user_max_upload_file_size($context);
4240 $properties->timemodified = time();
4241 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
4242 $DB->update_record("lesson_pages", $properties);
4244 // Trigger an event: page updated.
4245 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
4247 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
4248 // These page types have only one answer to save the jump and score.
4249 if (count($answers) > 1) {
4250 $answer = array_shift($answers);
4251 foreach ($answers as $a) {
4252 $DB->delete_record('lesson_answers', array('id' => $a->id));
4254 } else if (count($answers) == 1) {
4255 $answer = array_shift($answers);
4256 } else {
4257 $answer = new stdClass;
4258 $answer->lessonid = $properties->lessonid;
4259 $answer->pageid = $properties->id;
4260 $answer->timecreated = time();
4263 $answer->timemodified = time();
4264 if (isset($properties->jumpto[0])) {
4265 $answer->jumpto = $properties->jumpto[0];
4267 if (isset($properties->score[0])) {
4268 $answer->score = $properties->score[0];
4270 if (!empty($answer->id)) {
4271 $DB->update_record("lesson_answers", $answer->properties());
4272 } else {
4273 $DB->insert_record("lesson_answers", $answer);
4275 } else {
4276 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
4277 if (!array_key_exists($i, $this->answers)) {
4278 $this->answers[$i] = new stdClass;
4279 $this->answers[$i]->lessonid = $this->lesson->id;
4280 $this->answers[$i]->pageid = $this->id;
4281 $this->answers[$i]->timecreated = $this->timecreated;
4284 if (isset($properties->answer_editor[$i])) {
4285 if (is_array($properties->answer_editor[$i])) {
4286 // Multichoice and true/false pages have an HTML editor.
4287 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
4288 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
4289 } else {
4290 // Branch tables, shortanswer and mumerical pages have only a text field.
4291 $this->answers[$i]->answer = $properties->answer_editor[$i];
4292 $this->answers[$i]->answerformat = FORMAT_MOODLE;
4296 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4297 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
4298 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
4301 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
4302 if (isset($properties->jumpto[$i])) {
4303 $this->answers[$i]->jumpto = $properties->jumpto[$i];
4305 if ($this->lesson->custom && isset($properties->score[$i])) {
4306 $this->answers[$i]->score = $properties->score[$i];
4308 if (!isset($this->answers[$i]->id)) {
4309 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
4310 } else {
4311 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
4314 // Save files in answers and responses.
4315 if (isset($properties->response_editor[$i])) {
4316 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4317 $properties->answer_editor[$i], $properties->response_editor[$i]);
4318 } else {
4319 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4320 $properties->answer_editor[$i]);
4323 } else if (isset($this->answers[$i]->id)) {
4324 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
4325 unset($this->answers[$i]);
4329 return true;
4333 * Can be set to true if the page requires a static link to create a new instance
4334 * instead of simply being included in the dropdown
4335 * @param int $previd
4336 * @return bool
4338 public function add_page_link($previd) {
4339 return false;
4343 * Returns true if a page has been viewed before
4345 * @param array|int $param Either an array of pages that have been seen or the
4346 * number of retakes a user has had
4347 * @return bool
4349 public function is_unseen($param) {
4350 global $USER, $DB;
4351 if (is_array($param)) {
4352 $seenpages = $param;
4353 return (!array_key_exists($this->properties->id, $seenpages));
4354 } else {
4355 $nretakes = $param;
4356 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
4357 return true;
4360 return false;
4364 * Checks to see if a page has been answered previously
4365 * @param int $nretakes
4366 * @return bool
4368 public function is_unanswered($nretakes) {
4369 global $DB, $USER;
4370 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
4371 return true;
4373 return false;
4377 * Creates answers within the database for this lesson_page. Usually only ever
4378 * called when creating a new page instance
4379 * @param object $properties
4380 * @return array
4382 public function create_answers($properties) {
4383 global $DB, $PAGE;
4384 // now add the answers
4385 $newanswer = new stdClass;
4386 $newanswer->lessonid = $this->lesson->id;
4387 $newanswer->pageid = $this->properties->id;
4388 $newanswer->timecreated = $this->properties->timecreated;
4390 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
4391 $context = context_module::instance($cm->id);
4393 $answers = array();
4395 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
4396 $answer = clone($newanswer);
4398 if (isset($properties->answer_editor[$i])) {
4399 if (is_array($properties->answer_editor[$i])) {
4400 // Multichoice and true/false pages have an HTML editor.
4401 $answer->answer = $properties->answer_editor[$i]['text'];
4402 $answer->answerformat = $properties->answer_editor[$i]['format'];
4403 } else {
4404 // Branch tables, shortanswer and mumerical pages have only a text field.
4405 $answer->answer = $properties->answer_editor[$i];
4406 $answer->answerformat = FORMAT_MOODLE;
4409 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4410 $answer->response = $properties->response_editor[$i]['text'];
4411 $answer->responseformat = $properties->response_editor[$i]['format'];
4414 if (isset($answer->answer) && $answer->answer != '') {
4415 if (isset($properties->jumpto[$i])) {
4416 $answer->jumpto = $properties->jumpto[$i];
4418 if ($this->lesson->custom && isset($properties->score[$i])) {
4419 $answer->score = $properties->score[$i];
4421 $answer->id = $DB->insert_record("lesson_answers", $answer);
4422 if (isset($properties->response_editor[$i])) {
4423 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4424 $properties->answer_editor[$i], $properties->response_editor[$i]);
4425 } else {
4426 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4427 $properties->answer_editor[$i]);
4429 $answers[$answer->id] = new lesson_page_answer($answer);
4430 } else {
4431 break;
4435 $this->answers = $answers;
4436 return $answers;
4440 * This method MUST be overridden by all question page types, or page types that
4441 * wish to score a page.
4443 * The structure of result should always be the same so it is a good idea when
4444 * overriding this method on a page type to call
4445 * <code>
4446 * $result = parent::check_answer();
4447 * </code>
4448 * before modifying it as required.
4450 * @return stdClass
4452 public function check_answer() {
4453 $result = new stdClass;
4454 $result->answerid = 0;
4455 $result->noanswer = false;
4456 $result->correctanswer = false;
4457 $result->isessayquestion = false; // use this to turn off review button on essay questions
4458 $result->response = '';
4459 $result->newpageid = 0; // stay on the page
4460 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
4461 $result->userresponse = null;
4462 $result->feedback = '';
4463 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
4464 $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing.
4465 return $result;
4469 * True if the page uses a custom option
4471 * Should be override and set to true if the page uses a custom option.
4473 * @return bool
4475 public function has_option() {
4476 return false;
4480 * Returns the maximum number of answers for this page given the maximum number
4481 * of answers permitted by the lesson.
4483 * @param int $default
4484 * @return int
4486 public function max_answers($default) {
4487 return $default;
4491 * Returns the properties of this lesson page as an object
4492 * @return stdClass;
4494 public function properties() {
4495 $properties = clone($this->properties);
4496 if ($this->answers === null) {
4497 $this->get_answers();
4499 if (count($this->answers)>0) {
4500 $count = 0;
4501 $qtype = $properties->qtype;
4502 foreach ($this->answers as $answer) {
4503 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
4504 if ($qtype != LESSON_PAGE_MATCHING) {
4505 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
4506 } else {
4507 $properties->{'response_editor['.$count.']'} = $answer->response;
4509 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
4510 $properties->{'score['.$count.']'} = $answer->score;
4511 $count++;
4514 return $properties;
4518 * Returns an array of options to display when choosing the jumpto for a page/answer
4519 * @static
4520 * @param int $pageid
4521 * @param lesson $lesson
4522 * @return array
4524 public static function get_jumptooptions($pageid, lesson $lesson) {
4525 global $DB;
4526 $jump = array();
4527 $jump[0] = get_string("thispage", "lesson");
4528 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
4529 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
4530 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
4532 if ($pageid == 0) {
4533 return $jump;
4536 $pages = $lesson->load_all_pages();
4537 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))) {
4538 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
4539 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
4541 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
4542 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
4544 if (!optional_param('firstpage', 0, PARAM_INT)) {
4545 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
4546 while (true) {
4547 if ($apageid) {
4548 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
4549 $jump[$apageid] = strip_tags(format_string($title,true));
4550 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
4551 } else {
4552 // last page reached
4553 break;
4557 return $jump;
4560 * Returns the contents field for the page properly formatted and with plugin
4561 * file url's converted
4562 * @return string
4564 public function get_contents() {
4565 global $PAGE;
4566 if (!empty($this->properties->contents)) {
4567 if (!isset($this->properties->contentsformat)) {
4568 $this->properties->contentsformat = FORMAT_HTML;
4570 $context = context_module::instance($PAGE->cm->id);
4571 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
4572 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
4573 return format_text($contents, $this->properties->contentsformat,
4574 array('context' => $context, 'noclean' => true,
4575 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
4576 } else {
4577 return '';
4582 * Set to true if this page should display in the menu block
4583 * @return bool
4585 protected function get_displayinmenublock() {
4586 return false;
4590 * Get the string that describes the options of this page type
4591 * @return string
4593 public function option_description_string() {
4594 return '';
4598 * Updates a table with the answers for this page
4599 * @param html_table $table
4600 * @return html_table
4602 public function display_answers(html_table $table) {
4603 $answers = $this->get_answers();
4604 $i = 1;
4605 foreach ($answers as $answer) {
4606 $cells = array();
4607 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
4608 $cells[] = $this->get_jump_name($answer->jumpto);
4609 $table->data[] = new html_table_row($cells);
4610 if ($i === 1){
4611 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
4613 $i++;
4615 return $table;
4619 * Determines if this page should be grayed out on the management/report screens
4620 * @return int 0 or 1
4622 protected function get_grayout() {
4623 return 0;
4627 * Adds stats for this page to the &pagestats object. This should be defined
4628 * for all page types that grade
4629 * @param array $pagestats
4630 * @param int $tries
4631 * @return bool
4633 public function stats(array &$pagestats, $tries) {
4634 return true;
4638 * Formats the answers of this page for a report
4640 * @param object $answerpage
4641 * @param object $answerdata
4642 * @param object $useranswer
4643 * @param array $pagestats
4644 * @param int $i Count of first level answers
4645 * @param int $n Count of second level answers
4646 * @return object The answer page for this
4648 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
4649 $answers = $this->get_answers();
4650 $formattextdefoptions = new stdClass;
4651 $formattextdefoptions->para = false; //I'll use it widely in this page
4652 foreach ($answers as $answer) {
4653 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
4654 $answerdata->answers[] = array($data, "");
4655 $answerpage->answerdata = $answerdata;
4657 return $answerpage;
4661 * Gets an array of the jumps used by the answers of this page
4663 * @return array
4665 public function get_jumps() {
4666 global $DB;
4667 $jumps = array();
4668 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
4669 if ($answers = $this->get_answers()) {
4670 foreach ($answers as $answer) {
4671 $jumps[] = $this->get_jump_name($answer->jumpto);
4673 } else {
4674 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
4676 return $jumps;
4679 * Informs whether this page type require manual grading or not
4680 * @return bool
4682 public function requires_manual_grading() {
4683 return false;
4687 * A callback method that allows a page to override the next page a user will
4688 * see during when this page is being completed.
4689 * @return false|int
4691 public function override_next_page() {
4692 return false;
4696 * This method is used to determine if this page is a valid page
4698 * @param array $validpages
4699 * @param array $pageviews
4700 * @return int The next page id to check
4702 public function valid_page_and_view(&$validpages, &$pageviews) {
4703 $validpages[$this->properties->id] = 1;
4704 return $this->properties->nextpageid;
4708 * Get files from the page area file.
4710 * @param bool $includedirs whether or not include directories
4711 * @param int $updatedsince return files updated since this time
4712 * @return array list of stored_file objects
4713 * @since Moodle 3.2
4715 public function get_files($includedirs = true, $updatedsince = 0) {
4716 $fs = get_file_storage();
4717 return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id,
4718 'itemid, filepath, filename', $includedirs, $updatedsince);
4725 * Class used to represent an answer to a page
4727 * @property int $id The ID of this answer in the database
4728 * @property int $lessonid The ID of the lesson this answer belongs to
4729 * @property int $pageid The ID of the page this answer belongs to
4730 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
4731 * @property int $grade The grade this answer is worth
4732 * @property int $score The score this answer will give
4733 * @property int $flags Used to store options for the answer
4734 * @property int $timecreated A timestamp of when the answer was created
4735 * @property int $timemodified A timestamp of when the answer was modified
4736 * @property string $answer The answer itself
4737 * @property string $response The response the user sees if selecting this answer
4739 * @copyright 2009 Sam Hemelryk
4740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4742 class lesson_page_answer extends lesson_base {
4745 * Loads an page answer from the DB
4747 * @param int $id
4748 * @return lesson_page_answer
4750 public static function load($id) {
4751 global $DB;
4752 $answer = $DB->get_record("lesson_answers", array("id" => $id));
4753 return new lesson_page_answer($answer);
4757 * Given an object of properties and a page created answer(s) and saves them
4758 * in the database.
4760 * @param stdClass $properties
4761 * @param lesson_page $page
4762 * @return array
4764 public static function create($properties, lesson_page $page) {
4765 return $page->create_answers($properties);
4769 * Get files from the answer area file.
4771 * @param bool $includedirs whether or not include directories
4772 * @param int $updatedsince return files updated since this time
4773 * @return array list of stored_file objects
4774 * @since Moodle 3.2
4776 public function get_files($includedirs = true, $updatedsince = 0) {
4778 $lesson = lesson::load($this->properties->lessonid);
4779 $fs = get_file_storage();
4780 $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
4781 'itemid, filepath, filename', $includedirs, $updatedsince);
4782 $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
4783 'itemid, filepath, filename', $includedirs, $updatedsince);
4784 return array_merge($answerfiles, $responsefiles);
4790 * A management class for page types
4792 * This class is responsible for managing the different pages. A manager object can
4793 * be retrieved by calling the following line of code:
4794 * <code>
4795 * $manager = lesson_page_type_manager::get($lesson);
4796 * </code>
4797 * The first time the page type manager is retrieved the it includes all of the
4798 * different page types located in mod/lesson/pagetypes.
4800 * @copyright 2009 Sam Hemelryk
4801 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4803 class lesson_page_type_manager {
4806 * An array of different page type classes
4807 * @var array
4809 protected $types = array();
4812 * Retrieves the lesson page type manager object
4814 * If the object hasn't yet been created it is created here.
4816 * @staticvar lesson_page_type_manager $pagetypemanager
4817 * @param lesson $lesson
4818 * @return lesson_page_type_manager
4820 public static function get(lesson $lesson) {
4821 static $pagetypemanager;
4822 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
4823 $pagetypemanager = new lesson_page_type_manager();
4824 $pagetypemanager->load_lesson_types($lesson);
4826 return $pagetypemanager;
4830 * Finds and loads all lesson page types in mod/lesson/pagetypes
4832 * @param lesson $lesson
4834 public function load_lesson_types(lesson $lesson) {
4835 global $CFG;
4836 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
4837 $dir = dir($basedir);
4838 while (false !== ($entry = $dir->read())) {
4839 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
4840 continue;
4842 require_once($basedir.$entry);
4843 $class = 'lesson_page_type_'.strtok($entry,'.');
4844 if (class_exists($class)) {
4845 $pagetype = new $class(new stdClass, $lesson);
4846 $this->types[$pagetype->typeid] = $pagetype;
4853 * Returns an array of strings to describe the loaded page types
4855 * @param int $type Can be used to return JUST the string for the requested type
4856 * @return array
4858 public function get_page_type_strings($type=null, $special=true) {
4859 $types = array();
4860 foreach ($this->types as $pagetype) {
4861 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
4862 $types[$pagetype->typeid] = $pagetype->typestring;
4865 return $types;
4869 * Returns the basic string used to identify a page type provided with an id
4871 * This string can be used to instantiate or identify the page type class.
4872 * If the page type id is unknown then 'unknown' is returned
4874 * @param int $id
4875 * @return string
4877 public function get_page_type_idstring($id) {
4878 foreach ($this->types as $pagetype) {
4879 if ((int)$pagetype->typeid === (int)$id) {
4880 return $pagetype->idstring;
4883 return 'unknown';
4887 * Loads a page for the provided lesson given it's id
4889 * This function loads a page from the lesson when given both the lesson it belongs
4890 * to as well as the page's id.
4891 * If the page doesn't exist an error is thrown
4893 * @param int $pageid The id of the page to load
4894 * @param lesson $lesson The lesson the page belongs to
4895 * @return lesson_page A class that extends lesson_page
4897 public function load_page($pageid, lesson $lesson) {
4898 global $DB;
4899 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
4900 print_error('cannotfindpages', 'lesson');
4902 $pagetype = get_class($this->types[$page->qtype]);
4903 $page = new $pagetype($page, $lesson);
4904 return $page;
4908 * This function detects errors in the ordering between 2 pages and updates the page records.
4910 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
4911 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
4913 protected function check_page_order($page1, $page2) {
4914 global $DB;
4915 if (empty($page1)) {
4916 if ($page2->prevpageid != 0) {
4917 debugging("***prevpageid of page " . $page2->id . " set to 0***");
4918 $page2->prevpageid = 0;
4919 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
4921 } else if (empty($page2)) {
4922 if ($page1->nextpageid != 0) {
4923 debugging("***nextpageid of page " . $page1->id . " set to 0***");
4924 $page1->nextpageid = 0;
4925 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
4927 } else {
4928 if ($page1->nextpageid != $page2->id) {
4929 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
4930 $page1->nextpageid = $page2->id;
4931 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
4933 if ($page2->prevpageid != $page1->id) {
4934 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
4935 $page2->prevpageid = $page1->id;
4936 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
4942 * This function loads ALL pages that belong to the lesson.
4944 * @param lesson $lesson
4945 * @return array An array of lesson_page_type_*
4947 public function load_all_pages(lesson $lesson) {
4948 global $DB;
4949 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
4950 return array(); // Records returned empty.
4952 foreach ($pages as $key=>$page) {
4953 $pagetype = get_class($this->types[$page->qtype]);
4954 $pages[$key] = new $pagetype($page, $lesson);
4957 $orderedpages = array();
4958 $lastpageid = 0;
4959 $morepages = true;
4960 while ($morepages) {
4961 $morepages = false;
4962 foreach ($pages as $page) {
4963 if ((int)$page->prevpageid === (int)$lastpageid) {
4964 // Check for errors in page ordering and fix them on the fly.
4965 $prevpage = null;
4966 if ($lastpageid !== 0) {
4967 $prevpage = $orderedpages[$lastpageid];
4969 $this->check_page_order($prevpage, $page);
4970 $morepages = true;
4971 $orderedpages[$page->id] = $page;
4972 unset($pages[$page->id]);
4973 $lastpageid = $page->id;
4974 if ((int)$page->nextpageid===0) {
4975 break 2;
4976 } else {
4977 break 1;
4983 // Add remaining pages and fix the nextpageid links for each page.
4984 foreach ($pages as $page) {
4985 // Check for errors in page ordering and fix them on the fly.
4986 $prevpage = null;
4987 if ($lastpageid !== 0) {
4988 $prevpage = $orderedpages[$lastpageid];
4990 $this->check_page_order($prevpage, $page);
4991 $orderedpages[$page->id] = $page;
4992 unset($pages[$page->id]);
4993 $lastpageid = $page->id;
4996 if ($lastpageid !== 0) {
4997 $this->check_page_order($orderedpages[$lastpageid], null);
5000 return $orderedpages;
5004 * Fetches an mform that can be used to create/edit an page
5006 * @param int $type The id for the page type
5007 * @param array $arguments Any arguments to pass to the mform
5008 * @return lesson_add_page_form_base
5010 public function get_page_form($type, $arguments) {
5011 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
5012 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
5013 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
5014 $class = 'lesson_add_page_form_selection';
5015 } else if ($class === 'lesson_add_page_form_unknown') {
5016 $class = 'lesson_add_page_form_selection';
5018 return new $class(null, $arguments);
5022 * Returns an array of links to use as add page links
5023 * @param int $previd The id of the previous page
5024 * @return array
5026 public function get_add_page_type_links($previd) {
5027 global $OUTPUT;
5029 $links = array();
5031 foreach ($this->types as $key=>$type) {
5032 if ($link = $type->add_page_link($previd)) {
5033 $links[$key] = $link;
5037 return $links;