MDL-57649 mod_lesson: Delete answer files correctly.
[moodle.git] / mod / lesson / locallib.php
blob7c7c3792b939e5df1cf6f83d482cfb978180adb5
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 = 0;
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 = 0;
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 // Keep the original page object.
1082 $answerpage->page = $page;
1083 $data ='';
1085 $answerdata = new stdClass;
1086 // Set some defaults for the answer data.
1087 $answerdata->score = null;
1088 $answerdata->response = null;
1089 $answerdata->responseformat = FORMAT_PLAIN;
1091 $answerpage->title = format_string($page->title);
1093 $options = new stdClass;
1094 $options->noclean = true;
1095 $options->overflowdiv = true;
1096 $options->context = $context;
1097 $answerpage->contents = format_text($page->contents, $page->contentsformat, $options);
1099 $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string();
1100 $answerpage->grayout = $page->grayout;
1101 $answerpage->context = $context;
1103 if (empty($userid)) {
1104 // there is no userid, so set these vars and display stats.
1105 $answerpage->grayout = 0;
1106 $useranswer = null;
1107 } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) {
1108 // get the user's answer for this page
1109 // need to find the right one
1110 $i = 0;
1111 foreach ($useranswers as $userattempt) {
1112 $useranswer = $userattempt;
1113 $i++;
1114 if ($lesson->maxattempts == $i) {
1115 break; // reached maxattempts, break out
1118 } else {
1119 // user did not answer this page, gray it out and set some nulls
1120 $answerpage->grayout = 1;
1121 $useranswer = null;
1123 $i = 0;
1124 $n = 0;
1125 $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
1126 $pageid = $page->nextpageid;
1129 $userstats = new stdClass;
1130 if (!empty($userid)) {
1131 $params = array("lessonid"=>$lesson->id, "userid"=>$userid);
1133 $alreadycompleted = true;
1135 if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
1136 $userstats->grade = -1;
1137 $userstats->completed = -1;
1138 $alreadycompleted = false;
1139 } else {
1140 $userstats->grade = current($grades);
1141 $userstats->completed = $userstats->grade->completed;
1142 $userstats->grade = round($userstats->grade->grade, 2);
1145 if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
1146 $userstats->timetotake = -1;
1147 $alreadycompleted = false;
1148 } else {
1149 $userstats->timetotake = current($times);
1150 $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime;
1153 if ($alreadycompleted) {
1154 $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid);
1158 return array($answerpages, $userstats);
1163 * Abstract class that page type's MUST inherit from.
1165 * This is the abstract class that ALL add page type forms must extend.
1166 * You will notice that all but two of the methods this class contains are final.
1167 * Essentially the only thing that extending classes can do is extend custom_definition.
1168 * OR if it has a special requirement on creation it can extend construction_override
1170 * @abstract
1171 * @copyright 2009 Sam Hemelryk
1172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1174 abstract class lesson_add_page_form_base extends moodleform {
1177 * This is the classic define that is used to identify this pagetype.
1178 * Will be one of LESSON_*
1179 * @var int
1181 public $qtype;
1184 * The simple string that describes the page type e.g. truefalse, multichoice
1185 * @var string
1187 public $qtypestring;
1190 * An array of options used in the htmleditor
1191 * @var array
1193 protected $editoroptions = array();
1196 * True if this is a standard page of false if it does something special.
1197 * Questions are standard pages, branch tables are not
1198 * @var bool
1200 protected $standard = true;
1203 * Answer format supported by question type.
1205 protected $answerformat = '';
1208 * Response format supported by question type.
1210 protected $responseformat = '';
1213 * Each page type can and should override this to add any custom elements to
1214 * the basic form that they want
1216 public function custom_definition() {}
1219 * Returns answer format used by question type.
1221 public function get_answer_format() {
1222 return $this->answerformat;
1226 * Returns response format used by question type.
1228 public function get_response_format() {
1229 return $this->responseformat;
1233 * Used to determine if this is a standard page or a special page
1234 * @return bool
1236 public final function is_standard() {
1237 return (bool)$this->standard;
1241 * Add the required basic elements to the form.
1243 * This method adds the basic elements to the form including title and contents
1244 * and then calls custom_definition();
1246 public final function definition() {
1247 $mform = $this->_form;
1248 $editoroptions = $this->_customdata['editoroptions'];
1250 if ($this->qtypestring != 'selectaqtype') {
1251 if ($this->_customdata['edit']) {
1252 $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring, 'lesson'));
1253 } else {
1254 $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring, 'lesson'));
1258 if (!empty($this->_customdata['returnto'])) {
1259 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
1260 $mform->setType('returnto', PARAM_URL);
1263 $mform->addElement('hidden', 'id');
1264 $mform->setType('id', PARAM_INT);
1266 $mform->addElement('hidden', 'pageid');
1267 $mform->setType('pageid', PARAM_INT);
1269 if ($this->standard === true) {
1270 $mform->addElement('hidden', 'qtype');
1271 $mform->setType('qtype', PARAM_INT);
1273 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1274 $mform->setType('title', PARAM_TEXT);
1275 $mform->addRule('title', get_string('required'), 'required', null, 'client');
1277 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
1278 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
1279 $mform->setType('contents_editor', PARAM_RAW);
1280 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1283 $this->custom_definition();
1285 if ($this->_customdata['edit'] === true) {
1286 $mform->addElement('hidden', 'edit', 1);
1287 $mform->setType('edit', PARAM_BOOL);
1288 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1289 } else if ($this->qtype === 'questiontype') {
1290 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1291 } else {
1292 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1297 * Convenience function: Adds a jumpto select element
1299 * @param string $name
1300 * @param string|null $label
1301 * @param int $selected The page to select by default
1303 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
1304 $title = get_string("jump", "lesson");
1305 if ($label === null) {
1306 $label = $title;
1308 if (is_int($name)) {
1309 $name = "jumpto[$name]";
1311 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
1312 $this->_form->setDefault($name, $selected);
1313 $this->_form->addHelpButton($name, 'jumps', 'lesson');
1317 * Convenience function: Adds a score input element
1319 * @param string $name
1320 * @param string|null $label
1321 * @param mixed $value The default value
1323 protected final function add_score($name, $label=null, $value=null) {
1324 if ($label === null) {
1325 $label = get_string("score", "lesson");
1328 if (is_int($name)) {
1329 $name = "score[$name]";
1331 $this->_form->addElement('text', $name, $label, array('size'=>5));
1332 $this->_form->setType($name, PARAM_INT);
1333 if ($value !== null) {
1334 $this->_form->setDefault($name, $value);
1336 $this->_form->addHelpButton($name, 'score', 'lesson');
1338 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1339 if (!$this->_customdata['lesson']->custom) {
1340 $this->_form->freeze($name);
1345 * Convenience function: Adds an answer editor
1347 * @param int $count The count of the element to add
1348 * @param string $label, null means default
1349 * @param bool $required
1350 * @param string $format
1351 * @return void
1353 protected final function add_answer($count, $label = null, $required = false, $format= '') {
1354 if ($label === null) {
1355 $label = get_string('answer', 'lesson');
1358 if ($format == LESSON_ANSWER_HTML) {
1359 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
1360 array('rows' => '4', 'columns' => '80'),
1361 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1362 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
1363 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1364 } else {
1365 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
1366 array('size' => '50', 'maxlength' => '200'));
1367 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
1370 if ($required) {
1371 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1375 * Convenience function: Adds an response editor
1377 * @param int $count The count of the element to add
1378 * @param string $label, null means default
1379 * @param bool $required
1380 * @return void
1382 protected final function add_response($count, $label = null, $required = false) {
1383 if ($label === null) {
1384 $label = get_string('response', 'lesson');
1386 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
1387 array('rows' => '4', 'columns' => '80'),
1388 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1389 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
1390 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1392 if ($required) {
1393 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1398 * A function that gets called upon init of this object by the calling script.
1400 * This can be used to process an immediate action if required. Currently it
1401 * is only used in special cases by non-standard page types.
1403 * @return bool
1405 public function construction_override($pageid, lesson $lesson) {
1406 return true;
1413 * Class representation of a lesson
1415 * This class is used the interact with, and manage a lesson once instantiated.
1416 * If you need to fetch a lesson object you can do so by calling
1418 * <code>
1419 * lesson::load($lessonid);
1420 * // or
1421 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1422 * $lesson = new lesson($lessonrecord);
1423 * </code>
1425 * The class itself extends lesson_base as all classes within the lesson module should
1427 * These properties are from the database
1428 * @property int $id The id of this lesson
1429 * @property int $course The ID of the course this lesson belongs to
1430 * @property string $name The name of this lesson
1431 * @property int $practice Flag to toggle this as a practice lesson
1432 * @property int $modattempts Toggle to allow the user to go back and review answers
1433 * @property int $usepassword Toggle the use of a password for entry
1434 * @property string $password The password to require users to enter
1435 * @property int $dependency ID of another lesson this lesson is dependent on
1436 * @property string $conditions Conditions of the lesson dependency
1437 * @property int $grade The maximum grade a user can achieve (%)
1438 * @property int $custom Toggle custom scoring on or off
1439 * @property int $ongoing Toggle display of an ongoing score
1440 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1441 * @property int $maxanswers The max number of answers or branches
1442 * @property int $maxattempts The maximum number of attempts a user can record
1443 * @property int $review Toggle use or wrong answer review button
1444 * @property int $nextpagedefault Override the default next page
1445 * @property int $feedback Toggles display of default feedback
1446 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1447 * @property int $maxpages Maximum number of pages this lesson can contain
1448 * @property int $retake Flag to allow users to retake a lesson
1449 * @property int $activitylink Relate this lesson to another lesson
1450 * @property string $mediafile File to pop up to or webpage to display
1451 * @property int $mediaheight Sets the height of the media file popup
1452 * @property int $mediawidth Sets the width of the media file popup
1453 * @property int $mediaclose Toggle display of a media close button
1454 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1455 * @property int $width Width of slideshow
1456 * @property int $height Height of slideshow
1457 * @property string $bgcolor Background colour of slideshow
1458 * @property int $displayleft Display a left menu
1459 * @property int $displayleftif Sets the condition on which the left menu is displayed
1460 * @property int $progressbar Flag to toggle display of a lesson progress bar
1461 * @property int $available Timestamp of when this lesson becomes available
1462 * @property int $deadline Timestamp of when this lesson is no longer available
1463 * @property int $timemodified Timestamp when lesson was last modified
1464 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1466 * These properties are calculated
1467 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1468 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1470 * @copyright 2009 Sam Hemelryk
1471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1473 class lesson extends lesson_base {
1476 * The id of the first page (where prevpageid = 0) gets set and retrieved by
1477 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1478 * @var int
1480 protected $firstpageid = null;
1482 * The id of the last page (where nextpageid = 0) gets set and retrieved by
1483 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1484 * @var int
1486 protected $lastpageid = null;
1488 * An array used to cache the pages associated with this lesson after the first
1489 * time they have been loaded.
1490 * A note to developers: If you are going to be working with MORE than one or
1491 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1492 * in order to save excess database queries.
1493 * @var array An array of lesson_page objects
1495 protected $pages = array();
1497 * Flag that gets set to true once all of the pages associated with the lesson
1498 * have been loaded.
1499 * @var bool
1501 protected $loadedallpages = false;
1504 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1505 * @see get_cm()
1506 * @var stdClass
1508 protected $cm = null;
1511 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1512 * @see get_courserecord()
1513 * @var stdClass
1515 protected $courserecord = null;
1518 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1519 * @see get_context()
1520 * @var stdClass
1522 protected $context = null;
1525 * Constructor method
1527 * @param object $properties
1528 * @param stdClass $cm course module object
1529 * @param stdClass $course course object
1530 * @since Moodle 3.3
1532 public function __construct($properties, $cm = null, $course = null) {
1533 parent::__construct($properties);
1534 $this->cm = $cm;
1535 $this->courserecord = $course;
1539 * Simply generates a lesson object given an array/object of properties
1540 * Overrides {@see lesson_base->create()}
1541 * @static
1542 * @param object|array $properties
1543 * @return lesson
1545 public static function create($properties) {
1546 return new lesson($properties);
1550 * Generates a lesson object from the database given its id
1551 * @static
1552 * @param int $lessonid
1553 * @return lesson
1555 public static function load($lessonid) {
1556 global $DB;
1558 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1559 print_error('invalidcoursemodule');
1561 return new lesson($lesson);
1565 * Deletes this lesson from the database
1567 public function delete() {
1568 global $CFG, $DB;
1569 require_once($CFG->libdir.'/gradelib.php');
1570 require_once($CFG->dirroot.'/calendar/lib.php');
1572 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1573 $context = context_module::instance($cm->id);
1575 $this->delete_all_overrides();
1577 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1578 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1579 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1580 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1581 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1582 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1583 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1584 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1585 $coursecontext = context_course::instance($cm->course);
1586 foreach($events as $event) {
1587 $event->context = $coursecontext;
1588 $event = calendar_event::load($event);
1589 $event->delete();
1593 // Delete files associated with this module.
1594 $fs = get_file_storage();
1595 $fs->delete_area_files($context->id);
1597 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1598 return true;
1602 * Deletes a lesson override from the database and clears any corresponding calendar events
1604 * @param int $overrideid The id of the override being deleted
1605 * @return bool true on success
1607 public function delete_override($overrideid) {
1608 global $CFG, $DB;
1610 require_once($CFG->dirroot . '/calendar/lib.php');
1612 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1614 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1616 // Delete the events.
1617 $conds = array('modulename' => 'lesson',
1618 'instance' => $this->properties->id);
1619 if (isset($override->userid)) {
1620 $conds['userid'] = $override->userid;
1621 } else {
1622 $conds['groupid'] = $override->groupid;
1624 $events = $DB->get_records('event', $conds);
1625 foreach ($events as $event) {
1626 $eventold = calendar_event::load($event);
1627 $eventold->delete();
1630 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1632 // Set the common parameters for one of the events we will be triggering.
1633 $params = array(
1634 'objectid' => $override->id,
1635 'context' => context_module::instance($cm->id),
1636 'other' => array(
1637 'lessonid' => $override->lessonid
1640 // Determine which override deleted event to fire.
1641 if (!empty($override->userid)) {
1642 $params['relateduserid'] = $override->userid;
1643 $event = \mod_lesson\event\user_override_deleted::create($params);
1644 } else {
1645 $params['other']['groupid'] = $override->groupid;
1646 $event = \mod_lesson\event\group_override_deleted::create($params);
1649 // Trigger the override deleted event.
1650 $event->add_record_snapshot('lesson_overrides', $override);
1651 $event->trigger();
1653 return true;
1657 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1659 public function delete_all_overrides() {
1660 global $DB;
1662 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1663 foreach ($overrides as $override) {
1664 $this->delete_override($override->id);
1669 * Updates the lesson properties with override information for a user.
1671 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1672 * then use that otherwise, if there are group-specific overrides, return the most
1673 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1675 * Special case: if there is more than one password that applies to the user, then
1676 * lesson->extrapasswords will contain an array of strings giving the remaining
1677 * passwords.
1679 * @param int $userid The userid.
1681 public function update_effective_access($userid) {
1682 global $DB;
1684 // Check for user override.
1685 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1687 if (!$override) {
1688 $override = new stdClass();
1689 $override->available = null;
1690 $override->deadline = null;
1691 $override->timelimit = null;
1692 $override->review = null;
1693 $override->maxattempts = null;
1694 $override->retake = null;
1695 $override->password = null;
1698 // Check for group overrides.
1699 $groupings = groups_get_user_groups($this->properties->course, $userid);
1701 if (!empty($groupings[0])) {
1702 // Select all overrides that apply to the User's groups.
1703 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1704 $sql = "SELECT * FROM {lesson_overrides}
1705 WHERE groupid $extra AND lessonid = ?";
1706 $params[] = $this->properties->id;
1707 $records = $DB->get_records_sql($sql, $params);
1709 // Combine the overrides.
1710 $availables = array();
1711 $deadlines = array();
1712 $timelimits = array();
1713 $reviews = array();
1714 $attempts = array();
1715 $retakes = array();
1716 $passwords = array();
1718 foreach ($records as $gpoverride) {
1719 if (isset($gpoverride->available)) {
1720 $availables[] = $gpoverride->available;
1722 if (isset($gpoverride->deadline)) {
1723 $deadlines[] = $gpoverride->deadline;
1725 if (isset($gpoverride->timelimit)) {
1726 $timelimits[] = $gpoverride->timelimit;
1728 if (isset($gpoverride->review)) {
1729 $reviews[] = $gpoverride->review;
1731 if (isset($gpoverride->maxattempts)) {
1732 $attempts[] = $gpoverride->maxattempts;
1734 if (isset($gpoverride->retake)) {
1735 $retakes[] = $gpoverride->retake;
1737 if (isset($gpoverride->password)) {
1738 $passwords[] = $gpoverride->password;
1741 // If there is a user override for a setting, ignore the group override.
1742 if (is_null($override->available) && count($availables)) {
1743 $override->available = min($availables);
1745 if (is_null($override->deadline) && count($deadlines)) {
1746 if (in_array(0, $deadlines)) {
1747 $override->deadline = 0;
1748 } else {
1749 $override->deadline = max($deadlines);
1752 if (is_null($override->timelimit) && count($timelimits)) {
1753 if (in_array(0, $timelimits)) {
1754 $override->timelimit = 0;
1755 } else {
1756 $override->timelimit = max($timelimits);
1759 if (is_null($override->review) && count($reviews)) {
1760 $override->review = max($reviews);
1762 if (is_null($override->maxattempts) && count($attempts)) {
1763 $override->maxattempts = max($attempts);
1765 if (is_null($override->retake) && count($retakes)) {
1766 $override->retake = max($retakes);
1768 if (is_null($override->password) && count($passwords)) {
1769 $override->password = array_shift($passwords);
1770 if (count($passwords)) {
1771 $override->extrapasswords = $passwords;
1777 // Merge with lesson defaults.
1778 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1779 foreach ($keys as $key) {
1780 if (isset($override->{$key})) {
1781 $this->properties->{$key} = $override->{$key};
1785 // Special handling of lesson usepassword and password.
1786 if (isset($override->password)) {
1787 if ($override->password == '') {
1788 $this->properties->usepassword = 0;
1789 } else {
1790 $this->properties->usepassword = 1;
1791 $this->properties->password = $override->password;
1792 if (isset($override->extrapasswords)) {
1793 $this->properties->extrapasswords = $override->extrapasswords;
1800 * Fetches messages from the session that may have been set in previous page
1801 * actions.
1803 * <code>
1804 * // Do not call this method directly instead use
1805 * $lesson->messages;
1806 * </code>
1808 * @return array
1810 protected function get_messages() {
1811 global $SESSION;
1813 $messages = array();
1814 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1815 $messages = $SESSION->lesson_messages[$this->properties->id];
1816 unset($SESSION->lesson_messages[$this->properties->id]);
1819 return $messages;
1823 * Get all of the attempts for the current user.
1825 * @param int $retries
1826 * @param bool $correct Optional: only fetch correct attempts
1827 * @param int $pageid Optional: only fetch attempts at the given page
1828 * @param int $userid Optional: defaults to the current user if not set
1829 * @return array|false
1831 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1832 global $USER, $DB;
1833 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1834 if ($correct) {
1835 $params['correct'] = 1;
1837 if ($pageid !== null) {
1838 $params['pageid'] = $pageid;
1840 if ($userid === null) {
1841 $params['userid'] = $USER->id;
1843 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1848 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1850 * @param int $lessonattempt the lesson attempt number (also known as retries)
1851 * @param int $userid the user id to retrieve the data from
1852 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter)
1853 * @param string $fields a comma separated list of fields to return
1854 * @return array of pages
1855 * @since Moodle 3.3
1857 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1858 global $USER, $DB;
1860 if ($userid === null) {
1861 $userid = $USER->id;
1863 $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
1864 return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1868 * Returns the first page for the lesson or false if there isn't one.
1870 * This method should be called via the magic method __get();
1871 * <code>
1872 * $firstpage = $lesson->firstpage;
1873 * </code>
1875 * @return lesson_page|bool Returns the lesson_page specialised object or false
1877 protected function get_firstpage() {
1878 $pages = $this->load_all_pages();
1879 if (count($pages) > 0) {
1880 foreach ($pages as $page) {
1881 if ((int)$page->prevpageid === 0) {
1882 return $page;
1886 return false;
1890 * Returns the last page for the lesson or false if there isn't one.
1892 * This method should be called via the magic method __get();
1893 * <code>
1894 * $lastpage = $lesson->lastpage;
1895 * </code>
1897 * @return lesson_page|bool Returns the lesson_page specialised object or false
1899 protected function get_lastpage() {
1900 $pages = $this->load_all_pages();
1901 if (count($pages) > 0) {
1902 foreach ($pages as $page) {
1903 if ((int)$page->nextpageid === 0) {
1904 return $page;
1908 return false;
1912 * Returns the id of the first page of this lesson. (prevpageid = 0)
1913 * @return int
1915 protected function get_firstpageid() {
1916 global $DB;
1917 if ($this->firstpageid == null) {
1918 if (!$this->loadedallpages) {
1919 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1920 if (!$firstpageid) {
1921 print_error('cannotfindfirstpage', 'lesson');
1923 $this->firstpageid = $firstpageid;
1924 } else {
1925 $firstpage = $this->get_firstpage();
1926 $this->firstpageid = $firstpage->id;
1929 return $this->firstpageid;
1933 * Returns the id of the last page of this lesson. (nextpageid = 0)
1934 * @return int
1936 public function get_lastpageid() {
1937 global $DB;
1938 if ($this->lastpageid == null) {
1939 if (!$this->loadedallpages) {
1940 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1941 if (!$lastpageid) {
1942 print_error('cannotfindlastpage', 'lesson');
1944 $this->lastpageid = $lastpageid;
1945 } else {
1946 $lastpageid = $this->get_lastpage();
1947 $this->lastpageid = $lastpageid->id;
1951 return $this->lastpageid;
1955 * Gets the next page id to display after the one that is provided.
1956 * @param int $nextpageid
1957 * @return bool
1959 public function get_next_page($nextpageid) {
1960 global $USER, $DB;
1961 $allpages = $this->load_all_pages();
1962 if ($this->properties->nextpagedefault) {
1963 // in Flash Card mode...first get number of retakes
1964 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1965 shuffle($allpages);
1966 $found = false;
1967 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1968 foreach ($allpages as $nextpage) {
1969 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1970 $found = true;
1971 break;
1974 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1975 foreach ($allpages as $nextpage) {
1976 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1977 $found = true;
1978 break;
1982 if ($found) {
1983 if ($this->properties->maxpages) {
1984 // check number of pages viewed (in the lesson)
1985 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1986 return LESSON_EOL;
1989 return $nextpage->id;
1992 // In a normal lesson mode
1993 foreach ($allpages as $nextpage) {
1994 if ((int)$nextpage->id === (int)$nextpageid) {
1995 return $nextpage->id;
1998 return LESSON_EOL;
2002 * Sets a message against the session for this lesson that will displayed next
2003 * time the lesson processes messages
2005 * @param string $message
2006 * @param string $class
2007 * @param string $align
2008 * @return bool
2010 public function add_message($message, $class="notifyproblem", $align='center') {
2011 global $SESSION;
2013 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
2014 $SESSION->lesson_messages = array();
2015 $SESSION->lesson_messages[$this->properties->id] = array();
2016 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
2017 $SESSION->lesson_messages[$this->properties->id] = array();
2020 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
2022 return true;
2026 * Check if the lesson is accessible at the present time
2027 * @return bool True if the lesson is accessible, false otherwise
2029 public function is_accessible() {
2030 $available = $this->properties->available;
2031 $deadline = $this->properties->deadline;
2032 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
2036 * Starts the lesson time for the current user
2037 * @return bool Returns true
2039 public function start_timer() {
2040 global $USER, $DB;
2042 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2043 false, MUST_EXIST);
2045 // Trigger lesson started event.
2046 $event = \mod_lesson\event\lesson_started::create(array(
2047 'objectid' => $this->properties()->id,
2048 'context' => context_module::instance($cm->id),
2049 'courseid' => $this->properties()->course
2051 $event->trigger();
2053 $USER->startlesson[$this->properties->id] = true;
2055 $timenow = time();
2056 $startlesson = new stdClass;
2057 $startlesson->lessonid = $this->properties->id;
2058 $startlesson->userid = $USER->id;
2059 $startlesson->starttime = $timenow;
2060 $startlesson->lessontime = $timenow;
2061 if (WS_SERVER) {
2062 $startlesson->timemodifiedoffline = $timenow;
2064 $DB->insert_record('lesson_timer', $startlesson);
2065 if ($this->properties->timelimit) {
2066 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
2068 return true;
2072 * Updates the timer to the current time and returns the new timer object
2073 * @param bool $restart If set to true the timer is restarted
2074 * @param bool $continue If set to true AND $restart=true then the timer
2075 * will continue from a previous attempt
2076 * @return stdClass The new timer
2078 public function update_timer($restart=false, $continue=false, $endreached =false) {
2079 global $USER, $DB;
2081 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2083 // clock code
2084 // get time information for this user
2085 if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
2086 $this->start_timer();
2087 $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
2089 $timer = current($timer); // This will get the latest start time record.
2091 if ($restart) {
2092 if ($continue) {
2093 // continue a previous test, need to update the clock (think this option is disabled atm)
2094 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
2096 // Trigger lesson resumed event.
2097 $event = \mod_lesson\event\lesson_resumed::create(array(
2098 'objectid' => $this->properties->id,
2099 'context' => context_module::instance($cm->id),
2100 'courseid' => $this->properties->course
2102 $event->trigger();
2104 } else {
2105 // starting over, so reset the clock
2106 $timer->starttime = time();
2108 // Trigger lesson restarted event.
2109 $event = \mod_lesson\event\lesson_restarted::create(array(
2110 'objectid' => $this->properties->id,
2111 'context' => context_module::instance($cm->id),
2112 'courseid' => $this->properties->course
2114 $event->trigger();
2119 $timenow = time();
2120 $timer->lessontime = $timenow;
2121 if (WS_SERVER) {
2122 $timer->timemodifiedoffline = $timenow;
2124 $timer->completed = $endreached;
2125 $DB->update_record('lesson_timer', $timer);
2127 // Update completion state.
2128 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2129 false, MUST_EXIST);
2130 $course = get_course($cm->course);
2131 $completion = new completion_info($course);
2132 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
2133 $completion->update_state($cm, COMPLETION_COMPLETE);
2135 return $timer;
2139 * Updates the timer to the current time then stops it by unsetting the user var
2140 * @return bool Returns true
2142 public function stop_timer() {
2143 global $USER, $DB;
2144 unset($USER->startlesson[$this->properties->id]);
2146 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2147 false, MUST_EXIST);
2149 // Trigger lesson ended event.
2150 $event = \mod_lesson\event\lesson_ended::create(array(
2151 'objectid' => $this->properties()->id,
2152 'context' => context_module::instance($cm->id),
2153 'courseid' => $this->properties()->course
2155 $event->trigger();
2157 return $this->update_timer(false, false, true);
2161 * Checks to see if the lesson has pages
2163 public function has_pages() {
2164 global $DB;
2165 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
2166 return ($pagecount>0);
2170 * Returns the link for the related activity
2171 * @return array|false
2173 public function link_for_activitylink() {
2174 global $DB;
2175 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
2176 if ($module) {
2177 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
2178 if ($modname) {
2179 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
2180 if ($instancename) {
2181 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
2182 get_string('activitylinkname', 'lesson', $instancename),
2183 array('class'=>'centerpadded lessonbutton standardbutton'));
2187 return '';
2191 * Loads the requested page.
2193 * This function will return the requested page id as either a specialised
2194 * lesson_page object OR as a generic lesson_page.
2195 * If the page has been loaded previously it will be returned from the pages
2196 * array, otherwise it will be loaded from the database first
2198 * @param int $pageid
2199 * @return lesson_page A lesson_page object or an object that extends it
2201 public function load_page($pageid) {
2202 if (!array_key_exists($pageid, $this->pages)) {
2203 $manager = lesson_page_type_manager::get($this);
2204 $this->pages[$pageid] = $manager->load_page($pageid, $this);
2206 return $this->pages[$pageid];
2210 * Loads ALL of the pages for this lesson
2212 * @return array An array containing all pages from this lesson
2214 public function load_all_pages() {
2215 if (!$this->loadedallpages) {
2216 $manager = lesson_page_type_manager::get($this);
2217 $this->pages = $manager->load_all_pages($this);
2218 $this->loadedallpages = true;
2220 return $this->pages;
2224 * Duplicate the lesson page.
2226 * @param int $pageid Page ID of the page to duplicate.
2227 * @return void.
2229 public function duplicate_page($pageid) {
2230 global $PAGE;
2231 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2232 $context = context_module::instance($cm->id);
2233 // Load the page.
2234 $page = $this->load_page($pageid);
2235 $properties = $page->properties();
2236 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2237 if (!$properties->qoption) {
2238 unset($properties->qoption);
2240 if (!$properties->layout) {
2241 unset($properties->layout);
2243 if (!$properties->display) {
2244 unset($properties->display);
2247 $properties->pageid = $pageid;
2248 // Add text and format into the format required to create a new page.
2249 $properties->contents_editor = array(
2250 'text' => $properties->contents,
2251 'format' => $properties->contentsformat
2253 $answers = $page->get_answers();
2254 // Answers need to be added to $properties.
2255 $i = 0;
2256 $answerids = array();
2257 foreach ($answers as $answer) {
2258 // Needs to be rearranged to work with the create function.
2259 $properties->answer_editor[$i] = array(
2260 'text' => $answer->answer,
2261 'format' => $answer->answerformat
2264 $properties->response_editor[$i] = array(
2265 'text' => $answer->response,
2266 'format' => $answer->responseformat
2268 $answerids[] = $answer->id;
2270 $properties->jumpto[$i] = $answer->jumpto;
2271 $properties->score[$i] = $answer->score;
2273 $i++;
2275 // Create the duplicate page.
2276 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
2277 $newanswers = $newlessonpage->get_answers();
2278 // Copy over the file areas as well.
2279 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
2280 $j = 0;
2281 foreach ($newanswers as $answer) {
2282 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
2283 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
2285 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
2286 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
2288 $j++;
2293 * Copy the files from one page to another.
2295 * @param string $filearea Area that the files are stored.
2296 * @param int $itemid Item ID.
2297 * @param int $newitemid The item ID for the new page.
2298 * @param int $contextid Context ID for this page.
2299 * @return void.
2301 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2302 $fs = get_file_storage();
2303 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2304 foreach ($files as $file) {
2305 $fieldupdates = array('itemid' => $newitemid);
2306 $fs->create_file_from_storedfile($fieldupdates, $file);
2311 * Determines if a jumpto value is correct or not.
2313 * returns true if jumpto page is (logically) after the pageid page or
2314 * if the jumpto value is a special value. Returns false in all other cases.
2316 * @param int $pageid Id of the page from which you are jumping from.
2317 * @param int $jumpto The jumpto number.
2318 * @return boolean True or false after a series of tests.
2320 public function jumpto_is_correct($pageid, $jumpto) {
2321 global $DB;
2323 // first test the special values
2324 if (!$jumpto) {
2325 // same page
2326 return false;
2327 } elseif ($jumpto == LESSON_NEXTPAGE) {
2328 return true;
2329 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2330 return true;
2331 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2332 return true;
2333 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2334 return true;
2335 } elseif ($jumpto == LESSON_EOL) {
2336 return true;
2339 $pages = $this->load_all_pages();
2340 $apageid = $pages[$pageid]->nextpageid;
2341 while ($apageid != 0) {
2342 if ($jumpto == $apageid) {
2343 return true;
2345 $apageid = $pages[$apageid]->nextpageid;
2347 return false;
2351 * Returns the time a user has remaining on this lesson
2352 * @param int $starttime Starttime timestamp
2353 * @return string
2355 public function time_remaining($starttime) {
2356 $timeleft = $starttime + $this->properties->timelimit - time();
2357 $hours = floor($timeleft/3600);
2358 $timeleft = $timeleft - ($hours * 3600);
2359 $minutes = floor($timeleft/60);
2360 $secs = $timeleft - ($minutes * 60);
2362 if ($minutes < 10) {
2363 $minutes = "0$minutes";
2365 if ($secs < 10) {
2366 $secs = "0$secs";
2368 $output = array();
2369 $output[] = $hours;
2370 $output[] = $minutes;
2371 $output[] = $secs;
2372 $output = implode(':', $output);
2373 return $output;
2377 * Interprets LESSON_CLUSTERJUMP jumpto value.
2379 * This will select a page randomly
2380 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
2381 * and the page selected will be a page that has not been viewed already
2382 * and if any pages are within a branch table or end of branch then only 1 page within
2383 * the branch table or end of branch will be randomly selected (sub clustering).
2385 * @param int $pageid Id of the current page from which we are jumping from.
2386 * @param int $userid Id of the user.
2387 * @return int The id of the next page.
2389 public function cluster_jump($pageid, $userid=null) {
2390 global $DB, $USER;
2392 if ($userid===null) {
2393 $userid = $USER->id;
2395 // get the number of retakes
2396 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
2397 $retakes = 0;
2399 // get all the lesson_attempts aka what the user has seen
2400 $seenpages = array();
2401 if ($attempts = $this->get_attempts($retakes)) {
2402 foreach ($attempts as $attempt) {
2403 $seenpages[$attempt->pageid] = $attempt->pageid;
2408 // get the lesson pages
2409 $lessonpages = $this->load_all_pages();
2410 // find the start of the cluster
2411 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2412 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
2413 break;
2415 $pageid = $lessonpages[$pageid]->prevpageid;
2418 $clusterpages = array();
2419 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
2420 $unseen = array();
2421 foreach ($clusterpages as $key=>$cluster) {
2422 // Remove the page if it is in a branch table or is an endofbranch.
2423 if ($this->is_sub_page_of_type($cluster->id,
2424 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
2425 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
2426 unset($clusterpages[$key]);
2427 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
2428 // If branchtable, check to see if any pages inside have been viewed.
2429 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2430 $flag = true;
2431 foreach ($branchpages as $branchpage) {
2432 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
2433 $flag = false;
2436 if ($flag && count($branchpages) > 0) {
2437 // Add branch table.
2438 $unseen[] = $cluster;
2440 } elseif ($cluster->is_unseen($seenpages)) {
2441 $unseen[] = $cluster;
2445 if (count($unseen) > 0) {
2446 // it does not contain elements, then use exitjump, otherwise find out next page/branch
2447 $nextpage = $unseen[rand(0, count($unseen)-1)];
2448 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
2449 // if branch table, then pick a random page inside of it
2450 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2451 return $branchpages[rand(0, count($branchpages)-1)]->id;
2452 } else { // otherwise, return the page's id
2453 return $nextpage->id;
2455 } else {
2456 // seen all there is to see, leave the cluster
2457 if (end($clusterpages)->nextpageid == 0) {
2458 return LESSON_EOL;
2459 } else {
2460 $clusterendid = $pageid;
2461 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2462 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2463 break;
2465 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
2467 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
2468 if ($exitjump == LESSON_NEXTPAGE) {
2469 $exitjump = $lessonpages[$clusterendid]->nextpageid;
2471 if ($exitjump == 0) {
2472 return LESSON_EOL;
2473 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
2474 return $exitjump;
2475 } else {
2476 if (!array_key_exists($exitjump, $lessonpages)) {
2477 $found = false;
2478 foreach ($lessonpages as $page) {
2479 if ($page->id === $clusterendid) {
2480 $found = true;
2481 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2482 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
2483 if ($exitjump == LESSON_NEXTPAGE) {
2484 $exitjump = $lessonpages[$page->id]->nextpageid;
2486 break;
2490 if (!array_key_exists($exitjump, $lessonpages)) {
2491 return LESSON_EOL;
2493 return $exitjump;
2500 * Finds all pages that appear to be a subtype of the provided pageid until
2501 * an end point specified within $ends is encountered or no more pages exist
2503 * @param int $pageid
2504 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2505 * the subtype
2506 * @return array An array of specialised lesson_page objects
2508 public function get_sub_pages_of($pageid, array $ends) {
2509 $lessonpages = $this->load_all_pages();
2510 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
2511 $pages = array();
2513 while (true) {
2514 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2515 break;
2517 $pages[] = $lessonpages[$pageid];
2518 $pageid = $lessonpages[$pageid]->nextpageid;
2521 return $pages;
2525 * Checks to see if the specified page[id] is a subpage of a type specified in
2526 * the $types array, until either there are no more pages of we find a type
2527 * corresponding to that of a type specified in $ends
2529 * @param int $pageid The id of the page to check
2530 * @param array $types An array of types that would signify this page was a subpage
2531 * @param array $ends An array of types that mean this is not a subpage
2532 * @return bool
2534 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2535 $pages = $this->load_all_pages();
2536 $pageid = $pages[$pageid]->prevpageid; // move up one
2538 array_unshift($ends, 0);
2539 // go up the pages till branch table
2540 while (true) {
2541 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2542 return false;
2543 } else if (in_array($pages[$pageid]->qtype, $types)) {
2544 return true;
2546 $pageid = $pages[$pageid]->prevpageid;
2551 * Move a page resorting all other pages.
2553 * @param int $pageid
2554 * @param int $after
2555 * @return void
2557 public function resort_pages($pageid, $after) {
2558 global $CFG;
2560 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2561 $context = context_module::instance($cm->id);
2563 $pages = $this->load_all_pages();
2565 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2566 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2569 $pagetomove = clone($pages[$pageid]);
2570 unset($pages[$pageid]);
2572 $pageids = array();
2573 if ($after === 0) {
2574 $pageids['p0'] = $pageid;
2576 foreach ($pages as $page) {
2577 $pageids[] = $page->id;
2578 if ($page->id == $after) {
2579 $pageids[] = $pageid;
2583 $pageidsref = $pageids;
2584 reset($pageidsref);
2585 $prev = 0;
2586 $next = next($pageidsref);
2587 foreach ($pageids as $pid) {
2588 if ($pid === $pageid) {
2589 $page = $pagetomove;
2590 } else {
2591 $page = $pages[$pid];
2593 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2594 $page->move($next, $prev);
2596 if ($pid === $pageid) {
2597 // We will trigger an event.
2598 $pageupdated = array('next' => $next, 'prev' => $prev);
2602 $prev = $page->id;
2603 $next = next($pageidsref);
2604 if (!$next) {
2605 $next = 0;
2609 // Trigger an event: page moved.
2610 if (!empty($pageupdated)) {
2611 $eventparams = array(
2612 'context' => $context,
2613 'objectid' => $pageid,
2614 'other' => array(
2615 'pagetype' => $page->get_typestring(),
2616 'prevpageid' => $pageupdated['prev'],
2617 'nextpageid' => $pageupdated['next']
2620 $event = \mod_lesson\event\page_moved::create($eventparams);
2621 $event->trigger();
2627 * Return the lesson context object.
2629 * @return stdClass context
2630 * @since Moodle 3.3
2632 public function get_context() {
2633 if ($this->context == null) {
2634 $this->context = context_module::instance($this->get_cm()->id);
2636 return $this->context;
2640 * Set the lesson course module object.
2642 * @param stdClass $cm course module objct
2643 * @since Moodle 3.3
2645 private function set_cm($cm) {
2646 $this->cm = $cm;
2650 * Return the lesson course module object.
2652 * @return stdClass course module
2653 * @since Moodle 3.3
2655 public function get_cm() {
2656 if ($this->cm == null) {
2657 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2659 return $this->cm;
2663 * Set the lesson course object.
2665 * @param stdClass $course course objct
2666 * @since Moodle 3.3
2668 private function set_courserecord($course) {
2669 $this->courserecord = $course;
2673 * Return the lesson course object.
2675 * @return stdClass course
2676 * @since Moodle 3.3
2678 public function get_courserecord() {
2679 global $DB;
2681 if ($this->courserecord == null) {
2682 $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2684 return $this->courserecord;
2688 * Check if the user can manage the lesson activity.
2690 * @return bool true if the user can manage the lesson
2691 * @since Moodle 3.3
2693 public function can_manage() {
2694 return has_capability('mod/lesson:manage', $this->get_context());
2698 * Check if time restriction is applied.
2700 * @return mixed false if there aren't restrictions or an object with the restriction information
2701 * @since Moodle 3.3
2703 public function get_time_restriction_status() {
2704 if ($this->can_manage()) {
2705 return false;
2708 if (!$this->is_accessible()) {
2709 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2710 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2711 } else {
2712 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2714 return (object) $status;
2716 return false;
2720 * Check if password restriction is applied.
2722 * @param string $userpassword the user password to check (if the restriction is set)
2723 * @return mixed false if there aren't restrictions or an object with the restriction information
2724 * @since Moodle 3.3
2726 public function get_password_restriction_status($userpassword) {
2727 global $USER;
2728 if ($this->can_manage()) {
2729 return false;
2732 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2733 $correctpass = false;
2734 if (!empty($userpassword) &&
2735 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2736 // With or without md5 for backward compatibility (MDL-11090).
2737 $correctpass = true;
2738 $USER->lessonloggedin[$this->id] = true;
2739 } else if (isset($this->properties->extrapasswords)) {
2740 // Group overrides may have additional passwords.
2741 foreach ($this->properties->extrapasswords as $password) {
2742 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2743 $correctpass = true;
2744 $USER->lessonloggedin[$this->id] = true;
2748 return !$correctpass;
2750 return false;
2754 * Check if dependencies restrictions are applied.
2756 * @return mixed false if there aren't restrictions or an object with the restriction information
2757 * @since Moodle 3.3
2759 public function get_dependencies_restriction_status() {
2760 global $DB, $USER;
2761 if ($this->can_manage()) {
2762 return false;
2765 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2766 // Lesson exists, so we can proceed.
2767 $conditions = unserialize($this->properties->conditions);
2768 // Assume false for all.
2769 $errors = array();
2770 // Check for the timespent condition.
2771 if ($conditions->timespent) {
2772 $timespent = false;
2773 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2774 // Go through all the times and test to see if any of them satisfy the condition.
2775 foreach ($attempttimes as $attempttime) {
2776 $duration = $attempttime->lessontime - $attempttime->starttime;
2777 if ($conditions->timespent < $duration / 60) {
2778 $timespent = true;
2782 if (!$timespent) {
2783 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2786 // Check for the gradebetterthan condition.
2787 if ($conditions->gradebetterthan) {
2788 $gradebetterthan = false;
2789 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2790 // Go through all the grades and test to see if any of them satisfy the condition.
2791 foreach ($studentgrades as $studentgrade) {
2792 if ($studentgrade->grade >= $conditions->gradebetterthan) {
2793 $gradebetterthan = true;
2797 if (!$gradebetterthan) {
2798 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2801 // Check for the completed condition.
2802 if ($conditions->completed) {
2803 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2804 $errors[] = get_string('completederror', 'lesson');
2807 if (!empty($errors)) {
2808 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2811 return false;
2815 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2817 * @return bool true if is in review mode
2818 * @since Moodle 3.3
2820 public function is_in_review_mode() {
2821 global $DB, $USER;
2823 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2824 if ($userhasgrade && !$this->properties->retake) {
2825 return true;
2827 return false;
2831 * Return the last page the current user saw.
2833 * @param int $retriescount the number of retries for the lesson (the last retry number).
2834 * @return mixed false if the user didn't see the lesson or the last page id
2836 public function get_last_page_seen($retriescount) {
2837 global $DB, $USER;
2839 $lastpageseen = false;
2840 $allattempts = $this->get_attempts($retriescount);
2841 if (!empty($allattempts)) {
2842 $attempt = end($allattempts);
2843 $attemptpage = $this->load_page($attempt->pageid);
2844 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2845 // Convert the jumpto to a proper page id.
2846 if ($jumpto == 0) {
2847 // Check if a question has been incorrectly answered AND no more attempts at it are left.
2848 $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2849 if (count($nattempts) >= $this->properties->maxattempts) {
2850 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2851 } else {
2852 $lastpageseen = $attempt->pageid;
2854 } else if ($jumpto == LESSON_NEXTPAGE) {
2855 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2856 } else if ($jumpto == LESSON_CLUSTERJUMP) {
2857 $lastpageseen = $this->cluster_jump($attempt->pageid);
2858 } else {
2859 $lastpageseen = $jumpto;
2863 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
2864 // In here, user has viewed a branch table.
2865 $lastbranchtable = current($branchtables);
2866 if (count($allattempts) > 0) {
2867 if ($lastbranchtable->timeseen > $attempt->timeseen) {
2868 // This branch table was viewed more recently than the question page.
2869 if (!empty($lastbranchtable->nextpageid)) {
2870 $lastpageseen = $lastbranchtable->nextpageid;
2871 } else {
2872 // Next page ID did not exist prior to MDL-34006.
2873 $lastpageseen = $lastbranchtable->pageid;
2876 } else {
2877 // Has not answered any questions but has viewed a branch table.
2878 if (!empty($lastbranchtable->nextpageid)) {
2879 $lastpageseen = $lastbranchtable->nextpageid;
2880 } else {
2881 // Next page ID did not exist prior to MDL-34006.
2882 $lastpageseen = $lastbranchtable->pageid;
2886 return $lastpageseen;
2890 * Return the number of retries in a lesson for a given user.
2892 * @param int $userid the user id
2893 * @return int the retries count
2894 * @since Moodle 3.3
2896 public function count_user_retries($userid) {
2897 global $DB;
2899 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
2903 * Check if a user left a timed session.
2905 * @param int $retriescount the number of retries for the lesson (the last retry number).
2906 * @return true if the user left the timed session
2907 * @since Moodle 3.3
2909 public function left_during_timed_session($retriescount) {
2910 global $DB, $USER;
2912 $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
2913 return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
2917 * Trigger module viewed event and set the module viewed for completion.
2919 * @since Moodle 3.3
2921 public function set_module_viewed() {
2922 global $CFG;
2923 require_once($CFG->libdir . '/completionlib.php');
2925 // Trigger module viewed event.
2926 $event = \mod_lesson\event\course_module_viewed::create(array(
2927 'objectid' => $this->properties->id,
2928 'context' => $this->get_context()
2930 $event->add_record_snapshot('course_modules', $this->get_cm());
2931 $event->add_record_snapshot('course', $this->get_courserecord());
2932 $event->trigger();
2934 // Mark as viewed.
2935 $completion = new completion_info($this->get_courserecord());
2936 $completion->set_module_viewed($this->get_cm());
2940 * Return the timers in the current lesson for the given user.
2942 * @param int $userid the user id
2943 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
2944 * @param string $fields a comma separated list of fields to return
2945 * @param int $limitfrom return a subset of records, starting at this point (optional).
2946 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
2947 * @return array list of timers for the given user in the lesson
2948 * @since Moodle 3.3
2950 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
2951 global $DB, $USER;
2953 if ($userid === null) {
2954 $userid = $USER->id;
2957 $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
2958 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
2962 * Check if the user is out of time in a timed lesson.
2964 * @param stdClass $timer timer object
2965 * @return bool True if the user is on time, false is the user ran out of time
2966 * @since Moodle 3.3
2968 public function check_time($timer) {
2969 if ($this->properties->timelimit) {
2970 $timeleft = $timer->starttime + $this->properties->timelimit - time();
2971 if ($timeleft <= 0) {
2972 // Out of time.
2973 $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
2974 return false;
2975 } else if ($timeleft < 60) {
2976 // One minute warning.
2977 $this->add_message(get_string('studentoneminwarning', 'lesson'));
2980 return true;
2984 * Add different informative messages to the given page.
2986 * @param lesson_page $page page object
2987 * @param reviewmode $bool whether we are in review mode or not
2988 * @since Moodle 3.3
2990 public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
2991 global $DB, $USER;
2993 if (!$this->can_manage()) {
2994 if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
2995 // Tell student how many questions they have seen, how many are required and their grade.
2996 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2997 $gradeinfo = lesson_grade($this, $ntries);
2998 if ($gradeinfo->attempts) {
2999 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3000 $a = new stdClass;
3001 $a->nquestions = $gradeinfo->nquestions;
3002 $a->minquestions = $this->properties->minquestions;
3003 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3006 if (!$reviewmode && !$this->properties->retake) {
3007 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
3008 if ($this->properties->grade != GRADE_TYPE_NONE) {
3009 $a = new stdClass;
3010 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3011 $a->total = $this->properties->grade;
3012 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3017 } else {
3018 if ($this->properties->timelimit) {
3019 $this->add_message(get_string('teachertimerwarning', 'lesson'));
3021 if (lesson_display_teacher_warning($this)) {
3022 // This is the warning msg for teachers to inform them that cluster
3023 // and unseen does not work while logged in as a teacher.
3024 $warningvars = new stdClass();
3025 $warningvars->cluster = get_string('clusterjump', 'lesson');
3026 $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
3027 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3033 * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3035 * @return str the ongoing score message
3036 * @since Moodle 3.3
3038 public function get_ongoing_score_message() {
3039 global $USER, $DB;
3041 $context = $this->get_context();
3043 if (has_capability('mod/lesson:manage', $context)) {
3044 return get_string('teacherongoingwarning', 'lesson');
3045 } else {
3046 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3047 if (isset($USER->modattempts[$this->properties->id])) {
3048 $ntries--;
3050 $gradeinfo = lesson_grade($this, $ntries);
3051 $a = new stdClass;
3052 if ($this->properties->custom) {
3053 $a->score = $gradeinfo->earned;
3054 $a->currenthigh = $gradeinfo->total;
3055 return get_string("ongoingcustom", "lesson", $a);
3056 } else {
3057 $a->correct = $gradeinfo->earned;
3058 $a->viewed = $gradeinfo->attempts;
3059 return get_string("ongoingnormal", "lesson", $a);
3065 * Calculate the progress of the current user in the lesson.
3067 * @return int the progress (scale 0-100)
3068 * @since Moodle 3.3
3070 public function calculate_progress() {
3071 global $USER, $DB;
3073 // Check if the user is reviewing the attempt.
3074 if (isset($USER->modattempts[$this->properties->id])) {
3075 return 100;
3078 // All of the lesson pages.
3079 $pages = $this->load_all_pages();
3080 foreach ($pages as $page) {
3081 if ($page->prevpageid == 0) {
3082 $pageid = $page->id; // Find the first page id.
3083 break;
3087 // Current attempt number.
3088 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
3089 $ntries = 0; // May not be necessary.
3092 $viewedpageids = array();
3093 if ($attempts = $this->get_attempts($ntries, false)) {
3094 foreach ($attempts as $attempt) {
3095 $viewedpageids[$attempt->pageid] = $attempt;
3099 $viewedbranches = array();
3100 // Collect all of the branch tables viewed.
3101 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
3102 foreach ($branches as $branch) {
3103 $viewedbranches[$branch->pageid] = $branch;
3105 $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3108 // Filter out the following pages:
3109 // - End of Cluster
3110 // - End of Branch
3111 // - Pages found inside of Clusters
3112 // Do not filter out Cluster Page(s) because we count a cluster as one.
3113 // By keeping the cluster page, we get our 1.
3114 $validpages = array();
3115 while ($pageid != 0) {
3116 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3119 // Progress calculation as a percent.
3120 $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3121 return (int) $progress;
3125 * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3127 * @param int $pageid the given page id
3128 * @param mod_lesson_renderer $lessonoutput the lesson output rendered
3129 * @param bool $reviewmode whether we are in review mode or not
3130 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
3131 * @return array the page object and contents
3132 * @throws moodle_exception
3133 * @since Moodle 3.3
3135 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
3136 global $USER, $CFG;
3138 $page = $this->load_page($pageid);
3139 // Check if the page is of a special type and if so take any nessecary action.
3140 $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3142 // Avoid redirections returning the jump to special page id.
3143 if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3144 return array($newpageid, null, null);
3147 if (is_numeric($newpageid)) {
3148 $page = $this->load_page($newpageid);
3151 // Add different informative messages to the given page.
3152 $this->add_messages_on_page_view($page, $reviewmode);
3154 if (is_array($page->answers) && count($page->answers) > 0) {
3155 // This is for modattempts option. Find the users previous answer to this page,
3156 // and then display it below in answer processing.
3157 if (isset($USER->modattempts[$this->properties->id])) {
3158 $retries = $this->count_user_retries($USER->id);
3159 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
3160 throw new moodle_exception('cannotfindpreattempt', 'lesson');
3162 $attempt = end($attempts);
3163 $USER->modattempts[$this->properties->id] = $attempt;
3164 } else {
3165 $attempt = false;
3167 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3168 } else {
3169 require_once($CFG->dirroot . '/mod/lesson/view_form.php');
3170 $data = new stdClass;
3171 $data->id = $this->get_cm()->id;
3172 $data->pageid = $page->id;
3173 $data->newpageid = $this->get_next_page($page->nextpageid);
3175 $customdata = array(
3176 'title' => $page->title,
3177 'contents' => $page->get_contents()
3179 $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
3180 $mform->set_data($data);
3181 ob_start();
3182 $mform->display();
3183 $lessoncontent = ob_get_contents();
3184 ob_end_clean();
3187 return array($page->id, $page, $lessoncontent);
3191 * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
3193 * @param lesson_page $page lesson page
3194 * @param int $newpageid the new page id
3195 * @return int the real page to jump to (or end of lesson)
3196 * @since Moodle 3.3
3198 public function calculate_new_page_on_jump(lesson_page $page, $newpageid) {
3199 global $USER, $DB;
3201 $canmanage = $this->can_manage();
3203 if (isset($USER->modattempts[$this->properties->id])) {
3204 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
3205 if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) {
3206 // Remember, this session variable holds the pageid of the last page that the user saw.
3207 $newpageid = LESSON_EOL;
3208 } else {
3209 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3210 $nretakes--; // Make sure we are looking at the right try.
3211 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
3212 $found = false;
3213 $temppageid = 0;
3214 // Make sure that the newpageid always defaults to something valid.
3215 $newpageid = LESSON_EOL;
3216 foreach ($attempts as $attempt) {
3217 if ($found && $temppageid != $attempt->pageid) {
3218 // Now try to find the next page, make sure next few attempts do no belong to current page.
3219 $newpageid = $attempt->pageid;
3220 break;
3222 if ($attempt->pageid == $page->id) {
3223 $found = true; // If found current page.
3224 $temppageid = $attempt->pageid;
3228 } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) {
3229 // Going to check to see if the page that the user is going to view next, is a cluster page.
3230 // If so, dont display, go into the cluster.
3231 // The $newpageid > 0 is used to filter out all of the negative code jumps.
3232 $newpage = $this->load_page($newpageid);
3233 if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3234 $newpageid = $overridenewpageid;
3236 } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) {
3237 if ($canmanage) {
3238 if ($page->nextpageid == 0) {
3239 $newpageid = LESSON_EOL;
3240 } else {
3241 $newpageid = $page->nextpageid;
3243 } else {
3244 $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id);
3246 } else if ($newpageid == LESSON_PREVIOUSPAGE) {
3247 $newpageid = $page->prevpageid;
3248 } else if ($newpageid == LESSON_RANDOMPAGE) {
3249 $newpageid = lesson_random_question_jump($this, $page->id);
3250 } else if ($newpageid == LESSON_CLUSTERJUMP) {
3251 if ($canmanage) {
3252 if ($page->nextpageid == 0) { // If teacher, go to next page.
3253 $newpageid = LESSON_EOL;
3254 } else {
3255 $newpageid = $page->nextpageid;
3257 } else {
3258 $newpageid = $this->cluster_jump($page->id);
3260 } else if ($newpageid == 0) {
3261 $newpageid = $page->id;
3262 } else if ($newpageid == LESSON_NEXTPAGE) {
3263 $newpageid = $this->get_next_page($page->nextpageid);
3266 return $newpageid;
3270 * Process page responses.
3272 * @param lesson_page $page page object
3273 * @since Moodle 3.3
3275 public function process_page_responses(lesson_page $page) {
3276 $context = $this->get_context();
3278 // Check the page has answers [MDL-25632].
3279 if (count($page->answers) > 0) {
3280 $result = $page->record_attempt($context);
3281 } else {
3282 // The page has no answers so we will just progress to the next page in the
3283 // sequence (as set by newpageid).
3284 $result = new stdClass;
3285 $result->newpageid = optional_param('newpageid', $page->nextpageid, PARAM_INT);
3286 $result->nodefaultresponse = true;
3287 $result->inmediatejump = false;
3290 if ($result->inmediatejump) {
3291 return $result;
3294 $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);
3296 return $result;
3300 * Add different informative messages to the given page.
3302 * @param lesson_page $page page object
3303 * @param stdClass $result the page processing result object
3304 * @param bool $reviewmode whether we are in review mode or not
3305 * @since Moodle 3.3
3307 public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
3309 if ($this->can_manage()) {
3310 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3311 if (lesson_display_teacher_warning($this)) {
3312 $warningvars = new stdClass();
3313 $warningvars->cluster = get_string("clusterjump", "lesson");
3314 $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
3315 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3317 // Inform teacher that s/he will not see the timer.
3318 if ($this->properties->timelimit) {
3319 $this->add_message(get_string("teachertimerwarning", "lesson"));
3322 // Report attempts remaining.
3323 if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
3324 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
3329 * Process and return all the information for the end of lesson page.
3331 * @param string $outoftime used to check to see if the student ran out of time
3332 * @return stdclass an object with all the page data ready for rendering
3333 * @since Moodle 3.3
3335 public function process_eol_page($outoftime) {
3336 global $DB, $USER;
3338 $course = $this->get_courserecord();
3339 $cm = $this->get_cm();
3340 $canmanage = $this->can_manage();
3342 // Init all the possible fields and values.
3343 $data = (object) array(
3344 'gradelesson' => true,
3345 'notenoughtimespent' => false,
3346 'numberofpagesviewed' => false,
3347 'youshouldview' => false,
3348 'numberofcorrectanswers' => false,
3349 'displayscorewithessays' => false,
3350 'displayscorewithoutessays' => false,
3351 'yourcurrentgradeisoutof' => false,
3352 'eolstudentoutoftimenoanswers' => false,
3353 'welldone' => false,
3354 'progressbar' => false,
3355 'displayofgrade' => false,
3356 'reviewlesson' => false,
3357 'modattemptsnoteacher' => false,
3358 'activitylink' => false,
3359 'progresscompleted' => false,
3362 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3363 if (isset($USER->modattempts[$this->properties->id])) {
3364 $ntries--; // Need to look at the old attempts :).
3367 $gradeinfo = lesson_grade($this, $ntries);
3368 $data->gradeinfo = $gradeinfo;
3369 if ($this->properties->custom && !$canmanage) {
3370 // Before we calculate the custom score make sure they answered the minimum
3371 // number of questions. We only need to do this for custom scoring as we can
3372 // not get the miniumum score the user should achieve. If we are not using
3373 // custom scoring (so all questions are valued as 1) then we simply check if
3374 // they answered more than the minimum questions, if not, we mark it out of the
3375 // number specified in the minimum questions setting - which is done in lesson_grade().
3376 // Get the number of answers given.
3377 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3378 $data->gradelesson = false;
3379 $a = new stdClass;
3380 $a->nquestions = $gradeinfo->nquestions;
3381 $a->minquestions = $this->properties->minquestions;
3382 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3386 if (!$canmanage) {
3387 if ($data->gradelesson) {
3388 // Store this now before any modifications to pages viewed.
3389 $progresscompleted = $this->calculate_progress();
3391 // Update the clock / get time information for this user.
3392 $this->stop_timer();
3394 // Update completion state.
3395 $completion = new completion_info($course);
3396 if ($completion->is_enabled($cm) && $this->properties->completionendreached) {
3397 $completion->update_state($cm, COMPLETION_COMPLETE);
3400 if ($this->properties->completiontimespent > 0) {
3401 $duration = $DB->get_field_sql(
3402 "SELECT SUM(lessontime - starttime)
3403 FROM {lesson_timer}
3404 WHERE lessonid = :lessonid
3405 AND userid = :userid",
3406 array('userid' => $USER->id, 'lessonid' => $this->properties->id));
3407 if (!$duration) {
3408 $duration = 0;
3411 // If student has not spend enough time in the lesson, display a message.
3412 if ($duration < $this->properties->completiontimespent) {
3413 $a = new stdClass;
3414 $a->timespentraw = $duration;
3415 $a->timespent = format_time($duration);
3416 $a->timerequiredraw = $this->properties->completiontimespent;
3417 $a->timerequired = format_time($this->properties->completiontimespent);
3418 $data->notenoughtimespent = $a;
3422 if ($gradeinfo->attempts) {
3423 if (!$this->properties->custom) {
3424 $data->numberofpagesviewed = $gradeinfo->nquestions;
3425 if ($this->properties->minquestions) {
3426 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3427 $data->youshouldview = $this->properties->minquestions;
3430 $data->numberofcorrectanswers = $gradeinfo->earned;
3432 $a = new stdClass;
3433 $a->score = $gradeinfo->earned;
3434 $a->grade = $gradeinfo->total;
3435 if ($gradeinfo->nmanual) {
3436 $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
3437 $a->essayquestions = $gradeinfo->nmanual;
3438 $data->displayscorewithessays = $a;
3439 } else {
3440 $data->displayscorewithoutessays = $a;
3442 if ($this->properties->grade != GRADE_TYPE_NONE) {
3443 $a = new stdClass;
3444 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3445 $a->total = $this->properties->grade;
3446 $data->yourcurrentgradeisoutof = $a;
3449 $grade = new stdClass();
3450 $grade->lessonid = $this->properties->id;
3451 $grade->userid = $USER->id;
3452 $grade->grade = $gradeinfo->grade;
3453 $grade->completed = time();
3454 if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record.
3455 if (!$grades = $DB->get_records("lesson_grades",
3456 array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
3457 throw new moodle_exception('cannotfindgrade', 'lesson');
3459 $oldgrade = array_shift($grades);
3460 $grade->id = $oldgrade->id;
3461 $DB->update_record("lesson_grades", $grade);
3462 } else {
3463 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3465 } else {
3466 if ($this->properties->timelimit) {
3467 if ($outoftime == 'normal') {
3468 $grade = new stdClass();
3469 $grade->lessonid = $this->properties->id;
3470 $grade->userid = $USER->id;
3471 $grade->grade = 0;
3472 $grade->completed = time();
3473 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3474 $data->eolstudentoutoftimenoanswers = true;
3476 } else {
3477 $data->welldone = true;
3481 // Update central gradebook.
3482 lesson_update_grades($this, $USER->id);
3483 $data->progresscompleted = $progresscompleted;
3485 } else {
3486 // Display for teacher.
3487 if ($this->properties->grade != GRADE_TYPE_NONE) {
3488 $data->displayofgrade = true;
3492 if ($this->properties->modattempts && !$canmanage) {
3493 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3494 // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3495 // to pass to view again. This is slick cause it wont call the empty($pageid) code
3496 // $ntries is decremented above.
3497 if (!$attempts = $this->get_attempts($ntries)) {
3498 $attempts = array();
3499 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id));
3500 } else {
3501 $firstattempt = current($attempts);
3502 $pageid = $firstattempt->pageid;
3503 // If the student wishes to review, need to know the last question page that the student answered.
3504 // This will help to make sure that the student can leave the lesson via pushing the continue button.
3505 $lastattempt = end($attempts);
3506 $USER->modattempts[$this->properties->id] = $lastattempt->pageid;
3508 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid));
3510 $data->reviewlesson = $url->out(false);
3511 } else if ($this->properties->modattempts && $canmanage) {
3512 $data->modattemptsnoteacher = true;
3515 if ($this->properties->activitylink) {
3516 $data->activitylink = $this->link_for_activitylink();
3518 return $data;
3524 * Abstract class to provide a core functions to the all lesson classes
3526 * This class should be abstracted by ALL classes with the lesson module to ensure
3527 * that all classes within this module can be interacted with in the same way.
3529 * This class provides the user with a basic properties array that can be fetched
3530 * or set via magic methods, or alternatively by defining methods get_blah() or
3531 * set_blah() within the extending object.
3533 * @copyright 2009 Sam Hemelryk
3534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3536 abstract class lesson_base {
3539 * An object containing properties
3540 * @var stdClass
3542 protected $properties;
3545 * The constructor
3546 * @param stdClass $properties
3548 public function __construct($properties) {
3549 $this->properties = (object)$properties;
3553 * Magic property method
3555 * Attempts to call a set_$key method if one exists otherwise falls back
3556 * to simply set the property
3558 * @param string $key
3559 * @param mixed $value
3561 public function __set($key, $value) {
3562 if (method_exists($this, 'set_'.$key)) {
3563 $this->{'set_'.$key}($value);
3565 $this->properties->{$key} = $value;
3569 * Magic get method
3571 * Attempts to call a get_$key method to return the property and ralls over
3572 * to return the raw property
3574 * @param str $key
3575 * @return mixed
3577 public function __get($key) {
3578 if (method_exists($this, 'get_'.$key)) {
3579 return $this->{'get_'.$key}();
3581 return $this->properties->{$key};
3585 * Stupid PHP needs an isset magic method if you use the get magic method and
3586 * still want empty calls to work.... blah ~!
3588 * @param string $key
3589 * @return bool
3591 public function __isset($key) {
3592 if (method_exists($this, 'get_'.$key)) {
3593 $val = $this->{'get_'.$key}();
3594 return !empty($val);
3596 return !empty($this->properties->{$key});
3599 //NOTE: E_STRICT does not allow to change function signature!
3602 * If implemented should create a new instance, save it in the DB and return it
3604 //public static function create() {}
3606 * If implemented should load an instance from the DB and return it
3608 //public static function load() {}
3610 * Fetches all of the properties of the object
3611 * @return stdClass
3613 public function properties() {
3614 return $this->properties;
3620 * Abstract class representation of a page associated with a lesson.
3622 * This class should MUST be extended by all specialised page types defined in
3623 * mod/lesson/pagetypes/.
3624 * There are a handful of abstract methods that need to be defined as well as
3625 * severl methods that can optionally be defined in order to make the page type
3626 * operate in the desired way
3628 * Database properties
3629 * @property int $id The id of this lesson page
3630 * @property int $lessonid The id of the lesson this page belongs to
3631 * @property int $prevpageid The id of the page before this one
3632 * @property int $nextpageid The id of the next page in the page sequence
3633 * @property int $qtype Identifies the page type of this page
3634 * @property int $qoption Used to record page type specific options
3635 * @property int $layout Used to record page specific layout selections
3636 * @property int $display Used to record page specific display selections
3637 * @property int $timecreated Timestamp for when the page was created
3638 * @property int $timemodified Timestamp for when the page was last modified
3639 * @property string $title The title of this page
3640 * @property string $contents The rich content shown to describe the page
3641 * @property int $contentsformat The format of the contents field
3643 * Calculated properties
3644 * @property-read array $answers An array of answers for this page
3645 * @property-read bool $displayinmenublock Toggles display in the left menu block
3646 * @property-read array $jumps An array containing all the jumps this page uses
3647 * @property-read lesson $lesson The lesson this page belongs to
3648 * @property-read int $type The type of the page [question | structure]
3649 * @property-read typeid The unique identifier for the page type
3650 * @property-read typestring The string that describes this page type
3652 * @abstract
3653 * @copyright 2009 Sam Hemelryk
3654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3656 abstract class lesson_page extends lesson_base {
3659 * A reference to the lesson this page belongs to
3660 * @var lesson
3662 protected $lesson = null;
3664 * Contains the answers to this lesson_page once loaded
3665 * @var null|array
3667 protected $answers = null;
3669 * This sets the type of the page, can be one of the constants defined below
3670 * @var int
3672 protected $type = 0;
3675 * Constants used to identify the type of the page
3677 const TYPE_QUESTION = 0;
3678 const TYPE_STRUCTURE = 1;
3681 * This method should return the integer used to identify the page type within
3682 * the database and throughout code. This maps back to the defines used in 1.x
3683 * @abstract
3684 * @return int
3686 abstract protected function get_typeid();
3688 * This method should return the string that describes the pagetype
3689 * @abstract
3690 * @return string
3692 abstract protected function get_typestring();
3695 * This method gets called to display the page to the user taking the lesson
3696 * @abstract
3697 * @param object $renderer
3698 * @param object $attempt
3699 * @return string
3701 abstract public function display($renderer, $attempt);
3704 * Creates a new lesson_page within the database and returns the correct pagetype
3705 * object to use to interact with the new lesson
3707 * @final
3708 * @static
3709 * @param object $properties
3710 * @param lesson $lesson
3711 * @return lesson_page Specialised object that extends lesson_page
3713 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
3714 global $DB;
3715 $newpage = new stdClass;
3716 $newpage->title = $properties->title;
3717 $newpage->contents = $properties->contents_editor['text'];
3718 $newpage->contentsformat = $properties->contents_editor['format'];
3719 $newpage->lessonid = $lesson->id;
3720 $newpage->timecreated = time();
3721 $newpage->qtype = $properties->qtype;
3722 $newpage->qoption = (isset($properties->qoption))?1:0;
3723 $newpage->layout = (isset($properties->layout))?1:0;
3724 $newpage->display = (isset($properties->display))?1:0;
3725 $newpage->prevpageid = 0; // this is a first page
3726 $newpage->nextpageid = 0; // this is the only page
3728 if ($properties->pageid) {
3729 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
3730 if (!$prevpage) {
3731 print_error('cannotfindpages', 'lesson');
3733 $newpage->prevpageid = $prevpage->id;
3734 $newpage->nextpageid = $prevpage->nextpageid;
3735 } else {
3736 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
3737 if ($nextpage) {
3738 // This is the first page, there are existing pages put this at the start
3739 $newpage->nextpageid = $nextpage->id;
3743 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
3745 $editor = new stdClass;
3746 $editor->id = $newpage->id;
3747 $editor->contents_editor = $properties->contents_editor;
3748 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
3749 $DB->update_record("lesson_pages", $editor);
3751 if ($newpage->prevpageid > 0) {
3752 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
3754 if ($newpage->nextpageid > 0) {
3755 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
3758 $page = lesson_page::load($newpage, $lesson);
3759 $page->create_answers($properties);
3761 // Trigger an event: page created.
3762 $eventparams = array(
3763 'context' => $context,
3764 'objectid' => $newpage->id,
3765 'other' => array(
3766 'pagetype' => $page->get_typestring()
3769 $event = \mod_lesson\event\page_created::create($eventparams);
3770 $snapshot = clone($newpage);
3771 $snapshot->timemodified = 0;
3772 $event->add_record_snapshot('lesson_pages', $snapshot);
3773 $event->trigger();
3775 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
3777 return $page;
3781 * This method loads a page object from the database and returns it as a
3782 * specialised object that extends lesson_page
3784 * @final
3785 * @static
3786 * @param int $id
3787 * @param lesson $lesson
3788 * @return lesson_page Specialised lesson_page object
3790 final public static function load($id, lesson $lesson) {
3791 global $DB;
3793 if (is_object($id) && !empty($id->qtype)) {
3794 $page = $id;
3795 } else {
3796 $page = $DB->get_record("lesson_pages", array("id" => $id));
3797 if (!$page) {
3798 print_error('cannotfindpages', 'lesson');
3801 $manager = lesson_page_type_manager::get($lesson);
3803 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
3804 if (!class_exists($class)) {
3805 $class = 'lesson_page';
3808 return new $class($page, $lesson);
3812 * Deletes a lesson_page from the database as well as any associated records.
3813 * @final
3814 * @return bool
3816 final public function delete() {
3817 global $DB;
3819 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3820 $context = context_module::instance($cm->id);
3822 // Delete files associated with attempts.
3823 $fs = get_file_storage();
3824 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
3825 foreach ($attempts as $attempt) {
3826 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
3830 // Then delete all the associated records...
3831 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
3833 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
3835 // Delete files related to answers and responses.
3836 if ($answers = $DB->get_records("lesson_answers", array("pageid" => $this->properties->id))) {
3837 foreach ($answers as $answer) {
3838 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $answer->id);
3839 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $answer->id);
3843 // ...now delete the answers...
3844 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
3845 // ..and the page itself
3846 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
3848 // Trigger an event: page deleted.
3849 $eventparams = array(
3850 'context' => $context,
3851 'objectid' => $this->properties->id,
3852 'other' => array(
3853 'pagetype' => $this->get_typestring()
3856 $event = \mod_lesson\event\page_deleted::create($eventparams);
3857 $event->add_record_snapshot('lesson_pages', $this->properties);
3858 $event->trigger();
3860 // Delete files associated with this page.
3861 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
3863 // repair the hole in the linkage
3864 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
3865 //This is the only page, no repair needed
3866 } elseif (!$this->properties->prevpageid) {
3867 // this is the first page...
3868 $page = $this->lesson->load_page($this->properties->nextpageid);
3869 $page->move(null, 0);
3870 } elseif (!$this->properties->nextpageid) {
3871 // this is the last page...
3872 $page = $this->lesson->load_page($this->properties->prevpageid);
3873 $page->move(0);
3874 } else {
3875 // page is in the middle...
3876 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
3877 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
3879 $prevpage->move($nextpage->id);
3880 $nextpage->move(null, $prevpage->id);
3882 return true;
3886 * Moves a page by updating its nextpageid and prevpageid values within
3887 * the database
3889 * @final
3890 * @param int $nextpageid
3891 * @param int $prevpageid
3893 final public function move($nextpageid=null, $prevpageid=null) {
3894 global $DB;
3895 if ($nextpageid === null) {
3896 $nextpageid = $this->properties->nextpageid;
3898 if ($prevpageid === null) {
3899 $prevpageid = $this->properties->prevpageid;
3901 $obj = new stdClass;
3902 $obj->id = $this->properties->id;
3903 $obj->prevpageid = $prevpageid;
3904 $obj->nextpageid = $nextpageid;
3905 $DB->update_record('lesson_pages', $obj);
3909 * Returns the answers that are associated with this page in the database
3911 * @final
3912 * @return array
3914 final public function get_answers() {
3915 global $DB;
3916 if ($this->answers === null) {
3917 $this->answers = array();
3918 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
3919 if (!$answers) {
3920 // It is possible that a lesson upgraded from Moodle 1.9 still
3921 // contains questions without any answers [MDL-25632].
3922 // debugging(get_string('cannotfindanswer', 'lesson'));
3923 return array();
3925 foreach ($answers as $answer) {
3926 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
3929 return $this->answers;
3933 * Returns the lesson this page is associated with
3934 * @final
3935 * @return lesson
3937 final protected function get_lesson() {
3938 return $this->lesson;
3942 * Returns the type of page this is. Not to be confused with page type
3943 * @final
3944 * @return int
3946 final protected function get_type() {
3947 return $this->type;
3951 * Records an attempt at this page
3953 * @final
3954 * @global moodle_database $DB
3955 * @param stdClass $context
3956 * @return stdClass Returns the result of the attempt
3958 final public function record_attempt($context) {
3959 global $DB, $USER, $OUTPUT, $PAGE;
3962 * This should be overridden by each page type to actually check the response
3963 * against what ever custom criteria they have defined
3965 $result = $this->check_answer();
3967 // Processes inmediate jumps.
3968 if ($result->inmediatejump) {
3969 return $result;
3972 $result->attemptsremaining = 0;
3973 $result->maxattemptsreached = false;
3975 if ($result->noanswer) {
3976 $result->newpageid = $this->properties->id; // display same page again
3977 $result->feedback = get_string('noanswer', 'lesson');
3978 } else {
3979 if (!has_capability('mod/lesson:manage', $context)) {
3980 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
3982 // Get the number of attempts that have been made on this question for this student and retake,
3983 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
3984 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
3986 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
3987 if ($nattempts >= $this->lesson->maxattempts) {
3988 $result->maxattemptsreached = true;
3989 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
3990 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
3991 return $result;
3994 // record student's attempt
3995 $attempt = new stdClass;
3996 $attempt->lessonid = $this->lesson->id;
3997 $attempt->pageid = $this->properties->id;
3998 $attempt->userid = $USER->id;
3999 $attempt->answerid = $result->answerid;
4000 $attempt->retry = $nretakes;
4001 $attempt->correct = $result->correctanswer;
4002 if($result->userresponse !== null) {
4003 $attempt->useranswer = $result->userresponse;
4006 $attempt->timeseen = time();
4007 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
4008 $userisreviewing = false;
4009 if (isset($USER->modattempts[$this->lesson->id])) {
4010 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
4011 $userisreviewing = true;
4014 // Only insert a record if we are not reviewing the lesson.
4015 if (!$userisreviewing) {
4016 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
4017 $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
4018 // Trigger an event: question answered.
4019 $eventparams = array(
4020 'context' => context_module::instance($PAGE->cm->id),
4021 'objectid' => $this->properties->id,
4022 'other' => array(
4023 'pagetype' => $this->get_typestring()
4026 $event = \mod_lesson\event\question_answered::create($eventparams);
4027 $event->add_record_snapshot('lesson_attempts', $attempt);
4028 $event->trigger();
4030 // Increase the number of attempts made.
4031 $nattempts++;
4034 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
4035 // displaying of message(s) is at the end of page for more ergonomic display
4036 if (!$result->correctanswer && ($result->newpageid == 0)) {
4037 // retreive the number of attempts left counter for displaying at bottom of feedback page
4038 if ($nattempts >= $this->lesson->maxattempts) {
4039 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4040 $result->maxattemptsreached = true;
4042 $result->newpageid = LESSON_NEXTPAGE;
4043 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4044 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
4049 // Determine default feedback if necessary
4050 if (empty($result->response)) {
4051 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
4052 // These conditions have been met:
4053 // 1. The lesson manager has not supplied feedback to the student
4054 // 2. Not displaying default feedback
4055 // 3. The user did provide an answer
4056 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
4058 $result->nodefaultresponse = true; // This will cause a redirect below
4059 } else if ($result->isessayquestion) {
4060 $result->response = get_string('defaultessayresponse', 'lesson');
4061 } else if ($result->correctanswer) {
4062 $result->response = get_string('thatsthecorrectanswer', 'lesson');
4063 } else {
4064 $result->response = get_string('thatsthewronganswer', 'lesson');
4068 if ($result->response) {
4069 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
4070 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4071 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
4072 if ($qattempts == 1) {
4073 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
4074 } else {
4075 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
4077 } else {
4078 $result->feedback = '';
4080 $class = 'response';
4081 if ($result->correctanswer) {
4082 $class .= ' correct'; // CSS over-ride this if they exist (!important).
4083 } else if (!$result->isessayquestion) {
4084 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
4086 $options = new stdClass;
4087 $options->noclean = true;
4088 $options->para = true;
4089 $options->overflowdiv = true;
4090 $options->context = $context;
4092 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
4093 'generalbox boxaligncenter');
4094 if (isset($result->studentanswerformat)) {
4095 // This is the student's answer so it should be cleaned.
4096 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
4097 array('context' => $context, 'para' => true));
4098 } else {
4099 $studentanswer = format_string($result->studentanswer);
4101 $result->feedback .= '<div class="correctanswer generalbox"><em>'
4102 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
4103 if (isset($result->responseformat)) {
4104 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
4105 'mod_lesson', 'page_responses', $result->answerid);
4106 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
4107 , $class);
4108 } else {
4109 $result->feedback .= $OUTPUT->box($result->response, $class);
4111 $result->feedback .= '</div>';
4115 return $result;
4119 * Returns the string for a jump name
4121 * @final
4122 * @param int $jumpto Jump code or page ID
4123 * @return string
4125 final protected function get_jump_name($jumpto) {
4126 global $DB;
4127 static $jumpnames = array();
4129 if (!array_key_exists($jumpto, $jumpnames)) {
4130 if ($jumpto == LESSON_THISPAGE) {
4131 $jumptitle = get_string('thispage', 'lesson');
4132 } elseif ($jumpto == LESSON_NEXTPAGE) {
4133 $jumptitle = get_string('nextpage', 'lesson');
4134 } elseif ($jumpto == LESSON_EOL) {
4135 $jumptitle = get_string('endoflesson', 'lesson');
4136 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
4137 $jumptitle = get_string('unseenpageinbranch', 'lesson');
4138 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
4139 $jumptitle = get_string('previouspage', 'lesson');
4140 } elseif ($jumpto == LESSON_RANDOMPAGE) {
4141 $jumptitle = get_string('randompageinbranch', 'lesson');
4142 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
4143 $jumptitle = get_string('randombranch', 'lesson');
4144 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
4145 $jumptitle = get_string('clusterjump', 'lesson');
4146 } else {
4147 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
4148 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
4151 $jumpnames[$jumpto] = format_string($jumptitle,true);
4154 return $jumpnames[$jumpto];
4158 * Constructor method
4159 * @param object $properties
4160 * @param lesson $lesson
4162 public function __construct($properties, lesson $lesson) {
4163 parent::__construct($properties);
4164 $this->lesson = $lesson;
4168 * Returns the score for the attempt
4169 * This may be overridden by page types that require manual grading
4170 * @param array $answers
4171 * @param object $attempt
4172 * @return int
4174 public function earned_score($answers, $attempt) {
4175 return $answers[$attempt->answerid]->score;
4179 * This is a callback method that can be override and gets called when ever a page
4180 * is viewed
4182 * @param bool $canmanage True if the user has the manage cap
4183 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
4184 * @return mixed
4186 public function callback_on_view($canmanage, $redirect = true) {
4187 return true;
4191 * save editor answers files and update answer record
4193 * @param object $context
4194 * @param int $maxbytes
4195 * @param object $answer
4196 * @param object $answereditor
4197 * @param object $responseeditor
4199 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
4200 global $DB;
4201 if (isset($answereditor['itemid'])) {
4202 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
4203 $context->id, 'mod_lesson', 'page_answers', $answer->id,
4204 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4205 $answer->answer, null);
4206 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
4208 if (isset($responseeditor['itemid'])) {
4209 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
4210 $context->id, 'mod_lesson', 'page_responses', $answer->id,
4211 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4212 $answer->response, null);
4213 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
4218 * Rewrite urls in response and optionality answer of a question answer
4220 * @param object $answer
4221 * @param bool $rewriteanswer must rewrite answer
4222 * @return object answer with rewritten urls
4224 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
4225 global $PAGE;
4227 $context = context_module::instance($PAGE->cm->id);
4228 if ($rewriteanswer) {
4229 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
4230 'mod_lesson', 'page_answers', $answer->id);
4232 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
4233 'mod_lesson', 'page_responses', $answer->id);
4235 return $answer;
4239 * Updates a lesson page and its answers within the database
4241 * @param object $properties
4242 * @return bool
4244 public function update($properties, $context = null, $maxbytes = null) {
4245 global $DB, $PAGE;
4246 $answers = $this->get_answers();
4247 $properties->id = $this->properties->id;
4248 $properties->lessonid = $this->lesson->id;
4249 if (empty($properties->qoption)) {
4250 $properties->qoption = '0';
4252 if (empty($context)) {
4253 $context = $PAGE->context;
4255 if ($maxbytes === null) {
4256 $maxbytes = get_user_max_upload_file_size($context);
4258 $properties->timemodified = time();
4259 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
4260 $DB->update_record("lesson_pages", $properties);
4262 // Trigger an event: page updated.
4263 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
4265 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
4266 // These page types have only one answer to save the jump and score.
4267 if (count($answers) > 1) {
4268 $answer = array_shift($answers);
4269 foreach ($answers as $a) {
4270 $DB->delete_record('lesson_answers', array('id' => $a->id));
4272 } else if (count($answers) == 1) {
4273 $answer = array_shift($answers);
4274 } else {
4275 $answer = new stdClass;
4276 $answer->lessonid = $properties->lessonid;
4277 $answer->pageid = $properties->id;
4278 $answer->timecreated = time();
4281 $answer->timemodified = time();
4282 if (isset($properties->jumpto[0])) {
4283 $answer->jumpto = $properties->jumpto[0];
4285 if (isset($properties->score[0])) {
4286 $answer->score = $properties->score[0];
4288 if (!empty($answer->id)) {
4289 $DB->update_record("lesson_answers", $answer->properties());
4290 } else {
4291 $DB->insert_record("lesson_answers", $answer);
4293 } else {
4294 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
4295 if (!array_key_exists($i, $this->answers)) {
4296 $this->answers[$i] = new stdClass;
4297 $this->answers[$i]->lessonid = $this->lesson->id;
4298 $this->answers[$i]->pageid = $this->id;
4299 $this->answers[$i]->timecreated = $this->timecreated;
4302 if (isset($properties->answer_editor[$i])) {
4303 if (is_array($properties->answer_editor[$i])) {
4304 // Multichoice and true/false pages have an HTML editor.
4305 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
4306 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
4307 } else {
4308 // Branch tables, shortanswer and mumerical pages have only a text field.
4309 $this->answers[$i]->answer = $properties->answer_editor[$i];
4310 $this->answers[$i]->answerformat = FORMAT_MOODLE;
4314 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4315 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
4316 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
4319 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
4320 if (isset($properties->jumpto[$i])) {
4321 $this->answers[$i]->jumpto = $properties->jumpto[$i];
4323 if ($this->lesson->custom && isset($properties->score[$i])) {
4324 $this->answers[$i]->score = $properties->score[$i];
4326 if (!isset($this->answers[$i]->id)) {
4327 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
4328 } else {
4329 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
4332 // Save files in answers and responses.
4333 if (isset($properties->response_editor[$i])) {
4334 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4335 $properties->answer_editor[$i], $properties->response_editor[$i]);
4336 } else {
4337 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4338 $properties->answer_editor[$i]);
4341 } else if (isset($this->answers[$i]->id)) {
4342 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
4343 unset($this->answers[$i]);
4347 return true;
4351 * Can be set to true if the page requires a static link to create a new instance
4352 * instead of simply being included in the dropdown
4353 * @param int $previd
4354 * @return bool
4356 public function add_page_link($previd) {
4357 return false;
4361 * Returns true if a page has been viewed before
4363 * @param array|int $param Either an array of pages that have been seen or the
4364 * number of retakes a user has had
4365 * @return bool
4367 public function is_unseen($param) {
4368 global $USER, $DB;
4369 if (is_array($param)) {
4370 $seenpages = $param;
4371 return (!array_key_exists($this->properties->id, $seenpages));
4372 } else {
4373 $nretakes = $param;
4374 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
4375 return true;
4378 return false;
4382 * Checks to see if a page has been answered previously
4383 * @param int $nretakes
4384 * @return bool
4386 public function is_unanswered($nretakes) {
4387 global $DB, $USER;
4388 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
4389 return true;
4391 return false;
4395 * Creates answers within the database for this lesson_page. Usually only ever
4396 * called when creating a new page instance
4397 * @param object $properties
4398 * @return array
4400 public function create_answers($properties) {
4401 global $DB, $PAGE;
4402 // now add the answers
4403 $newanswer = new stdClass;
4404 $newanswer->lessonid = $this->lesson->id;
4405 $newanswer->pageid = $this->properties->id;
4406 $newanswer->timecreated = $this->properties->timecreated;
4408 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
4409 $context = context_module::instance($cm->id);
4411 $answers = array();
4413 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
4414 $answer = clone($newanswer);
4416 if (isset($properties->answer_editor[$i])) {
4417 if (is_array($properties->answer_editor[$i])) {
4418 // Multichoice and true/false pages have an HTML editor.
4419 $answer->answer = $properties->answer_editor[$i]['text'];
4420 $answer->answerformat = $properties->answer_editor[$i]['format'];
4421 } else {
4422 // Branch tables, shortanswer and mumerical pages have only a text field.
4423 $answer->answer = $properties->answer_editor[$i];
4424 $answer->answerformat = FORMAT_MOODLE;
4427 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4428 $answer->response = $properties->response_editor[$i]['text'];
4429 $answer->responseformat = $properties->response_editor[$i]['format'];
4432 if (isset($answer->answer) && $answer->answer != '') {
4433 if (isset($properties->jumpto[$i])) {
4434 $answer->jumpto = $properties->jumpto[$i];
4436 if ($this->lesson->custom && isset($properties->score[$i])) {
4437 $answer->score = $properties->score[$i];
4439 $answer->id = $DB->insert_record("lesson_answers", $answer);
4440 if (isset($properties->response_editor[$i])) {
4441 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4442 $properties->answer_editor[$i], $properties->response_editor[$i]);
4443 } else {
4444 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4445 $properties->answer_editor[$i]);
4447 $answers[$answer->id] = new lesson_page_answer($answer);
4448 } else {
4449 break;
4453 $this->answers = $answers;
4454 return $answers;
4458 * This method MUST be overridden by all question page types, or page types that
4459 * wish to score a page.
4461 * The structure of result should always be the same so it is a good idea when
4462 * overriding this method on a page type to call
4463 * <code>
4464 * $result = parent::check_answer();
4465 * </code>
4466 * before modifying it as required.
4468 * @return stdClass
4470 public function check_answer() {
4471 $result = new stdClass;
4472 $result->answerid = 0;
4473 $result->noanswer = false;
4474 $result->correctanswer = false;
4475 $result->isessayquestion = false; // use this to turn off review button on essay questions
4476 $result->response = '';
4477 $result->newpageid = 0; // stay on the page
4478 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
4479 $result->userresponse = null;
4480 $result->feedback = '';
4481 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
4482 $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing.
4483 return $result;
4487 * True if the page uses a custom option
4489 * Should be override and set to true if the page uses a custom option.
4491 * @return bool
4493 public function has_option() {
4494 return false;
4498 * Returns the maximum number of answers for this page given the maximum number
4499 * of answers permitted by the lesson.
4501 * @param int $default
4502 * @return int
4504 public function max_answers($default) {
4505 return $default;
4509 * Returns the properties of this lesson page as an object
4510 * @return stdClass;
4512 public function properties() {
4513 $properties = clone($this->properties);
4514 if ($this->answers === null) {
4515 $this->get_answers();
4517 if (count($this->answers)>0) {
4518 $count = 0;
4519 $qtype = $properties->qtype;
4520 foreach ($this->answers as $answer) {
4521 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
4522 if ($qtype != LESSON_PAGE_MATCHING) {
4523 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
4524 } else {
4525 $properties->{'response_editor['.$count.']'} = $answer->response;
4527 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
4528 $properties->{'score['.$count.']'} = $answer->score;
4529 $count++;
4532 return $properties;
4536 * Returns an array of options to display when choosing the jumpto for a page/answer
4537 * @static
4538 * @param int $pageid
4539 * @param lesson $lesson
4540 * @return array
4542 public static function get_jumptooptions($pageid, lesson $lesson) {
4543 global $DB;
4544 $jump = array();
4545 $jump[0] = get_string("thispage", "lesson");
4546 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
4547 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
4548 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
4550 if ($pageid == 0) {
4551 return $jump;
4554 $pages = $lesson->load_all_pages();
4555 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))) {
4556 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
4557 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
4559 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
4560 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
4562 if (!optional_param('firstpage', 0, PARAM_INT)) {
4563 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
4564 while (true) {
4565 if ($apageid) {
4566 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
4567 $jump[$apageid] = strip_tags(format_string($title,true));
4568 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
4569 } else {
4570 // last page reached
4571 break;
4575 return $jump;
4578 * Returns the contents field for the page properly formatted and with plugin
4579 * file url's converted
4580 * @return string
4582 public function get_contents() {
4583 global $PAGE;
4584 if (!empty($this->properties->contents)) {
4585 if (!isset($this->properties->contentsformat)) {
4586 $this->properties->contentsformat = FORMAT_HTML;
4588 $context = context_module::instance($PAGE->cm->id);
4589 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
4590 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
4591 return format_text($contents, $this->properties->contentsformat,
4592 array('context' => $context, 'noclean' => true,
4593 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
4594 } else {
4595 return '';
4600 * Set to true if this page should display in the menu block
4601 * @return bool
4603 protected function get_displayinmenublock() {
4604 return false;
4608 * Get the string that describes the options of this page type
4609 * @return string
4611 public function option_description_string() {
4612 return '';
4616 * Updates a table with the answers for this page
4617 * @param html_table $table
4618 * @return html_table
4620 public function display_answers(html_table $table) {
4621 $answers = $this->get_answers();
4622 $i = 1;
4623 foreach ($answers as $answer) {
4624 $cells = array();
4625 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
4626 $cells[] = $this->get_jump_name($answer->jumpto);
4627 $table->data[] = new html_table_row($cells);
4628 if ($i === 1){
4629 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
4631 $i++;
4633 return $table;
4637 * Determines if this page should be grayed out on the management/report screens
4638 * @return int 0 or 1
4640 protected function get_grayout() {
4641 return 0;
4645 * Adds stats for this page to the &pagestats object. This should be defined
4646 * for all page types that grade
4647 * @param array $pagestats
4648 * @param int $tries
4649 * @return bool
4651 public function stats(array &$pagestats, $tries) {
4652 return true;
4656 * Formats the answers of this page for a report
4658 * @param object $answerpage
4659 * @param object $answerdata
4660 * @param object $useranswer
4661 * @param array $pagestats
4662 * @param int $i Count of first level answers
4663 * @param int $n Count of second level answers
4664 * @return object The answer page for this
4666 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
4667 $answers = $this->get_answers();
4668 $formattextdefoptions = new stdClass;
4669 $formattextdefoptions->para = false; //I'll use it widely in this page
4670 foreach ($answers as $answer) {
4671 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
4672 $answerdata->answers[] = array($data, "");
4673 $answerpage->answerdata = $answerdata;
4675 return $answerpage;
4679 * Gets an array of the jumps used by the answers of this page
4681 * @return array
4683 public function get_jumps() {
4684 global $DB;
4685 $jumps = array();
4686 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
4687 if ($answers = $this->get_answers()) {
4688 foreach ($answers as $answer) {
4689 $jumps[] = $this->get_jump_name($answer->jumpto);
4691 } else {
4692 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
4694 return $jumps;
4697 * Informs whether this page type require manual grading or not
4698 * @return bool
4700 public function requires_manual_grading() {
4701 return false;
4705 * A callback method that allows a page to override the next page a user will
4706 * see during when this page is being completed.
4707 * @return false|int
4709 public function override_next_page() {
4710 return false;
4714 * This method is used to determine if this page is a valid page
4716 * @param array $validpages
4717 * @param array $pageviews
4718 * @return int The next page id to check
4720 public function valid_page_and_view(&$validpages, &$pageviews) {
4721 $validpages[$this->properties->id] = 1;
4722 return $this->properties->nextpageid;
4726 * Get files from the page area file.
4728 * @param bool $includedirs whether or not include directories
4729 * @param int $updatedsince return files updated since this time
4730 * @return array list of stored_file objects
4731 * @since Moodle 3.2
4733 public function get_files($includedirs = true, $updatedsince = 0) {
4734 $fs = get_file_storage();
4735 return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id,
4736 'itemid, filepath, filename', $includedirs, $updatedsince);
4743 * Class used to represent an answer to a page
4745 * @property int $id The ID of this answer in the database
4746 * @property int $lessonid The ID of the lesson this answer belongs to
4747 * @property int $pageid The ID of the page this answer belongs to
4748 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
4749 * @property int $grade The grade this answer is worth
4750 * @property int $score The score this answer will give
4751 * @property int $flags Used to store options for the answer
4752 * @property int $timecreated A timestamp of when the answer was created
4753 * @property int $timemodified A timestamp of when the answer was modified
4754 * @property string $answer The answer itself
4755 * @property string $response The response the user sees if selecting this answer
4757 * @copyright 2009 Sam Hemelryk
4758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4760 class lesson_page_answer extends lesson_base {
4763 * Loads an page answer from the DB
4765 * @param int $id
4766 * @return lesson_page_answer
4768 public static function load($id) {
4769 global $DB;
4770 $answer = $DB->get_record("lesson_answers", array("id" => $id));
4771 return new lesson_page_answer($answer);
4775 * Given an object of properties and a page created answer(s) and saves them
4776 * in the database.
4778 * @param stdClass $properties
4779 * @param lesson_page $page
4780 * @return array
4782 public static function create($properties, lesson_page $page) {
4783 return $page->create_answers($properties);
4787 * Get files from the answer area file.
4789 * @param bool $includedirs whether or not include directories
4790 * @param int $updatedsince return files updated since this time
4791 * @return array list of stored_file objects
4792 * @since Moodle 3.2
4794 public function get_files($includedirs = true, $updatedsince = 0) {
4796 $lesson = lesson::load($this->properties->lessonid);
4797 $fs = get_file_storage();
4798 $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
4799 'itemid, filepath, filename', $includedirs, $updatedsince);
4800 $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
4801 'itemid, filepath, filename', $includedirs, $updatedsince);
4802 return array_merge($answerfiles, $responsefiles);
4808 * A management class for page types
4810 * This class is responsible for managing the different pages. A manager object can
4811 * be retrieved by calling the following line of code:
4812 * <code>
4813 * $manager = lesson_page_type_manager::get($lesson);
4814 * </code>
4815 * The first time the page type manager is retrieved the it includes all of the
4816 * different page types located in mod/lesson/pagetypes.
4818 * @copyright 2009 Sam Hemelryk
4819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4821 class lesson_page_type_manager {
4824 * An array of different page type classes
4825 * @var array
4827 protected $types = array();
4830 * Retrieves the lesson page type manager object
4832 * If the object hasn't yet been created it is created here.
4834 * @staticvar lesson_page_type_manager $pagetypemanager
4835 * @param lesson $lesson
4836 * @return lesson_page_type_manager
4838 public static function get(lesson $lesson) {
4839 static $pagetypemanager;
4840 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
4841 $pagetypemanager = new lesson_page_type_manager();
4842 $pagetypemanager->load_lesson_types($lesson);
4844 return $pagetypemanager;
4848 * Finds and loads all lesson page types in mod/lesson/pagetypes
4850 * @param lesson $lesson
4852 public function load_lesson_types(lesson $lesson) {
4853 global $CFG;
4854 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
4855 $dir = dir($basedir);
4856 while (false !== ($entry = $dir->read())) {
4857 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
4858 continue;
4860 require_once($basedir.$entry);
4861 $class = 'lesson_page_type_'.strtok($entry,'.');
4862 if (class_exists($class)) {
4863 $pagetype = new $class(new stdClass, $lesson);
4864 $this->types[$pagetype->typeid] = $pagetype;
4871 * Returns an array of strings to describe the loaded page types
4873 * @param int $type Can be used to return JUST the string for the requested type
4874 * @return array
4876 public function get_page_type_strings($type=null, $special=true) {
4877 $types = array();
4878 foreach ($this->types as $pagetype) {
4879 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
4880 $types[$pagetype->typeid] = $pagetype->typestring;
4883 return $types;
4887 * Returns the basic string used to identify a page type provided with an id
4889 * This string can be used to instantiate or identify the page type class.
4890 * If the page type id is unknown then 'unknown' is returned
4892 * @param int $id
4893 * @return string
4895 public function get_page_type_idstring($id) {
4896 foreach ($this->types as $pagetype) {
4897 if ((int)$pagetype->typeid === (int)$id) {
4898 return $pagetype->idstring;
4901 return 'unknown';
4905 * Loads a page for the provided lesson given it's id
4907 * This function loads a page from the lesson when given both the lesson it belongs
4908 * to as well as the page's id.
4909 * If the page doesn't exist an error is thrown
4911 * @param int $pageid The id of the page to load
4912 * @param lesson $lesson The lesson the page belongs to
4913 * @return lesson_page A class that extends lesson_page
4915 public function load_page($pageid, lesson $lesson) {
4916 global $DB;
4917 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
4918 print_error('cannotfindpages', 'lesson');
4920 $pagetype = get_class($this->types[$page->qtype]);
4921 $page = new $pagetype($page, $lesson);
4922 return $page;
4926 * This function detects errors in the ordering between 2 pages and updates the page records.
4928 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
4929 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
4931 protected function check_page_order($page1, $page2) {
4932 global $DB;
4933 if (empty($page1)) {
4934 if ($page2->prevpageid != 0) {
4935 debugging("***prevpageid of page " . $page2->id . " set to 0***");
4936 $page2->prevpageid = 0;
4937 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
4939 } else if (empty($page2)) {
4940 if ($page1->nextpageid != 0) {
4941 debugging("***nextpageid of page " . $page1->id . " set to 0***");
4942 $page1->nextpageid = 0;
4943 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
4945 } else {
4946 if ($page1->nextpageid != $page2->id) {
4947 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
4948 $page1->nextpageid = $page2->id;
4949 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
4951 if ($page2->prevpageid != $page1->id) {
4952 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
4953 $page2->prevpageid = $page1->id;
4954 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
4960 * This function loads ALL pages that belong to the lesson.
4962 * @param lesson $lesson
4963 * @return array An array of lesson_page_type_*
4965 public function load_all_pages(lesson $lesson) {
4966 global $DB;
4967 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
4968 return array(); // Records returned empty.
4970 foreach ($pages as $key=>$page) {
4971 $pagetype = get_class($this->types[$page->qtype]);
4972 $pages[$key] = new $pagetype($page, $lesson);
4975 $orderedpages = array();
4976 $lastpageid = 0;
4977 $morepages = true;
4978 while ($morepages) {
4979 $morepages = false;
4980 foreach ($pages as $page) {
4981 if ((int)$page->prevpageid === (int)$lastpageid) {
4982 // Check for errors in page ordering and fix them on the fly.
4983 $prevpage = null;
4984 if ($lastpageid !== 0) {
4985 $prevpage = $orderedpages[$lastpageid];
4987 $this->check_page_order($prevpage, $page);
4988 $morepages = true;
4989 $orderedpages[$page->id] = $page;
4990 unset($pages[$page->id]);
4991 $lastpageid = $page->id;
4992 if ((int)$page->nextpageid===0) {
4993 break 2;
4994 } else {
4995 break 1;
5001 // Add remaining pages and fix the nextpageid links for each page.
5002 foreach ($pages as $page) {
5003 // Check for errors in page ordering and fix them on the fly.
5004 $prevpage = null;
5005 if ($lastpageid !== 0) {
5006 $prevpage = $orderedpages[$lastpageid];
5008 $this->check_page_order($prevpage, $page);
5009 $orderedpages[$page->id] = $page;
5010 unset($pages[$page->id]);
5011 $lastpageid = $page->id;
5014 if ($lastpageid !== 0) {
5015 $this->check_page_order($orderedpages[$lastpageid], null);
5018 return $orderedpages;
5022 * Fetches an mform that can be used to create/edit an page
5024 * @param int $type The id for the page type
5025 * @param array $arguments Any arguments to pass to the mform
5026 * @return lesson_add_page_form_base
5028 public function get_page_form($type, $arguments) {
5029 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
5030 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
5031 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
5032 $class = 'lesson_add_page_form_selection';
5033 } else if ($class === 'lesson_add_page_form_unknown') {
5034 $class = 'lesson_add_page_form_selection';
5036 return new $class(null, $arguments);
5040 * Returns an array of links to use as add page links
5041 * @param int $previd The id of the previous page
5042 * @return array
5044 public function get_add_page_type_links($previd) {
5045 global $OUTPUT;
5047 $links = array();
5049 foreach ($this->types as $key=>$type) {
5050 if ($link = $type->add_page_link($previd)) {
5051 $links[$key] = $link;
5055 return $links;