1<?php
2
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.
14//
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/>.
17
18/**
19 * Local library file for Lesson.  These are non-standard functions that are used
20 * only by Lesson.
21 *
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 **/
26
27/** Make sure this isn't being directly accessed */
28defined('MOODLE_INTERNAL') || die();
29
30/** Include the files that are required by this module */
31require_once($CFG->dirroot.'/course/moodleform_mod.php');
32require_once($CFG->dirroot . '/mod/lesson/lib.php');
33require_once($CFG->libdir . '/filelib.php');
34
35/** This page */
36define('LESSON_THISPAGE', 0);
37/** Next page -> any page not seen before */
38define("LESSON_UNSEENPAGE", 1);
39/** Next page -> any page not answered correctly */
40define("LESSON_UNANSWEREDPAGE", 2);
41/** Jump to Next Page */
42define("LESSON_NEXTPAGE", -1);
43/** End of Lesson */
44define("LESSON_EOL", -9);
45/** Jump to an unseen page within a branch and end of branch or end of lesson */
46define("LESSON_UNSEENBRANCHPAGE", -50);
47/** Jump to Previous Page */
48define("LESSON_PREVIOUSPAGE", -40);
49/** Jump to a random page within a branch and end of branch or end of lesson */
50define("LESSON_RANDOMPAGE", -60);
51/** Jump to a random Branch */
52define("LESSON_RANDOMBRANCH", -70);
53/** Cluster Jump */
54define("LESSON_CLUSTERJUMP", -80);
55/** Undefined */
56define("LESSON_UNDEFINED", -99);
57
58/** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59define("LESSON_MAX_EVENT_LENGTH", "432000");
60
61/** Answer format is HTML */
62define("LESSON_ANSWER_HTML", "HTML");
63
64/** Placeholder answer for all other answers. */
65define("LESSON_OTHER_ANSWERS", "@#wronganswer#@");
66
67//////////////////////////////////////////////////////////////////////////////////////
68/// Any other lesson functions go here.  Each of them must have a name that
69/// starts with lesson_
70
71/**
72 * Checks to see if a LESSON_CLUSTERJUMP or
73 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
74 *
75 * This function is only executed when a teacher is
76 * checking the navigation for a lesson.
77 *
78 * @param stdClass $lesson Id of the lesson that is to be checked.
79 * @return boolean True or false.
80 **/
81function lesson_display_teacher_warning($lesson) {
82    global $DB;
83
84    // get all of the lesson answers
85    $params = array ("lessonid" => $lesson->id);
86    if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
87        // no answers, then not using cluster or unseen
88        return false;
89    }
90    // just check for the first one that fulfills the requirements
91    foreach ($lessonanswers as $lessonanswer) {
92        if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
93            return true;
94        }
95    }
96
97    // if no answers use either of the two jumps
98    return false;
99}
100
101/**
102 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
103 *
104 * will return the pageid of a random unseen page that is within a branch
105 *
106 * @param lesson $lesson
107 * @param int $userid Id of the user.
108 * @param int $pageid Id of the page from which we are jumping.
109 * @return int Id of the next page.
110 **/
111function lesson_unseen_question_jump($lesson, $user, $pageid) {
112    global $DB;
113
114    // get the number of retakes
115    if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
116        $retakes = 0;
117    }
118
119    // get all the lesson_attempts aka what the user has seen
120    if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
121        foreach($viewedpages as $viewed) {
122            $seenpages[] = $viewed->pageid;
123        }
124    } else {
125        $seenpages = array();
126    }
127
128    // get the lesson pages
129    $lessonpages = $lesson->load_all_pages();
130
131    if ($pageid == LESSON_UNSEENBRANCHPAGE) {  // this only happens when a student leaves in the middle of an unseen question within a branch series
132        $pageid = $seenpages[0];  // just change the pageid to the last page viewed inside the branch table
133    }
134
135    // go up the pages till branch table
136    while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
137        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
138            break;
139        }
140        $pageid = $lessonpages[$pageid]->prevpageid;
141    }
142
143    $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
144
145    // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
146    $unseen = array();
147    foreach($pagesinbranch as $page) {
148        if (!in_array($page->id, $seenpages)) {
149            $unseen[] = $page->id;
150        }
151    }
152
153    if(count($unseen) == 0) {
154        if(isset($pagesinbranch)) {
155            $temp = end($pagesinbranch);
156            $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
157        } else {
158            // there are no pages inside the branch, so return the next page
159            $nextpage = $lessonpages[$pageid]->nextpageid;
160        }
161        if ($nextpage == 0) {
162            return LESSON_EOL;
163        } else {
164            return $nextpage;
165        }
166    } else {
167        return $unseen[rand(0, count($unseen)-1)];  // returns a random page id for the next page
168    }
169}
170
171/**
172 * Handles the unseen branch table jump.
173 *
174 * @param lesson $lesson
175 * @param int $userid User id.
176 * @return int Will return the page id of a branch table or end of lesson
177 **/
178function lesson_unseen_branch_jump($lesson, $userid) {
179    global $DB;
180
181    if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
182        $retakes = 0;
183    }
184
185    if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
186        print_error('cannotfindrecords', 'lesson');
187    }
188
189    // get the lesson pages
190    $lessonpages = $lesson->load_all_pages();
191
192    // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
193    // which is the branch table that starts the unseenbranch function
194    $seen = array();
195    foreach ($seenbranches as $seenbranch) {
196        if (!$seenbranch->flag) {
197            $seen[$seenbranch->pageid] = $seenbranch->pageid;
198        } else {
199            $start = $seenbranch->pageid;
200            break;
201        }
202    }
203    // this function searches through the lesson pages to find all the branch tables
204    // that follow the flagged branch table
205    $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
206    $branchtables = array();
207    while ($pageid != 0) {  // grab all of the branch table till eol
208        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
209            $branchtables[] = $lessonpages[$pageid]->id;
210        }
211        $pageid = $lessonpages[$pageid]->nextpageid;
212    }
213    $unseen = array();
214    foreach ($branchtables as $branchtable) {
215        // load all of the unseen branch tables into unseen
216        if (!array_key_exists($branchtable, $seen)) {
217            $unseen[] = $branchtable;
218        }
219    }
220    if (count($unseen) > 0) {
221        return $unseen[rand(0, count($unseen)-1)];  // returns a random page id for the next page
222    } else {
223        return LESSON_EOL;  // has viewed all of the branch tables
224    }
225}
226
227/**
228 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
229 *
230 * @param lesson $lesson
231 * @param int $pageid The id of the page that we are jumping from (?)
232 * @return int The pageid of a random page that is within a branch table
233 **/
234function lesson_random_question_jump($lesson, $pageid) {
235    global $DB;
236
237    // get the lesson pages
238    $params = array ("lessonid" => $lesson->id);
239    if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
240        print_error('cannotfindpages', 'lesson');
241    }
242
243    // go up the pages till branch table
244    while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
245
246        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
247            break;
248        }
249        $pageid = $lessonpages[$pageid]->prevpageid;
250    }
251
252    // get the pages within the branch
253    $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
254
255    if(count($pagesinbranch) == 0) {
256        // there are no pages inside the branch, so return the next page
257        return $lessonpages[$pageid]->nextpageid;
258    } else {
259        return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id;  // returns a random page id for the next page
260    }
261}
262
263/**
264 * Calculates a user's grade for a lesson.
265 *
266 * @param object $lesson The lesson that the user is taking.
267 * @param int $retries The attempt number.
268 * @param int $userid Id of the user (optional, default current user).
269 * @return object { nquestions => number of questions answered
270                    attempts => number of question attempts
271                    total => max points possible
272                    earned => points earned by student
273                    grade => calculated percentage grade
274                    nmanual => number of manually graded questions
275                    manualpoints => point value for manually graded questions }
276 */
277function lesson_grade($lesson, $ntries, $userid = 0) {
278    global $USER, $DB;
279
280    if (empty($userid)) {
281        $userid = $USER->id;
282    }
283
284    // Zero out everything
285    $ncorrect     = 0;
286    $nviewed      = 0;
287    $score        = 0;
288    $nmanual      = 0;
289    $manualpoints = 0;
290    $thegrade     = 0;
291    $nquestions   = 0;
292    $total        = 0;
293    $earned       = 0;
294
295    $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
296    if ($useranswers = $DB->get_records_select("lesson_attempts",  "lessonid = :lessonid AND
297            userid = :userid AND retry = :retry", $params, "timeseen")) {
298        // group each try with its page
299        $attemptset = array();
300        foreach ($useranswers as $useranswer) {
301            $attemptset[$useranswer->pageid][] = $useranswer;
302        }
303
304        // Drop all attempts that go beyond max attempts for the lesson
305        foreach ($attemptset as $key => $set) {
306            $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
307        }
308
309        // get only the pages and their answers that the user answered
310        list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
311        array_unshift($parameters, $lesson->id);
312        $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
313        $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
314
315        // Number of pages answered
316        $nquestions = count($pages);
317
318        foreach ($attemptset as $attempts) {
319            $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
320            if ($lesson->custom) {
321                $attempt = end($attempts);
322                // If essay question, handle it, otherwise add to score
323                if ($page->requires_manual_grading()) {
324                    $useranswerobj = unserialize($attempt->useranswer);
325                    if (isset($useranswerobj->score)) {
326                        $earned += $useranswerobj->score;
327                    }
328                    $nmanual++;
329                    $manualpoints += $answers[$attempt->answerid]->score;
330                } else if (!empty($attempt->answerid)) {
331                    $earned += $page->earned_score($answers, $attempt);
332                }
333            } else {
334                foreach ($attempts as $attempt) {
335                    $earned += $attempt->correct;
336                }
337                $attempt = end($attempts); // doesn't matter which one
338                // If essay question, increase numbers
339                if ($page->requires_manual_grading()) {
340                    $nmanual++;
341                    $manualpoints++;
342                }
343            }
344            // Number of times answered
345            $nviewed += count($attempts);
346        }
347
348        if ($lesson->custom) {
349            $bestscores = array();
350            // Find the highest possible score per page to get our total
351            foreach ($answers as $answer) {
352                if(!isset($bestscores[$answer->pageid])) {
353                    $bestscores[$answer->pageid] = $answer->score;
354                } else if ($bestscores[$answer->pageid] < $answer->score) {
355                    $bestscores[$answer->pageid] = $answer->score;
356                }
357            }
358            $total = array_sum($bestscores);
359        } else {
360            // Check to make sure the student has answered the minimum questions
361            if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
362                // Nope, increase number viewed by the amount of unanswered questions
363                $total =  $nviewed + ($lesson->minquestions - $nquestions);
364            } else {
365                $total = $nviewed;
366            }
367        }
368    }
369
370    if ($total) { // not zero
371        $thegrade = round(100 * $earned / $total, 5);
372    }
373
374    // Build the grade information object
375    $gradeinfo               = new stdClass;
376    $gradeinfo->nquestions   = $nquestions;
377    $gradeinfo->attempts     = $nviewed;
378    $gradeinfo->total        = $total;
379    $gradeinfo->earned       = $earned;
380    $gradeinfo->grade        = $thegrade;
381    $gradeinfo->nmanual      = $nmanual;
382    $gradeinfo->manualpoints = $manualpoints;
383
384    return $gradeinfo;
385}
386
387/**
388 * Determines if a user can view the left menu.  The determining factor
389 * is whether a user has a grade greater than or equal to the lesson setting
390 * of displayleftif
391 *
392 * @param object $lesson Lesson object of the current lesson
393 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
394 **/
395function lesson_displayleftif($lesson) {
396    global $CFG, $USER, $DB;
397
398    if (!empty($lesson->displayleftif)) {
399        // get the current user's max grade for this lesson
400        $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
401        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)) {
402            if ($maxgrade->maxgrade < $lesson->displayleftif) {
403                return 0;  // turn off the displayleft
404            }
405        } else {
406            return 0; // no grades
407        }
408    }
409
410    // if we get to here, keep the original state of displayleft lesson setting
411    return $lesson->displayleft;
412}
413
414/**
415 *
416 * @param $cm
417 * @param $lesson
418 * @param $page
419 * @return unknown_type
420 */
421function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
422    $bc = lesson_menu_block_contents($cm->id, $lesson);
423    if (!empty($bc)) {
424        $regions = $page->blocks->get_regions();
425        $firstregion = reset($regions);
426        $page->blocks->add_fake_block($bc, $firstregion);
427    }
428
429    $bc = lesson_mediafile_block_contents($cm->id, $lesson);
430    if (!empty($bc)) {
431        $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
432    }
433
434    if (!empty($timer)) {
435        $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
436        if (!empty($bc)) {
437            $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
438        }
439    }
440}
441
442/**
443 * If there is a media file associated with this
444 * lesson, return a block_contents that displays it.
445 *
446 * @param int $cmid Course Module ID for this lesson
447 * @param object $lesson Full lesson record object
448 * @return block_contents
449 **/
450function lesson_mediafile_block_contents($cmid, $lesson) {
451    global $OUTPUT;
452    if (empty($lesson->mediafile)) {
453        return null;
454    }
455
456    $options = array();
457    $options['menubar'] = 0;
458    $options['location'] = 0;
459    $options['left'] = 5;
460    $options['top'] = 5;
461    $options['scrollbars'] = 1;
462    $options['resizable'] = 1;
463    $options['width'] = $lesson->mediawidth;
464    $options['height'] = $lesson->mediaheight;
465
466    $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
467    $action = new popup_action('click', $link, 'lessonmediafile', $options);
468    $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
469
470    $bc = new block_contents();
471    $bc->title = get_string('linkedmedia', 'lesson');
472    $bc->attributes['class'] = 'mediafile block';
473    $bc->content = $content;
474
475    return $bc;
476}
477
478/**
479 * If a timed lesson and not a teacher, then
480 * return a block_contents containing the clock.
481 *
482 * @param int $cmid Course Module ID for this lesson
483 * @param object $lesson Full lesson record object
484 * @param object $timer Full timer record object
485 * @return block_contents
486 **/
487function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
488    // Display for timed lessons and for students only
489    $context = context_module::instance($cmid);
490    if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
491        return null;
492    }
493
494    $content = '<div id="lesson-timer">';
495    $content .=  $lesson->time_remaining($timer->starttime);
496    $content .= '</div>';
497
498    $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
499    $page->requires->data_for_js('clocksettings', $clocksettings, true);
500    $page->requires->strings_for_js(array('timeisup'), 'lesson');
501    $page->requires->js('/mod/lesson/timer.js');
502    $page->requires->js_init_call('show_clock');
503
504    $bc = new block_contents();
505    $bc->title = get_string('timeremaining', 'lesson');
506    $bc->attributes['class'] = 'clock block';
507    $bc->content = $content;
508
509    return $bc;
510}
511
512/**
513 * If left menu is turned on, then this will
514 * print the menu in a block
515 *
516 * @param int $cmid Course Module ID for this lesson
517 * @param lesson $lesson Full lesson record object
518 * @return void
519 **/
520function lesson_menu_block_contents($cmid, $lesson) {
521    global $CFG, $DB;
522
523    if (!$lesson->displayleft) {
524        return null;
525    }
526
527    $pages = $lesson->load_all_pages();
528    foreach ($pages as $page) {
529        if ((int)$page->prevpageid === 0) {
530            $pageid = $page->id;
531            break;
532        }
533    }
534    $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
535
536    if (!$pageid || !$pages) {
537        return null;
538    }
539
540    $content = '<a href="#maincontent" class="accesshide">' .
541        get_string('skip', 'lesson') .
542        "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
543
544    while ($pageid != 0) {
545        $page = $pages[$pageid];
546
547        // Only process branch tables with display turned on
548        if ($page->displayinmenublock && $page->display) {
549            if ($page->id == $currentpageid) {
550                $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
551            } else {
552                $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&amp;pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
553            }
554
555        }
556        $pageid = $page->nextpageid;
557    }
558    $content .= "</ul>\n</div>\n";
559
560    $bc = new block_contents();
561    $bc->title = get_string('lessonmenu', 'lesson');
562    $bc->attributes['class'] = 'menu block';
563    $bc->content = $content;
564
565    return $bc;
566}
567
568/**
569 * Adds header buttons to the page for the lesson
570 *
571 * @param object $cm
572 * @param object $context
573 * @param bool $extraeditbuttons
574 * @param int $lessonpageid
575 */
576function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
577    global $CFG, $PAGE, $OUTPUT;
578    if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
579        if ($lessonpageid === null) {
580            print_error('invalidpageid', 'lesson');
581        }
582        if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
583            $url = new moodle_url('/mod/lesson/editpage.php', array(
584                'id'       => $cm->id,
585                'pageid'   => $lessonpageid,
586                'edit'     => 1,
587                'returnto' => $PAGE->url->out_as_local_url(false)
588            ));
589            $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
590        }
591    }
592}
593
594/**
595 * This is a function used to detect media types and generate html code.
596 *
597 * @global object $CFG
598 * @global object $PAGE
599 * @param object $lesson
600 * @param object $context
601 * @return string $code the html code of media
602 */
603function lesson_get_media_html($lesson, $context) {
604    global $CFG, $PAGE, $OUTPUT;
605    require_once("$CFG->libdir/resourcelib.php");
606
607    // get the media file link
608    if (strpos($lesson->mediafile, '://') !== false) {
609        $url = new moodle_url($lesson->mediafile);
610    } else {
611        // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
612        $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
613    }
614    $title = $lesson->mediafile;
615
616    $clicktoopen = html_writer::link($url, get_string('download'));
617
618    $mimetype = resourcelib_guess_url_mimetype($url);
619
620    $extension = resourcelib_get_extension($url->out(false));
621
622    $mediamanager = core_media_manager::instance($PAGE);
623    $embedoptions = array(
624        core_media_manager::OPTION_TRUSTED => true,
625        core_media_manager::OPTION_BLOCK => true
626    );
627
628    // find the correct type and print it out
629    if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) {  // It's an image
630        $code = resourcelib_embed_image($url, $title);
631
632    } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
633        // Media (audio/video) file.
634        $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
635
636    } else {
637        // anything else - just try object tag enlarged as much as possible
638        $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
639    }
640
641    return $code;
642}
643
644/**
645 * Logic to happen when a/some group(s) has/have been deleted in a course.
646 *
647 * @param int $courseid The course ID.
648 * @param int $groupid The group id if it is known
649 * @return void
650 */
651function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
652    global $DB;
653
654    $params = array('courseid' => $courseid);
655    if ($groupid) {
656        $params['groupid'] = $groupid;
657        // We just update the group that was deleted.
658        $sql = "SELECT o.id, o.lessonid
659                  FROM {lesson_overrides} o
660                  JOIN {lesson} lesson ON lesson.id = o.lessonid
661                 WHERE lesson.course = :courseid
662                   AND o.groupid = :groupid";
663    } else {
664        // No groupid, we update all orphaned group overrides for all lessons in course.
665        $sql = "SELECT o.id, o.lessonid
666                  FROM {lesson_overrides} o
667                  JOIN {lesson} lesson ON lesson.id = o.lessonid
668             LEFT JOIN {groups} grp ON grp.id = o.groupid
669                 WHERE lesson.course = :courseid
670                   AND o.groupid IS NOT NULL
671                   AND grp.id IS NULL";
672    }
673    $records = $DB->get_records_sql_menu($sql, $params);
674    if (!$records) {
675        return; // Nothing to do.
676    }
677    $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
678}
679
680/**
681 * Return the overview report table and data.
682 *
683 * @param  lesson $lesson       lesson instance
684 * @param  mixed $currentgroup  false if not group used, 0 for all groups, group id (int) to filter by that groups
685 * @return mixed false if there is no information otherwise html_table and stdClass with the table and data
686 * @since  Moodle 3.3
687 */
688function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) {
689    global $DB, $CFG, $OUTPUT;
690    require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
691
692    $context = $lesson->context;
693    $cm = $lesson->cm;
694    // Count the number of branch and question pages in this lesson.
695    $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE));
696    $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount);
697
698    // Only load students if there attempts for this lesson.
699    $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id));
700    $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id));
701    $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id));
702    if ($attempts or $branches or $timer) {
703        list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
704        list($sort, $sortparams) = users_order_by_sql('u');
705
706        $extrafields = get_extra_user_fields($context);
707
708        $params['a1lessonid'] = $lesson->id;
709        $params['b1lessonid'] = $lesson->id;
710        $params['c1lessonid'] = $lesson->id;
711        $ufields = user_picture::fields('u', $extrafields);
712        $sql = "SELECT DISTINCT $ufields
713                FROM {user} u
714                JOIN (
715                    SELECT userid, lessonid FROM {lesson_attempts} a1
716                    WHERE a1.lessonid = :a1lessonid
717                        UNION
718                    SELECT userid, lessonid FROM {lesson_branch} b1
719                    WHERE b1.lessonid = :b1lessonid
720                        UNION
721                    SELECT userid, lessonid FROM {lesson_timer} c1
722                    WHERE c1.lessonid = :c1lessonid
723                    ) a ON u.id = a.userid
724                JOIN ($esql) ue ON ue.id = a.userid
725                ORDER BY $sort";
726
727        $students = $DB->get_recordset_sql($sql, $params);
728        if (!$students->valid()) {
729            $students->close();
730            return array(false, false);
731        }
732    } else {
733        return array(false, false);
734    }
735
736    if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) {
737        $grades = array();
738    }
739
740    if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) {
741        $times = array();
742    }
743
744    // Build an array for output.
745    $studentdata = array();
746
747    $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen');
748    foreach ($attempts as $attempt) {
749        // 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.
750        if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) {
751            // restore/setup defaults
752            $n = 0;
753            $timestart = 0;
754            $timeend = 0;
755            $usergrade = null;
756            $eol = 0;
757
758            // search for the grade record for this try. if not there, the nulls defined above will be used.
759            foreach($grades as $grade) {
760                // check to see if the grade matches the correct user
761                if ($grade->userid == $attempt->userid) {
762                    // see if n is = to the retry
763                    if ($n == $attempt->retry) {
764                        // get grade info
765                        $usergrade = round($grade->grade, 2); // round it here so we only have to do it once
766                        break;
767                    }
768                    $n++; // if not equal, then increment n
769                }
770            }
771            $n = 0;
772            // search for the time record for this try. if not there, the nulls defined above will be used.
773            foreach($times as $time) {
774                // check to see if the grade matches the correct user
775                if ($time->userid == $attempt->userid) {
776                    // see if n is = to the retry
777                    if ($n == $attempt->retry) {
778                        // get grade info
779                        $timeend = $time->lessontime;
780                        $timestart = $time->starttime;
781                        $eol = $time->completed;
782                        break;
783                    }
784                    $n++; // if not equal, then increment n
785                }
786            }
787
788            // build up the array.
789            // this array represents each student and all of their tries at the lesson
790            $studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart,
791                                                                    "timeend" => $timeend,
792                                                                    "grade" => $usergrade,
793                                                                    "end" => $eol,
794                                                                    "try" => $attempt->retry,
795                                                                    "userid" => $attempt->userid);
796        }
797    }
798    $attempts->close();
799
800    $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen');
801    foreach ($branches as $branch) {
802        // 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.
803        if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) {
804            // Restore/setup defaults.
805            $n = 0;
806            $timestart = 0;
807            $timeend = 0;
808            $usergrade = null;
809            $eol = 0;
810            // Search for the time record for this try. if not there, the nulls defined above will be used.
811            foreach ($times as $time) {
812                // Check to see if the grade matches the correct user.
813                if ($time->userid == $branch->userid) {
814                    // See if n is = to the retry.
815                    if ($n == $branch->retry) {
816                        // Get grade info.
817                        $timeend = $time->lessontime;
818                        $timestart = $time->starttime;
819                        $eol = $time->completed;
820                        break;
821                    }
822                    $n++; // If not equal, then increment n.
823                }
824            }
825
826            // Build up the array.
827            // This array represents each student and all of their tries at the lesson.
828            $studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart,
829                                                                    "timeend" => $timeend,
830                                                                    "grade" => $usergrade,
831                                                                    "end" => $eol,
832                                                                    "try" => $branch->retry,
833                                                                    "userid" => $branch->userid);
834        }
835    }
836    $branches->close();
837
838    // Need the same thing for timed entries that were not completed.
839    foreach ($times as $time) {
840        $endoflesson = $time->completed;
841        // If the time start is the same with another record then we shouldn't be adding another item to this array.
842        if (isset($studentdata[$time->userid])) {
843            $foundmatch = false;
844            $n = 0;
845            foreach ($studentdata[$time->userid] as $key => $value) {
846                if ($value['timestart'] == $time->starttime) {
847                    // Don't add this to the array.
848                    $foundmatch = true;
849                    break;
850                }
851            }
852            $n = count($studentdata[$time->userid]) + 1;
853            if (!$foundmatch) {
854                // Add a record.
855                $studentdata[$time->userid][] = array(
856                                "timestart" => $time->starttime,
857                                "timeend" => $time->lessontime,
858                                "grade" => null,
859                                "end" => $endoflesson,
860                                "try" => $n,
861                                "userid" => $time->userid
862                            );
863            }
864        } else {
865            $studentdata[$time->userid][] = array(
866                                "timestart" => $time->starttime,
867                                "timeend" => $time->lessontime,
868                                "grade" => null,
869                                "end" => $endoflesson,
870                                "try" => 0,
871                                "userid" => $time->userid
872                            );
873        }
874    }
875
876    // To store all the data to be returned by the function.
877    $data = new stdClass();
878
879    // Determine if lesson should have a score.
880    if ($branchcount > 0 AND $questioncount == 0) {
881        // This lesson only contains content pages and is not graded.
882        $data->lessonscored = false;
883    } else {
884        // This lesson is graded.
885        $data->lessonscored = true;
886    }
887    // set all the stats variables
888    $data->numofattempts = 0;
889    $data->avescore      = 0;
890    $data->avetime       = 0;
891    $data->highscore     = null;
892    $data->lowscore      = null;
893    $data->hightime      = null;
894    $data->lowtime       = null;
895    $data->students      = array();
896
897    $table = new html_table();
898
899    $headers = [get_string('name')];
900
901    foreach ($extrafields as $field) {
902        $headers[] = get_user_field_name($field);
903    }
904
905    $caneditlesson = has_capability('mod/lesson:edit', $context);
906    $attemptsheader = get_string('attempts', 'lesson');
907    if ($caneditlesson) {
908        $selectall = get_string('selectallattempts', 'lesson');
909        $deselectall = get_string('deselectallattempts', 'lesson');
910        // Build the select/deselect all control.
911        $selectallid = 'selectall-attempts';
912        $mastercheckbox = new \core\output\checkbox_toggleall('lesson-attempts', true, [
913            'id' => $selectallid,
914            'name' => $selectallid,
915            'value' => 1,
916            'label' => $selectall,
917            'selectall' => $selectall,
918            'deselectall' => $deselectall,
919            'labelclasses' => 'form-check-label'
920        ]);
921        $attemptsheader = $OUTPUT->render($mastercheckbox);
922    }
923    $headers [] = $attemptsheader;
924
925    // Set up the table object.
926    if ($data->lessonscored) {
927        $headers [] = get_string('highscore', 'lesson');
928    }
929
930    $colcount = count($headers);
931
932    $table->head = $headers;
933
934    $table->align = [];
935    $table->align = array_pad($table->align, $colcount, 'center');
936    $table->align[$colcount - 1] = 'left';
937
938    if ($data->lessonscored) {
939        $table->align[$colcount - 2] = 'left';
940    }
941
942    $table->wrap = [];
943    $table->wrap = array_pad($table->wrap, $colcount, 'nowrap');
944
945    $table->attributes['class'] = 'table table-striped';
946
947    // print out the $studentdata array
948    // going through each student that has attempted the lesson, so, each student should have something to be displayed
949    foreach ($students as $student) {
950        // check to see if the student has attempts to print out
951        if (array_key_exists($student->id, $studentdata)) {
952            // set/reset some variables
953            $attempts = array();
954            $dataforstudent = new stdClass;
955            $dataforstudent->attempts = array();
956            // gather the data for each user attempt
957            $bestgrade = 0;
958
959            // $tries holds all the tries/retries a student has done
960            $tries = $studentdata[$student->id];
961            $studentname = fullname($student, true);
962
963            foreach ($tries as $try) {
964                $dataforstudent->attempts[] = $try;
965
966                // Start to build up the checkbox and link.
967                $attempturlparams = [
968                    'id' => $cm->id,
969                    'action' => 'reportdetail',
970                    'userid' => $try['userid'],
971                    'try' => $try['try'],
972                ];
973
974                if ($try["grade"] !== null) { // if null then not done yet
975                    // this is what the link does when the user has completed the try
976                    $timetotake = $try["timeend"] - $try["timestart"];
977
978                    if ($try["grade"] > $bestgrade) {
979                        $bestgrade = $try["grade"];
980                    }
981
982                    $attemptdata = (object)[
983                        'grade' => $try["grade"],
984                        'timestart' => userdate($try["timestart"]),
985                        'duration' => format_time($timetotake),
986                    ];
987                    $attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata);
988
989                } else {
990                    if ($try["end"]) {
991                        // User finished the lesson but has no grade. (Happens when there are only content pages).
992                        $timetotake = $try["timeend"] - $try["timestart"];
993                        $attemptdata = (object)[
994                            'timestart' => userdate($try["timestart"]),
995                            'duration' => format_time($timetotake),
996                        ];
997                        $attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata);
998                    } else {
999                        // This is what the link does/looks like when the user has not completed the attempt.
1000                        if ($try['timestart'] !== 0) {
1001                            // Teacher previews do not track time spent.
1002                            $attemptlinkcontents = get_string("notcompletedwithdate", "lesson", userdate($try["timestart"]));
1003                        } else {
1004                            $attemptlinkcontents = get_string("notcompleted", "lesson");
1005                        }
1006                        $timetotake = null;
1007                    }
1008                }
1009                $attempturl = new moodle_url('/mod/lesson/report.php', $attempturlparams);
1010                $attemptlink = html_writer::link($attempturl, $attemptlinkcontents, ['class' => 'lesson-attempt-link']);
1011
1012                if ($caneditlesson) {
1013                    $attemptid = 'attempt-' . $try['userid'] . '-' . $try['try'];
1014                    $attemptname = 'attempts[' . $try['userid'] . '][' . $try['try'] . ']';
1015
1016                    $checkbox = new \core\output\checkbox_toggleall('lesson-attempts', false, [
1017                        'id' => $attemptid,
1018                        'name' => $attemptname,
1019                        'label' => $attemptlink
1020                    ]);
1021                    $attemptlink = $OUTPUT->render($checkbox);
1022                }
1023
1024                // build up the attempts array
1025                $attempts[] = $attemptlink;
1026
1027                // Run these lines for the stats only if the user finnished the lesson.
1028                if ($try["end"]) {
1029                    // User has completed the lesson.
1030                    $data->numofattempts++;
1031                    $data->avetime += $timetotake;
1032                    if ($timetotake > $data->hightime || $data->hightime == null) {
1033                        $data->hightime = $timetotake;
1034                    }
1035                    if ($timetotake < $data->lowtime || $data->lowtime == null) {
1036                        $data->lowtime = $timetotake;
1037                    }
1038                    if ($try["grade"] !== null) {
1039                        // The lesson was scored.
1040                        $data->avescore += $try["grade"];
1041                        if ($try["grade"] > $data->highscore || $data->highscore === null) {
1042                            $data->highscore = $try["grade"];
1043                        }
1044                        if ($try["grade"] < $data->lowscore || $data->lowscore === null) {
1045                            $data->lowscore = $try["grade"];
1046                        }
1047
1048                    }
1049                }
1050            }
1051            // get line breaks in after each attempt
1052            $attempts = implode("<br />\n", $attempts);
1053            $row = [$studentname];
1054
1055            foreach ($extrafields as $field) {
1056                $row[] = $student->$field;
1057            }
1058
1059            $row[] = $attempts;
1060
1061            if ($data->lessonscored) {
1062                // Add the grade if the lesson is graded.
1063                $row[] = $bestgrade."%";
1064            }
1065
1066            $table->data[] = $row;
1067
1068            // Add the student data.
1069            $dataforstudent->id = $student->id;
1070            $dataforstudent->fullname = $studentname;
1071            $dataforstudent->bestgrade = $bestgrade;
1072            $data->students[] = $dataforstudent;
1073        }
1074    }
1075    $students->close();
1076    if ($data->numofattempts > 0) {
1077        $data->avescore = $data->avescore / $data->numofattempts;
1078    }
1079
1080    return array($table, $data);
1081}
1082
1083/**
1084 * Return information about one user attempt (including answers)
1085 * @param  lesson $lesson  lesson instance
1086 * @param  int $userid     the user id
1087 * @param  int $attempt    the attempt number
1088 * @return array the user answers (array) and user data stats (object)
1089 * @since  Moodle 3.3
1090 */
1091function lesson_get_user_detailed_report_data(lesson $lesson, $userid, $attempt) {
1092    global $DB;
1093
1094    $context = $lesson->context;
1095    if (!empty($userid)) {
1096        // Apply overrides.
1097        $lesson->update_effective_access($userid);
1098    }
1099
1100    $pageid = 0;
1101    $lessonpages = $lesson->load_all_pages();
1102    foreach ($lessonpages as $lessonpage) {
1103        if ($lessonpage->prevpageid == 0) {
1104            $pageid = $lessonpage->id;
1105        }
1106    }
1107
1108    // now gather the stats into an object
1109    $firstpageid = $pageid;
1110    $pagestats = array();
1111    while ($pageid != 0) { // EOL
1112        $page = $lessonpages[$pageid];
1113        $params = array ("lessonid" => $lesson->id, "pageid" => $page->id);
1114        if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) {
1115            // get them ready for processing
1116            $orderedanswers = array();
1117            foreach ($allanswers as $singleanswer) {
1118                // ordering them like this, will help to find the single attempt record that we want to keep.
1119                $orderedanswers[$singleanswer->userid][$singleanswer->retry][] = $singleanswer;
1120            }
1121            // this is foreach user and for each try for that user, keep one attempt record
1122            foreach ($orderedanswers as $orderedanswer) {
1123                foreach($orderedanswer as $tries) {
1124                    $page->stats($pagestats, $tries);
1125                }
1126            }
1127        } else {
1128            // no one answered yet...
1129        }
1130        //unset($orderedanswers);  initialized above now
1131        $pageid = $page->nextpageid;
1132    }
1133
1134    $manager = lesson_page_type_manager::get($lesson);
1135    $qtypes = $manager->get_page_type_strings();
1136
1137    $answerpages = array();
1138    $answerpage = "";
1139    $pageid = $firstpageid;
1140    // cycle through all the pages
1141    //  foreach page, add to the $answerpages[] array all the data that is needed
1142    //  from the question, the users attempt, and the statistics
1143    // grayout pages that the user did not answer and Branch, end of branch, cluster
1144    // and end of cluster pages
1145    while ($pageid != 0) { // EOL
1146        $page = $lessonpages[$pageid];
1147        $answerpage = new stdClass;
1148        // Keep the original page object.
1149        $answerpage->page = $page;
1150        $data ='';
1151
1152        $answerdata = new stdClass;
1153        // Set some defaults for the answer data.
1154        $answerdata->score = null;
1155        $answerdata->response = null;
1156        $answerdata->responseformat = FORMAT_PLAIN;
1157
1158        $answerpage->title = format_string($page->title);
1159
1160        $options = new stdClass;
1161        $options->noclean = true;
1162        $options->overflowdiv = true;
1163        $options->context = $context;
1164        $answerpage->contents = format_text($page->contents, $page->contentsformat, $options);
1165
1166        $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string();
1167        $answerpage->grayout = $page->grayout;
1168        $answerpage->context = $context;
1169
1170        if (empty($userid)) {
1171            // there is no userid, so set these vars and display stats.
1172            $answerpage->grayout = 0;
1173            $useranswer = null;
1174        } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) {
1175            // get the user's answer for this page
1176            // need to find the right one
1177            $i = 0;
1178            foreach ($useranswers as $userattempt) {
1179                $useranswer = $userattempt;
1180                $i++;
1181                if ($lesson->maxattempts == $i) {
1182                    break; // reached maxattempts, break out
1183                }
1184            }
1185        } else {
1186            // user did not answer this page, gray it out and set some nulls
1187            $answerpage->grayout = 1;
1188            $useranswer = null;
1189        }
1190        $i = 0;
1191        $n = 0;
1192        $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
1193        $pageid = $page->nextpageid;
1194    }
1195
1196    $userstats = new stdClass;
1197    if (!empty($userid)) {
1198        $params = array("lessonid"=>$lesson->id, "userid"=>$userid);
1199
1200        $alreadycompleted = true;
1201
1202        if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
1203            $userstats->grade = -1;
1204            $userstats->completed = -1;
1205            $alreadycompleted = false;
1206        } else {
1207            $userstats->grade = current($grades);
1208            $userstats->completed = $userstats->grade->completed;
1209            $userstats->grade = round($userstats->grade->grade, 2);
1210        }
1211
1212        if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
1213            $userstats->timetotake = -1;
1214            $alreadycompleted = false;
1215        } else {
1216            $userstats->timetotake = current($times);
1217            $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime;
1218        }
1219
1220        if ($alreadycompleted) {
1221            $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid);
1222        }
1223    }
1224
1225    return array($answerpages, $userstats);
1226}
1227
1228/**
1229 * Return user's deadline for all lessons in a course, hereby taking into account group and user overrides.
1230 *
1231 * @param int $courseid the course id.
1232 * @return object An object with of all lessonsids and close unixdates in this course,
1233 * taking into account the most lenient overrides, if existing and 0 if no close date is set.
1234 */
1235function lesson_get_user_deadline($courseid) {
1236    global $DB, $USER;
1237
1238    // For teacher and manager/admins return lesson's deadline.
1239    if (has_capability('moodle/course:update', context_course::instance($courseid))) {
1240        $sql = "SELECT lesson.id, lesson.deadline AS userdeadline
1241                  FROM {lesson} lesson
1242                 WHERE lesson.course = :courseid";
1243
1244        $results = $DB->get_records_sql($sql, array('courseid' => $courseid));
1245        return $results;
1246    }
1247
1248    $sql = "SELECT a.id,
1249                   COALESCE(v.userclose, v.groupclose, a.deadline, 0) AS userdeadline
1250              FROM (
1251                      SELECT lesson.id as lessonid,
1252                             MAX(leo.deadline) AS userclose, MAX(qgo.deadline) AS groupclose
1253                        FROM {lesson} lesson
1254                   LEFT JOIN {lesson_overrides} leo on lesson.id = leo.lessonid AND leo.userid = :userid
1255                   LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
1256                   LEFT JOIN {lesson_overrides} qgo on lesson.id = qgo.lessonid AND qgo.groupid = gm.groupid
1257                       WHERE lesson.course = :courseid
1258                    GROUP BY lesson.id
1259                   ) v
1260              JOIN {lesson} a ON a.id = v.lessonid";
1261
1262    $results = $DB->get_records_sql($sql, array('userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid));
1263    return $results;
1264
1265}
1266
1267/**
1268 * Abstract class that page type's MUST inherit from.
1269 *
1270 * This is the abstract class that ALL add page type forms must extend.
1271 * You will notice that all but two of the methods this class contains are final.
1272 * Essentially the only thing that extending classes can do is extend custom_definition.
1273 * OR if it has a special requirement on creation it can extend construction_override
1274 *
1275 * @abstract
1276 * @copyright  2009 Sam Hemelryk
1277 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1278 */
1279abstract class lesson_add_page_form_base extends moodleform {
1280
1281    /**
1282     * This is the classic define that is used to identify this pagetype.
1283     * Will be one of LESSON_*
1284     * @var int
1285     */
1286    public $qtype;
1287
1288    /**
1289     * The simple string that describes the page type e.g. truefalse, multichoice
1290     * @var string
1291     */
1292    public $qtypestring;
1293
1294    /**
1295     * An array of options used in the htmleditor
1296     * @var array
1297     */
1298    protected $editoroptions = array();
1299
1300    /**
1301     * True if this is a standard page of false if it does something special.
1302     * Questions are standard pages, branch tables are not
1303     * @var bool
1304     */
1305    protected $standard = true;
1306
1307    /**
1308     * Answer format supported by question type.
1309     */
1310    protected $answerformat = '';
1311
1312    /**
1313     * Response format supported by question type.
1314     */
1315    protected $responseformat = '';
1316
1317    /**
1318     * Each page type can and should override this to add any custom elements to
1319     * the basic form that they want
1320     */
1321    public function custom_definition() {}
1322
1323    /**
1324     * Returns answer format used by question type.
1325     */
1326    public function get_answer_format() {
1327        return $this->answerformat;
1328    }
1329
1330    /**
1331     * Returns response format used by question type.
1332     */
1333    public function get_response_format() {
1334        return $this->responseformat;
1335    }
1336
1337    /**
1338     * Used to determine if this is a standard page or a special page
1339     * @return bool
1340     */
1341    public final function is_standard() {
1342        return (bool)$this->standard;
1343    }
1344
1345    /**
1346     * Add the required basic elements to the form.
1347     *
1348     * This method adds the basic elements to the form including title and contents
1349     * and then calls custom_definition();
1350     */
1351    public final function definition() {
1352        global $CFG;
1353        $mform = $this->_form;
1354        $editoroptions = $this->_customdata['editoroptions'];
1355
1356        if ($this->qtypestring != 'selectaqtype') {
1357            if ($this->_customdata['edit']) {
1358                $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring, 'lesson'));
1359            } else {
1360                $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring, 'lesson'));
1361            }
1362        }
1363
1364        if (!empty($this->_customdata['returnto'])) {
1365            $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
1366            $mform->setType('returnto', PARAM_LOCALURL);
1367        }
1368
1369        $mform->addElement('hidden', 'id');
1370        $mform->setType('id', PARAM_INT);
1371
1372        $mform->addElement('hidden', 'pageid');
1373        $mform->setType('pageid', PARAM_INT);
1374
1375        if ($this->standard === true) {
1376            $mform->addElement('hidden', 'qtype');
1377            $mform->setType('qtype', PARAM_INT);
1378
1379            $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1380            $mform->addRule('title', get_string('required'), 'required', null, 'client');
1381            if (!empty($CFG->formatstringstriptags)) {
1382                $mform->setType('title', PARAM_TEXT);
1383            } else {
1384                $mform->setType('title', PARAM_CLEANHTML);
1385            }
1386
1387            $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
1388            $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
1389            $mform->setType('contents_editor', PARAM_RAW);
1390            $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1391        }
1392
1393        $this->custom_definition();
1394
1395        if ($this->_customdata['edit'] === true) {
1396            $mform->addElement('hidden', 'edit', 1);
1397            $mform->setType('edit', PARAM_BOOL);
1398            $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1399        } else if ($this->qtype === 'questiontype') {
1400            $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1401        } else {
1402            $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1403        }
1404    }
1405
1406    /**
1407     * Convenience function: Adds a jumpto select element
1408     *
1409     * @param string $name
1410     * @param string|null $label
1411     * @param int $selected The page to select by default
1412     */
1413    protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
1414        $title = get_string("jump", "lesson");
1415        if ($label === null) {
1416            $label = $title;
1417        }
1418        if (is_int($name)) {
1419            $name = "jumpto[$name]";
1420        }
1421        $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
1422        $this->_form->setDefault($name, $selected);
1423        $this->_form->addHelpButton($name, 'jumps', 'lesson');
1424    }
1425
1426    /**
1427     * Convenience function: Adds a score input element
1428     *
1429     * @param string $name
1430     * @param string|null $label
1431     * @param mixed $value The default value
1432     */
1433    protected final function add_score($name, $label=null, $value=null) {
1434        if ($label === null) {
1435            $label = get_string("score", "lesson");
1436        }
1437
1438        if (is_int($name)) {
1439            $name = "score[$name]";
1440        }
1441        $this->_form->addElement('text', $name, $label, array('size'=>5));
1442        $this->_form->setType($name, PARAM_INT);
1443        if ($value !== null) {
1444            $this->_form->setDefault($name, $value);
1445        }
1446        $this->_form->addHelpButton($name, 'score', 'lesson');
1447
1448        // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1449        if (!$this->_customdata['lesson']->custom) {
1450            $this->_form->freeze($name);
1451        }
1452    }
1453
1454    /**
1455     * Convenience function: Adds an answer editor
1456     *
1457     * @param int $count The count of the element to add
1458     * @param string $label, null means default
1459     * @param bool $required
1460     * @param string $format
1461     * @param array $help Add help text via the addHelpButton. Must be an array which contains the string identifier and
1462     *                      component as it's elements
1463     * @return void
1464     */
1465    protected final function add_answer($count, $label = null, $required = false, $format= '', array $help = []) {
1466        if ($label === null) {
1467            $label = get_string('answer', 'lesson');
1468        }
1469
1470        if ($format == LESSON_ANSWER_HTML) {
1471            $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
1472                    array('rows' => '4', 'columns' => '80'),
1473                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1474            $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
1475            $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1476        } else {
1477            $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
1478                array('size' => '50', 'maxlength' => '200'));
1479            $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
1480        }
1481
1482        if ($required) {
1483            $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1484        }
1485
1486        if ($help) {
1487            $this->_form->addHelpButton("answer_editor[$count]", $help['identifier'], $help['component']);
1488        }
1489    }
1490    /**
1491     * Convenience function: Adds an response editor
1492     *
1493     * @param int $count The count of the element to add
1494     * @param string $label, null means default
1495     * @param bool $required
1496     * @return void
1497     */
1498    protected final function add_response($count, $label = null, $required = false) {
1499        if ($label === null) {
1500            $label = get_string('response', 'lesson');
1501        }
1502        $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
1503                 array('rows' => '4', 'columns' => '80'),
1504                 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1505        $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
1506        $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1507
1508        if ($required) {
1509            $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1510        }
1511    }
1512
1513    /**
1514     * A function that gets called upon init of this object by the calling script.
1515     *
1516     * This can be used to process an immediate action if required. Currently it
1517     * is only used in special cases by non-standard page types.
1518     *
1519     * @return bool
1520     */
1521    public function construction_override($pageid, lesson $lesson) {
1522        return true;
1523    }
1524}
1525
1526
1527
1528/**
1529 * Class representation of a lesson
1530 *
1531 * This class is used the interact with, and manage a lesson once instantiated.
1532 * If you need to fetch a lesson object you can do so by calling
1533 *
1534 * <code>
1535 * lesson::load($lessonid);
1536 * // or
1537 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1538 * $lesson = new lesson($lessonrecord);
1539 * </code>
1540 *
1541 * The class itself extends lesson_base as all classes within the lesson module should
1542 *
1543 * These properties are from the database
1544 * @property int $id The id of this lesson
1545 * @property int $course The ID of the course this lesson belongs to
1546 * @property string $name The name of this lesson
1547 * @property int $practice Flag to toggle this as a practice lesson
1548 * @property int $modattempts Toggle to allow the user to go back and review answers
1549 * @property int $usepassword Toggle the use of a password for entry
1550 * @property string $password The password to require users to enter
1551 * @property int $dependency ID of another lesson this lesson is dependent on
1552 * @property string $conditions Conditions of the lesson dependency
1553 * @property int $grade The maximum grade a user can achieve (%)
1554 * @property int $custom Toggle custom scoring on or off
1555 * @property int $ongoing Toggle display of an ongoing score
1556 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1557 * @property int $maxanswers The max number of answers or branches
1558 * @property int $maxattempts The maximum number of attempts a user can record
1559 * @property int $review Toggle use or wrong answer review button
1560 * @property int $nextpagedefault Override the default next page
1561 * @property int $feedback Toggles display of default feedback
1562 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1563 * @property int $maxpages Maximum number of pages this lesson can contain
1564 * @property int $retake Flag to allow users to retake a lesson
1565 * @property int $activitylink Relate this lesson to another lesson
1566 * @property string $mediafile File to pop up to or webpage to display
1567 * @property int $mediaheight Sets the height of the media file popup
1568 * @property int $mediawidth Sets the width of the media file popup
1569 * @property int $mediaclose Toggle display of a media close button
1570 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1571 * @property int $width Width of slideshow
1572 * @property int $height Height of slideshow
1573 * @property string $bgcolor Background colour of slideshow
1574 * @property int $displayleft Display a left menu
1575 * @property int $displayleftif Sets the condition on which the left menu is displayed
1576 * @property int $progressbar Flag to toggle display of a lesson progress bar
1577 * @property int $available Timestamp of when this lesson becomes available
1578 * @property int $deadline Timestamp of when this lesson is no longer available
1579 * @property int $timemodified Timestamp when lesson was last modified
1580 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1581 *
1582 * These properties are calculated
1583 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1584 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1585 *
1586 * @copyright  2009 Sam Hemelryk
1587 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1588 */
1589class lesson extends lesson_base {
1590
1591    /**
1592     * The id of the first page (where prevpageid = 0) gets set and retrieved by
1593     * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1594     * @var int
1595     */
1596    protected $firstpageid = null;
1597    /**
1598     * The id of the last page (where nextpageid = 0) gets set and retrieved by
1599     * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1600     * @var int
1601     */
1602    protected $lastpageid = null;
1603    /**
1604     * An array used to cache the pages associated with this lesson after the first
1605     * time they have been loaded.
1606     * A note to developers: If you are going to be working with MORE than one or
1607     * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1608     * in order to save excess database queries.
1609     * @var array An array of lesson_page objects
1610     */
1611    protected $pages = array();
1612    /**
1613     * Flag that gets set to true once all of the pages associated with the lesson
1614     * have been loaded.
1615     * @var bool
1616     */
1617    protected $loadedallpages = false;
1618
1619    /**
1620     * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1621     * @see get_cm()
1622     * @var stdClass
1623     */
1624    protected $cm = null;
1625
1626    /**
1627     * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1628     * @see get_courserecord()
1629     * @var stdClass
1630     */
1631    protected $courserecord = null;
1632
1633    /**
1634     * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1635     * @see get_context()
1636     * @var stdClass
1637     */
1638    protected $context = null;
1639
1640    /**
1641     * Constructor method
1642     *
1643     * @param object $properties
1644     * @param stdClass $cm course module object
1645     * @param stdClass $course course object
1646     * @since Moodle 3.3
1647     */
1648    public function __construct($properties, $cm = null, $course = null) {
1649        parent::__construct($properties);
1650        $this->cm = $cm;
1651        $this->courserecord = $course;
1652    }
1653
1654    /**
1655     * Simply generates a lesson object given an array/object of properties
1656     * Overrides {@see lesson_base->create()}
1657     * @static
1658     * @param object|array $properties
1659     * @return lesson
1660     */
1661    public static function create($properties) {
1662        return new lesson($properties);
1663    }
1664
1665    /**
1666     * Generates a lesson object from the database given its id
1667     * @static
1668     * @param int $lessonid
1669     * @return lesson
1670     */
1671    public static function load($lessonid) {
1672        global $DB;
1673
1674        if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1675            print_error('invalidcoursemodule');
1676        }
1677        return new lesson($lesson);
1678    }
1679
1680    /**
1681     * Deletes this lesson from the database
1682     */
1683    public function delete() {
1684        global $CFG, $DB;
1685        require_once($CFG->libdir.'/gradelib.php');
1686        require_once($CFG->dirroot.'/calendar/lib.php');
1687
1688        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1689        $context = context_module::instance($cm->id);
1690
1691        $this->delete_all_overrides();
1692
1693        grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1694
1695        // We must delete the module record after we delete the grade item.
1696        $DB->delete_records("lesson", array("id"=>$this->properties->id));
1697        $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1698        $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1699        $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1700        $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1701        $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1702        $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1703        if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1704            $coursecontext = context_course::instance($cm->course);
1705            foreach($events as $event) {
1706                $event->context = $coursecontext;
1707                $event = calendar_event::load($event);
1708                $event->delete();
1709            }
1710        }
1711
1712        // Delete files associated with this module.
1713        $fs = get_file_storage();
1714        $fs->delete_area_files($context->id);
1715
1716        return true;
1717    }
1718
1719    /**
1720     * Deletes a lesson override from the database and clears any corresponding calendar events
1721     *
1722     * @param int $overrideid The id of the override being deleted
1723     * @return bool true on success
1724     */
1725    public function delete_override($overrideid) {
1726        global $CFG, $DB;
1727
1728        require_once($CFG->dirroot . '/calendar/lib.php');
1729
1730        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1731
1732        $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1733
1734        // Delete the events.
1735        $conds = array('modulename' => 'lesson',
1736                'instance' => $this->properties->id);
1737        if (isset($override->userid)) {
1738            $conds['userid'] = $override->userid;
1739        } else {
1740            $conds['groupid'] = $override->groupid;
1741        }
1742        $events = $DB->get_records('event', $conds);
1743        foreach ($events as $event) {
1744            $eventold = calendar_event::load($event);
1745            $eventold->delete();
1746        }
1747
1748        $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1749
1750        // Set the common parameters for one of the events we will be triggering.
1751        $params = array(
1752            'objectid' => $override->id,
1753            'context' => context_module::instance($cm->id),
1754            'other' => array(
1755                'lessonid' => $override->lessonid
1756            )
1757        );
1758        // Determine which override deleted event to fire.
1759        if (!empty($override->userid)) {
1760            $params['relateduserid'] = $override->userid;
1761            $event = \mod_lesson\event\user_override_deleted::create($params);
1762        } else {
1763            $params['other']['groupid'] = $override->groupid;
1764            $event = \mod_lesson\event\group_override_deleted::create($params);
1765        }
1766
1767        // Trigger the override deleted event.
1768        $event->add_record_snapshot('lesson_overrides', $override);
1769        $event->trigger();
1770
1771        return true;
1772    }
1773
1774    /**
1775     * Deletes all lesson overrides from the database and clears any corresponding calendar events
1776     */
1777    public function delete_all_overrides() {
1778        global $DB;
1779
1780        $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1781        foreach ($overrides as $override) {
1782            $this->delete_override($override->id);
1783        }
1784    }
1785
1786    /**
1787     * Checks user enrollment in the current course.
1788     *
1789     * @param int $userid
1790     * @return null|stdClass user record
1791     */
1792    public function is_participant($userid) {
1793        return is_enrolled($this->get_context(), $userid, 'mod/lesson:view', $this->show_only_active_users());
1794    }
1795
1796    /**
1797     * Check is only active users in course should be shown.
1798     *
1799     * @return bool true if only active users should be shown.
1800     */
1801    public function show_only_active_users() {
1802        return !has_capability('moodle/course:viewsuspendedusers', $this->get_context());
1803    }
1804
1805    /**
1806     * Updates the lesson properties with override information for a user.
1807     *
1808     * Algorithm:  For each lesson setting, if there is a matching user-specific override,
1809     *   then use that otherwise, if there are group-specific overrides, return the most
1810     *   lenient combination of them.  If neither applies, leave the quiz setting unchanged.
1811     *
1812     *   Special case: if there is more than one password that applies to the user, then
1813     *   lesson->extrapasswords will contain an array of strings giving the remaining
1814     *   passwords.
1815     *
1816     * @param int $userid The userid.
1817     */
1818    public function update_effective_access($userid) {
1819        global $DB;
1820
1821        // Check for user override.
1822        $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1823
1824        if (!$override) {
1825            $override = new stdClass();
1826            $override->available = null;
1827            $override->deadline = null;
1828            $override->timelimit = null;
1829            $override->review = null;
1830            $override->maxattempts = null;
1831            $override->retake = null;
1832            $override->password = null;
1833        }
1834
1835        // Check for group overrides.
1836        $groupings = groups_get_user_groups($this->properties->course, $userid);
1837
1838        if (!empty($groupings[0])) {
1839            // Select all overrides that apply to the User's groups.
1840            list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1841            $sql = "SELECT * FROM {lesson_overrides}
1842                    WHERE groupid $extra AND lessonid = ?";
1843            $params[] = $this->properties->id;
1844            $records = $DB->get_records_sql($sql, $params);
1845
1846            // Combine the overrides.
1847            $availables = array();
1848            $deadlines = array();
1849            $timelimits = array();
1850            $reviews = array();
1851            $attempts = array();
1852            $retakes = array();
1853            $passwords = array();
1854
1855            foreach ($records as $gpoverride) {
1856                if (isset($gpoverride->available)) {
1857                    $availables[] = $gpoverride->available;
1858                }
1859                if (isset($gpoverride->deadline)) {
1860                    $deadlines[] = $gpoverride->deadline;
1861                }
1862                if (isset($gpoverride->timelimit)) {
1863                    $timelimits[] = $gpoverride->timelimit;
1864                }
1865                if (isset($gpoverride->review)) {
1866                    $reviews[] = $gpoverride->review;
1867                }
1868                if (isset($gpoverride->maxattempts)) {
1869                    $attempts[] = $gpoverride->maxattempts;
1870                }
1871                if (isset($gpoverride->retake)) {
1872                    $retakes[] = $gpoverride->retake;
1873                }
1874                if (isset($gpoverride->password)) {
1875                    $passwords[] = $gpoverride->password;
1876                }
1877            }
1878            // If there is a user override for a setting, ignore the group override.
1879            if (is_null($override->available) && count($availables)) {
1880                $override->available = min($availables);
1881            }
1882            if (is_null($override->deadline) && count($deadlines)) {
1883                if (in_array(0, $deadlines)) {
1884                    $override->deadline = 0;
1885                } else {
1886                    $override->deadline = max($deadlines);
1887                }
1888            }
1889            if (is_null($override->timelimit) && count($timelimits)) {
1890                if (in_array(0, $timelimits)) {
1891                    $override->timelimit = 0;
1892                } else {
1893                    $override->timelimit = max($timelimits);
1894                }
1895            }
1896            if (is_null($override->review) && count($reviews)) {
1897                $override->review = max($reviews);
1898            }
1899            if (is_null($override->maxattempts) && count($attempts)) {
1900                $override->maxattempts = max($attempts);
1901            }
1902            if (is_null($override->retake) && count($retakes)) {
1903                $override->retake = max($retakes);
1904            }
1905            if (is_null($override->password) && count($passwords)) {
1906                $override->password = array_shift($passwords);
1907                if (count($passwords)) {
1908                    $override->extrapasswords = $passwords;
1909                }
1910            }
1911
1912        }
1913
1914        // Merge with lesson defaults.
1915        $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1916        foreach ($keys as $key) {
1917            if (isset($override->{$key})) {
1918                $this->properties->{$key} = $override->{$key};
1919            }
1920        }
1921
1922        // Special handling of lesson usepassword and password.
1923        if (isset($override->password)) {
1924            if ($override->password == '') {
1925                $this->properties->usepassword = 0;
1926            } else {
1927                $this->properties->usepassword = 1;
1928                $this->properties->password = $override->password;
1929                if (isset($override->extrapasswords)) {
1930                    $this->properties->extrapasswords = $override->extrapasswords;
1931                }
1932            }
1933        }
1934    }
1935
1936    /**
1937     * Fetches messages from the session that may have been set in previous page
1938     * actions.
1939     *
1940     * <code>
1941     * // Do not call this method directly instead use
1942     * $lesson->messages;
1943     * </code>
1944     *
1945     * @return array
1946     */
1947    protected function get_messages() {
1948        global $SESSION;
1949
1950        $messages = array();
1951        if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1952            $messages = $SESSION->lesson_messages[$this->properties->id];
1953            unset($SESSION->lesson_messages[$this->properties->id]);
1954        }
1955
1956        return $messages;
1957    }
1958
1959    /**
1960     * Get all of the attempts for the current user.
1961     *
1962     * @param int $retries
1963     * @param bool $correct Optional: only fetch correct attempts
1964     * @param int $pageid Optional: only fetch attempts at the given page
1965     * @param int $userid Optional: defaults to the current user if not set
1966     * @return array|false
1967     */
1968    public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1969        global $USER, $DB;
1970        $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1971        if ($correct) {
1972            $params['correct'] = 1;
1973        }
1974        if ($pageid !== null) {
1975            $params['pageid'] = $pageid;
1976        }
1977        if ($userid === null) {
1978            $params['userid'] = $USER->id;
1979        }
1980        return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1981    }
1982
1983
1984    /**
1985     * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1986     *
1987     * @param  int $lessonattempt the lesson attempt number (also known as retries)
1988     * @param  int $userid        the user id to retrieve the data from
1989     * @param  string $sort          an order to sort the results in (a valid SQL ORDER BY parameter)
1990     * @param  string $fields        a comma separated list of fields to return
1991     * @return array of pages
1992     * @since  Moodle 3.3
1993     */
1994    public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1995        global $USER, $DB;
1996
1997        if ($userid === null) {
1998            $userid = $USER->id;
1999        }
2000        $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
2001        return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
2002    }
2003
2004    /**
2005     * Returns the first page for the lesson or false if there isn't one.
2006     *
2007     * This method should be called via the magic method __get();
2008     * <code>
2009     * $firstpage = $lesson->firstpage;
2010     * </code>
2011     *
2012     * @return lesson_page|bool Returns the lesson_page specialised object or false
2013     */
2014    protected function get_firstpage() {
2015        $pages = $this->load_all_pages();
2016        if (count($pages) > 0) {
2017            foreach ($pages as $page) {
2018                if ((int)$page->prevpageid === 0) {
2019                    return $page;
2020                }
2021            }
2022        }
2023        return false;
2024    }
2025
2026    /**
2027     * Returns the last page for the lesson or false if there isn't one.
2028     *
2029     * This method should be called via the magic method __get();
2030     * <code>
2031     * $lastpage = $lesson->lastpage;
2032     * </code>
2033     *
2034     * @return lesson_page|bool Returns the lesson_page specialised object or false
2035     */
2036    protected function get_lastpage() {
2037        $pages = $this->load_all_pages();
2038        if (count($pages) > 0) {
2039            foreach ($pages as $page) {
2040                if ((int)$page->nextpageid === 0) {
2041                    return $page;
2042                }
2043            }
2044        }
2045        return false;
2046    }
2047
2048    /**
2049     * Returns the id of the first page of this lesson. (prevpageid = 0)
2050     * @return int
2051     */
2052    protected function get_firstpageid() {
2053        global $DB;
2054        if ($this->firstpageid == null) {
2055            if (!$this->loadedallpages) {
2056                $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
2057                if (!$firstpageid) {
2058                    print_error('cannotfindfirstpage', 'lesson');
2059                }
2060                $this->firstpageid = $firstpageid;
2061            } else {
2062                $firstpage = $this->get_firstpage();
2063                $this->firstpageid = $firstpage->id;
2064            }
2065        }
2066        return $this->firstpageid;
2067    }
2068
2069    /**
2070     * Returns the id of the last page of this lesson. (nextpageid = 0)
2071     * @return int
2072     */
2073    public function get_lastpageid() {
2074        global $DB;
2075        if ($this->lastpageid == null) {
2076            if (!$this->loadedallpages) {
2077                $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
2078                if (!$lastpageid) {
2079                    print_error('cannotfindlastpage', 'lesson');
2080                }
2081                $this->lastpageid = $lastpageid;
2082            } else {
2083                $lastpageid = $this->get_lastpage();
2084                $this->lastpageid = $lastpageid->id;
2085            }
2086        }
2087
2088        return $this->lastpageid;
2089    }
2090
2091     /**
2092     * Gets the next page id to display after the one that is provided.
2093     * @param int $nextpageid
2094     * @return bool
2095     */
2096    public function get_next_page($nextpageid) {
2097        global $USER, $DB;
2098        $allpages = $this->load_all_pages();
2099        if ($this->properties->nextpagedefault) {
2100            // in Flash Card mode...first get number of retakes
2101            $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2102            shuffle($allpages);
2103            $found = false;
2104            if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
2105                foreach ($allpages as $nextpage) {
2106                    if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
2107                        $found = true;
2108                        break;
2109                    }
2110                }
2111            } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
2112                foreach ($allpages as $nextpage) {
2113                    if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
2114                        $found = true;
2115                        break;
2116                    }
2117                }
2118            }
2119            if ($found) {
2120                if ($this->properties->maxpages) {
2121                    // check number of pages viewed (in the lesson)
2122                    if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
2123                        return LESSON_EOL;
2124                    }
2125                }
2126                return $nextpage->id;
2127            }
2128        }
2129        // In a normal lesson mode
2130        foreach ($allpages as $nextpage) {
2131            if ((int)$nextpage->id === (int)$nextpageid) {
2132                return $nextpage->id;
2133            }
2134        }
2135        return LESSON_EOL;
2136    }
2137
2138    /**
2139     * Sets a message against the session for this lesson that will displayed next
2140     * time the lesson processes messages
2141     *
2142     * @param string $message
2143     * @param string $class
2144     * @param string $align
2145     * @return bool
2146     */
2147    public function add_message($message, $class="notifyproblem", $align='center') {
2148        global $SESSION;
2149
2150        if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
2151            $SESSION->lesson_messages = array();
2152            $SESSION->lesson_messages[$this->properties->id] = array();
2153        } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
2154            $SESSION->lesson_messages[$this->properties->id] = array();
2155        }
2156
2157        $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
2158
2159        return true;
2160    }
2161
2162    /**
2163     * Check if the lesson is accessible at the present time
2164     * @return bool True if the lesson is accessible, false otherwise
2165     */
2166    public function is_accessible() {
2167        $available = $this->properties->available;
2168        $deadline = $this->properties->deadline;
2169        return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
2170    }
2171
2172    /**
2173     * Starts the lesson time for the current user
2174     * @return bool Returns true
2175     */
2176    public function start_timer() {
2177        global $USER, $DB;
2178
2179        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2180            false, MUST_EXIST);
2181
2182        // Trigger lesson started event.
2183        $event = \mod_lesson\event\lesson_started::create(array(
2184            'objectid' => $this->properties()->id,
2185            'context' => context_module::instance($cm->id),
2186            'courseid' => $this->properties()->course
2187        ));
2188        $event->trigger();
2189
2190        $USER->startlesson[$this->properties->id] = true;
2191
2192        $timenow = time();
2193        $startlesson = new stdClass;
2194        $startlesson->lessonid = $this->properties->id;
2195        $startlesson->userid = $USER->id;
2196        $startlesson->starttime = $timenow;
2197        $startlesson->lessontime = $timenow;
2198        if (WS_SERVER) {
2199            $startlesson->timemodifiedoffline = $timenow;
2200        }
2201        $DB->insert_record('lesson_timer', $startlesson);
2202        if ($this->properties->timelimit) {
2203            $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
2204        }
2205        return true;
2206    }
2207
2208    /**
2209     * Updates the timer to the current time and returns the new timer object
2210     * @param bool $restart If set to true the timer is restarted
2211     * @param bool $continue If set to true AND $restart=true then the timer
2212     *                        will continue from a previous attempt
2213     * @return stdClass The new timer
2214     */
2215    public function update_timer($restart=false, $continue=false, $endreached =false) {
2216        global $USER, $DB;
2217
2218        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2219
2220        // clock code
2221        // get time information for this user
2222        if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
2223            $this->start_timer();
2224            $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
2225        }
2226        $timer = current($timer); // This will get the latest start time record.
2227
2228        if ($restart) {
2229            if ($continue) {
2230                // continue a previous test, need to update the clock  (think this option is disabled atm)
2231                $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
2232
2233                // Trigger lesson resumed event.
2234                $event = \mod_lesson\event\lesson_resumed::create(array(
2235                    'objectid' => $this->properties->id,
2236                    'context' => context_module::instance($cm->id),
2237                    'courseid' => $this->properties->course
2238                ));
2239                $event->trigger();
2240
2241            } else {
2242                // starting over, so reset the clock
2243                $timer->starttime = time();
2244
2245                // Trigger lesson restarted event.
2246                $event = \mod_lesson\event\lesson_restarted::create(array(
2247                    'objectid' => $this->properties->id,
2248                    'context' => context_module::instance($cm->id),
2249                    'courseid' => $this->properties->course
2250                ));
2251                $event->trigger();
2252
2253            }
2254        }
2255
2256        $timenow = time();
2257        $timer->lessontime = $timenow;
2258        if (WS_SERVER) {
2259            $timer->timemodifiedoffline = $timenow;
2260        }
2261        $timer->completed = $endreached;
2262        $DB->update_record('lesson_timer', $timer);
2263
2264        // Update completion state.
2265        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2266            false, MUST_EXIST);
2267        $course = get_course($cm->course);
2268        $completion = new completion_info($course);
2269        if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
2270            $completion->update_state($cm, COMPLETION_COMPLETE);
2271        }
2272        return $timer;
2273    }
2274
2275    /**
2276     * Updates the timer to the current time then stops it by unsetting the user var
2277     * @return bool Returns true
2278     */
2279    public function stop_timer() {
2280        global $USER, $DB;
2281        unset($USER->startlesson[$this->properties->id]);
2282
2283        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2284            false, MUST_EXIST);
2285
2286        // Trigger lesson ended event.
2287        $event = \mod_lesson\event\lesson_ended::create(array(
2288            'objectid' => $this->properties()->id,
2289            'context' => context_module::instance($cm->id),
2290            'courseid' => $this->properties()->course
2291        ));
2292        $event->trigger();
2293
2294        return $this->update_timer(false, false, true);
2295    }
2296
2297    /**
2298     * Checks to see if the lesson has pages
2299     */
2300    public function has_pages() {
2301        global $DB;
2302        $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
2303        return ($pagecount>0);
2304    }
2305
2306    /**
2307     * Returns the link for the related activity
2308     * @return string
2309     */
2310    public function link_for_activitylink() {
2311        global $DB;
2312        $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
2313        if ($module) {
2314            $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
2315            if ($modname) {
2316                $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
2317                if ($instancename) {
2318                    return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php',
2319                        array('id' => $this->properties->activitylink)), get_string('activitylinkname',
2320                        'lesson', $instancename), array('class' => 'centerpadded lessonbutton standardbutton p-r-1'));
2321                }
2322            }
2323        }
2324        return '';
2325    }
2326
2327    /**
2328     * Loads the requested page.
2329     *
2330     * This function will return the requested page id as either a specialised
2331     * lesson_page object OR as a generic lesson_page.
2332     * If the page has been loaded previously it will be returned from the pages
2333     * array, otherwise it will be loaded from the database first
2334     *
2335     * @param int $pageid
2336     * @return lesson_page A lesson_page object or an object that extends it
2337     */
2338    public function load_page($pageid) {
2339        if (!array_key_exists($pageid, $this->pages)) {
2340            $manager = lesson_page_type_manager::get($this);
2341            $this->pages[$pageid] = $manager->load_page($pageid, $this);
2342        }
2343        return $this->pages[$pageid];
2344    }
2345
2346    /**
2347     * Loads ALL of the pages for this lesson
2348     *
2349     * @return array An array containing all pages from this lesson
2350     */
2351    public function load_all_pages() {
2352        if (!$this->loadedallpages) {
2353            $manager = lesson_page_type_manager::get($this);
2354            $this->pages = $manager->load_all_pages($this);
2355            $this->loadedallpages = true;
2356        }
2357        return $this->pages;
2358    }
2359
2360    /**
2361     * Duplicate the lesson page.
2362     *
2363     * @param  int $pageid Page ID of the page to duplicate.
2364     * @return void.
2365     */
2366    public function duplicate_page($pageid) {
2367        global $PAGE;
2368        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2369        $context = context_module::instance($cm->id);
2370        // Load the page.
2371        $page = $this->load_page($pageid);
2372        $properties = $page->properties();
2373        // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2374        if (!$properties->qoption) {
2375            unset($properties->qoption);
2376        }
2377        if (!$properties->layout) {
2378            unset($properties->layout);
2379        }
2380        if (!$properties->display) {
2381            unset($properties->display);
2382        }
2383
2384        $properties->pageid = $pageid;
2385        // Add text and format into the format required to create a new page.
2386        $properties->contents_editor = array(
2387            'text' => $properties->contents,
2388            'format' => $properties->contentsformat
2389        );
2390        $answers = $page->get_answers();
2391        // Answers need to be added to $properties.
2392        $i = 0;
2393        $answerids = array();
2394        foreach ($answers as $answer) {
2395            // Needs to be rearranged to work with the create function.
2396            $properties->answer_editor[$i] = array(
2397                'text' => $answer->answer,
2398                'format' => $answer->answerformat
2399            );
2400
2401            $properties->response_editor[$i] = array(
2402              'text' => $answer->response,
2403              'format' => $answer->responseformat
2404            );
2405            $answerids[] = $answer->id;
2406
2407            $properties->jumpto[$i] = $answer->jumpto;
2408            $properties->score[$i] = $answer->score;
2409
2410            $i++;
2411        }
2412        // Create the duplicate page.
2413        $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
2414        $newanswers = $newlessonpage->get_answers();
2415        // Copy over the file areas as well.
2416        $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
2417        $j = 0;
2418        foreach ($newanswers as $answer) {
2419            if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
2420                $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
2421            }
2422            if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
2423                $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
2424            }
2425            $j++;
2426        }
2427    }
2428
2429    /**
2430     * Copy the files from one page to another.
2431     *
2432     * @param  string $filearea Area that the files are stored.
2433     * @param  int $itemid Item ID.
2434     * @param  int $newitemid The item ID for the new page.
2435     * @param  int $contextid Context ID for this page.
2436     * @return void.
2437     */
2438    protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2439        $fs = get_file_storage();
2440        $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2441        foreach ($files as $file) {
2442            $fieldupdates = array('itemid' => $newitemid);
2443            $fs->create_file_from_storedfile($fieldupdates, $file);
2444        }
2445    }
2446
2447    /**
2448     * Determines if a jumpto value is correct or not.
2449     *
2450     * returns true if jumpto page is (logically) after the pageid page or
2451     * if the jumpto value is a special value.  Returns false in all other cases.
2452     *
2453     * @param int $pageid Id of the page from which you are jumping from.
2454     * @param int $jumpto The jumpto number.
2455     * @return boolean True or false after a series of tests.
2456     **/
2457    public function jumpto_is_correct($pageid, $jumpto) {
2458        global $DB;
2459
2460        // first test the special values
2461        if (!$jumpto) {
2462            // same page
2463            return false;
2464        } elseif ($jumpto == LESSON_NEXTPAGE) {
2465            return true;
2466        } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2467            return true;
2468        } elseif ($jumpto == LESSON_RANDOMPAGE) {
2469            return true;
2470        } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2471            return true;
2472        } elseif ($jumpto == LESSON_EOL) {
2473            return true;
2474        }
2475
2476        $pages = $this->load_all_pages();
2477        $apageid = $pages[$pageid]->nextpageid;
2478        while ($apageid != 0) {
2479            if ($jumpto == $apageid) {
2480                return true;
2481            }
2482            $apageid = $pages[$apageid]->nextpageid;
2483        }
2484        return false;
2485    }
2486
2487    /**
2488     * Returns the time a user has remaining on this lesson
2489     * @param int $starttime Starttime timestamp
2490     * @return string
2491     */
2492    public function time_remaining($starttime) {
2493        $timeleft = $starttime + $this->properties->timelimit - time();
2494        $hours = floor($timeleft/3600);
2495        $timeleft = $timeleft - ($hours * 3600);
2496        $minutes = floor($timeleft/60);
2497        $secs = $timeleft - ($minutes * 60);
2498
2499        if ($minutes < 10) {
2500            $minutes = "0$minutes";
2501        }
2502        if ($secs < 10) {
2503            $secs = "0$secs";
2504        }
2505        $output   = array();
2506        $output[] = $hours;
2507        $output[] = $minutes;
2508        $output[] = $secs;
2509        $output = implode(':', $output);
2510        return $output;
2511    }
2512
2513    /**
2514     * Interprets LESSON_CLUSTERJUMP jumpto value.
2515     *
2516     * This will select a page randomly
2517     * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
2518     * and the page selected will be a page that has not been viewed already
2519     * and if any pages are within a branch table or end of branch then only 1 page within
2520     * the branch table or end of branch will be randomly selected (sub clustering).
2521     *
2522     * @param int $pageid Id of the current page from which we are jumping from.
2523     * @param int $userid Id of the user.
2524     * @return int The id of the next page.
2525     **/
2526    public function cluster_jump($pageid, $userid=null) {
2527        global $DB, $USER;
2528
2529        if ($userid===null) {
2530            $userid = $USER->id;
2531        }
2532        // get the number of retakes
2533        if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
2534            $retakes = 0;
2535        }
2536        // get all the lesson_attempts aka what the user has seen
2537        $seenpages = array();
2538        if ($attempts = $this->get_attempts($retakes)) {
2539            foreach ($attempts as $attempt) {
2540                $seenpages[$attempt->pageid] = $attempt->pageid;
2541            }
2542
2543        }
2544
2545        // get the lesson pages
2546        $lessonpages = $this->load_all_pages();
2547        // find the start of the cluster
2548        while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2549            if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
2550                break;
2551            }
2552            $pageid = $lessonpages[$pageid]->prevpageid;
2553        }
2554
2555        $clusterpages = array();
2556        $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
2557        $unseen = array();
2558        foreach ($clusterpages as $key=>$cluster) {
2559            // Remove the page if  it is in a branch table or is an endofbranch.
2560            if ($this->is_sub_page_of_type($cluster->id,
2561                    array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
2562                    || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
2563                unset($clusterpages[$key]);
2564            } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
2565                // If branchtable, check to see if any pages inside have been viewed.
2566                $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2567                $flag = true;
2568                foreach ($branchpages as $branchpage) {
2569                    if (array_key_exists($branchpage->id, $seenpages)) {  // Check if any of the pages have been viewed.
2570                        $flag = false;
2571                    }
2572                }
2573                if ($flag && count($branchpages) > 0) {
2574                    // Add branch table.
2575                    $unseen[] = $cluster;
2576                }
2577            } elseif ($cluster->is_unseen($seenpages)) {
2578                $unseen[] = $cluster;
2579            }
2580        }
2581
2582        if (count($unseen) > 0) {
2583            // it does not contain elements, then use exitjump, otherwise find out next page/branch
2584            $nextpage = $unseen[rand(0, count($unseen)-1)];
2585            if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
2586                // if branch table, then pick a random page inside of it
2587                $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2588                return $branchpages[rand(0, count($branchpages)-1)]->id;
2589            } else { // otherwise, return the page's id
2590                return $nextpage->id;
2591            }
2592        } else {
2593            // seen all there is to see, leave the cluster
2594            if (end($clusterpages)->nextpageid == 0) {
2595                return LESSON_EOL;
2596            } else {
2597                $clusterendid = $pageid;
2598                while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2599                    if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2600                        break;
2601                    }
2602                    $clusterendid = $lessonpages[$clusterendid]->nextpageid;
2603                }
2604                $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
2605                if ($exitjump == LESSON_NEXTPAGE) {
2606                    $exitjump = $lessonpages[$clusterendid]->nextpageid;
2607                }
2608                if ($exitjump == 0) {
2609                    return LESSON_EOL;
2610                } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
2611                    return $exitjump;
2612                } else {
2613                    if (!array_key_exists($exitjump, $lessonpages)) {
2614                        $found = false;
2615                        foreach ($lessonpages as $page) {
2616                            if ($page->id === $clusterendid) {
2617                                $found = true;
2618                            } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2619                                $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
2620                                if ($exitjump == LESSON_NEXTPAGE) {
2621                                    $exitjump = $lessonpages[$page->id]->nextpageid;
2622                                }
2623                                break;
2624                            }
2625                        }
2626                    }
2627                    if (!array_key_exists($exitjump, $lessonpages)) {
2628                        return LESSON_EOL;
2629                    }
2630                    // Check to see that the return type is not a cluster.
2631                    if ($lessonpages[$exitjump]->qtype == LESSON_PAGE_CLUSTER) {
2632                        // If the exitjump is a cluster then go through this function again and try to find an unseen question.
2633                        $exitjump = $this->cluster_jump($exitjump, $userid);
2634                    }
2635                    return $exitjump;
2636                }
2637            }
2638        }
2639    }
2640
2641    /**
2642     * Finds all pages that appear to be a subtype of the provided pageid until
2643     * an end point specified within $ends is encountered or no more pages exist
2644     *
2645     * @param int $pageid
2646     * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2647     *               the subtype
2648     * @return array An array of specialised lesson_page objects
2649     */
2650    public function get_sub_pages_of($pageid, array $ends) {
2651        $lessonpages = $this->load_all_pages();
2652        $pageid = $lessonpages[$pageid]->nextpageid;  // move to the first page after the branch table
2653        $pages = array();
2654
2655        while (true) {
2656            if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2657                break;
2658            }
2659            $pages[] = $lessonpages[$pageid];
2660            $pageid = $lessonpages[$pageid]->nextpageid;
2661        }
2662
2663        return $pages;
2664    }
2665
2666    /**
2667     * Checks to see if the specified page[id] is a subpage of a type specified in
2668     * the $types array, until either there are no more pages of we find a type
2669     * corresponding to that of a type specified in $ends
2670     *
2671     * @param int $pageid The id of the page to check
2672     * @param array $types An array of types that would signify this page was a subpage
2673     * @param array $ends An array of types that mean this is not a subpage
2674     * @return bool
2675     */
2676    public function is_sub_page_of_type($pageid, array $types, array $ends) {
2677        $pages = $this->load_all_pages();
2678        $pageid = $pages[$pageid]->prevpageid; // move up one
2679
2680        array_unshift($ends, 0);
2681        // go up the pages till branch table
2682        while (true) {
2683            if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2684                return false;
2685            } else if (in_array($pages[$pageid]->qtype, $types)) {
2686                return true;
2687            }
2688            $pageid = $pages[$pageid]->prevpageid;
2689        }
2690    }
2691
2692    /**
2693     * Move a page resorting all other pages.
2694     *
2695     * @param int $pageid
2696     * @param int $after
2697     * @return void
2698     */
2699    public function resort_pages($pageid, $after) {
2700        global $CFG;
2701
2702        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2703        $context = context_module::instance($cm->id);
2704
2705        $pages = $this->load_all_pages();
2706
2707        if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2708            print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2709        }
2710
2711        $pagetomove = clone($pages[$pageid]);
2712        unset($pages[$pageid]);
2713
2714        $pageids = array();
2715        if ($after === 0) {
2716            $pageids['p0'] = $pageid;
2717        }
2718        foreach ($pages as $page) {
2719            $pageids[] = $page->id;
2720            if ($page->id == $after) {
2721                $pageids[] = $pageid;
2722            }
2723        }
2724
2725        $pageidsref = $pageids;
2726        reset($pageidsref);
2727        $prev = 0;
2728        $next = next($pageidsref);
2729        foreach ($pageids as $pid) {
2730            if ($pid === $pageid) {
2731                $page = $pagetomove;
2732            } else {
2733                $page = $pages[$pid];
2734            }
2735            if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2736                $page->move($next, $prev);
2737
2738                if ($pid === $pageid) {
2739                    // We will trigger an event.
2740                    $pageupdated = array('next' => $next, 'prev' => $prev);
2741                }
2742            }
2743
2744            $prev = $page->id;
2745            $next = next($pageidsref);
2746            if (!$next) {
2747                $next = 0;
2748            }
2749        }
2750
2751        // Trigger an event: page moved.
2752        if (!empty($pageupdated)) {
2753            $eventparams = array(
2754                'context' => $context,
2755                'objectid' => $pageid,
2756                'other' => array(
2757                    'pagetype' => $page->get_typestring(),
2758                    'prevpageid' => $pageupdated['prev'],
2759                    'nextpageid' => $pageupdated['next']
2760                )
2761            );
2762            $event = \mod_lesson\event\page_moved::create($eventparams);
2763            $event->trigger();
2764        }
2765
2766    }
2767
2768    /**
2769     * Return the lesson context object.
2770     *
2771     * @return stdClass context
2772     * @since  Moodle 3.3
2773     */
2774    public function get_context() {
2775        if ($this->context == null) {
2776            $this->context = context_module::instance($this->get_cm()->id);
2777        }
2778        return $this->context;
2779    }
2780
2781    /**
2782     * Set the lesson course module object.
2783     *
2784     * @param stdClass $cm course module objct
2785     * @since  Moodle 3.3
2786     */
2787    private function set_cm($cm) {
2788        $this->cm = $cm;
2789    }
2790
2791    /**
2792     * Return the lesson course module object.
2793     *
2794     * @return stdClass course module
2795     * @since  Moodle 3.3
2796     */
2797    public function get_cm() {
2798        if ($this->cm == null) {
2799            $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2800        }
2801        return $this->cm;
2802    }
2803
2804    /**
2805     * Set the lesson course object.
2806     *
2807     * @param stdClass $course course objct
2808     * @since  Moodle 3.3
2809     */
2810    private function set_courserecord($course) {
2811        $this->courserecord = $course;
2812    }
2813
2814    /**
2815     * Return the lesson course object.
2816     *
2817     * @return stdClass course
2818     * @since  Moodle 3.3
2819     */
2820    public function get_courserecord() {
2821        global $DB;
2822
2823        if ($this->courserecord == null) {
2824            $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2825        }
2826        return $this->courserecord;
2827    }
2828
2829    /**
2830     * Check if the user can manage the lesson activity.
2831     *
2832     * @return bool true if the user can manage the lesson
2833     * @since  Moodle 3.3
2834     */
2835    public function can_manage() {
2836        return has_capability('mod/lesson:manage', $this->get_context());
2837    }
2838
2839    /**
2840     * Check if time restriction is applied.
2841     *
2842     * @return mixed false if  there aren't restrictions or an object with the restriction information
2843     * @since  Moodle 3.3
2844     */
2845    public function get_time_restriction_status() {
2846        if ($this->can_manage()) {
2847            return false;
2848        }
2849
2850        if (!$this->is_accessible()) {
2851            if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2852                $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2853            } else {
2854                $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2855            }
2856            return (object) $status;
2857        }
2858        return false;
2859    }
2860
2861    /**
2862     * Check if password restriction is applied.
2863     *
2864     * @param string $userpassword the user password to check (if the restriction is set)
2865     * @return mixed false if there aren't restrictions or an object with the restriction information
2866     * @since  Moodle 3.3
2867     */
2868    public function get_password_restriction_status($userpassword) {
2869        global $USER;
2870        if ($this->can_manage()) {
2871            return false;
2872        }
2873
2874        if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2875            $correctpass = false;
2876            if (!empty($userpassword) &&
2877                    (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2878                // With or without md5 for backward compatibility (MDL-11090).
2879                $correctpass = true;
2880                $USER->lessonloggedin[$this->id] = true;
2881            } else if (isset($this->properties->extrapasswords)) {
2882                // Group overrides may have additional passwords.
2883                foreach ($this->properties->extrapasswords as $password) {
2884                    if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2885                        $correctpass = true;
2886                        $USER->lessonloggedin[$this->id] = true;
2887                    }
2888                }
2889            }
2890            return !$correctpass;
2891        }
2892        return false;
2893    }
2894
2895    /**
2896     * Check if dependencies restrictions are applied.
2897     *
2898     * @return mixed false if there aren't restrictions or an object with the restriction information
2899     * @since  Moodle 3.3
2900     */
2901    public function get_dependencies_restriction_status() {
2902        global $DB, $USER;
2903        if ($this->can_manage()) {
2904            return false;
2905        }
2906
2907        if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2908            // Lesson exists, so we can proceed.
2909            $conditions = unserialize($this->properties->conditions);
2910            // Assume false for all.
2911            $errors = array();
2912            // Check for the timespent condition.
2913            if ($conditions->timespent) {
2914                $timespent = false;
2915                if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2916                    // Go through all the times and test to see if any of them satisfy the condition.
2917                    foreach ($attempttimes as $attempttime) {
2918                        $duration = $attempttime->lessontime - $attempttime->starttime;
2919                        if ($conditions->timespent < $duration / 60) {
2920                            $timespent = true;
2921                        }
2922                    }
2923                }
2924                if (!$timespent) {
2925                    $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2926                }
2927            }
2928            // Check for the gradebetterthan condition.
2929            if ($conditions->gradebetterthan) {
2930                $gradebetterthan = false;
2931                if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2932                    // Go through all the grades and test to see if any of them satisfy the condition.
2933                    foreach ($studentgrades as $studentgrade) {
2934                        if ($studentgrade->grade >= $conditions->gradebetterthan) {
2935                            $gradebetterthan = true;
2936                        }
2937                    }
2938                }
2939                if (!$gradebetterthan) {
2940                    $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2941                }
2942            }
2943            // Check for the completed condition.
2944            if ($conditions->completed) {
2945                if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2946                    $errors[] = get_string('completederror', 'lesson');
2947                }
2948            }
2949            if (!empty($errors)) {
2950                return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2951            }
2952        }
2953        return false;
2954    }
2955
2956    /**
2957     * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2958     *
2959     * @return bool true if is in review mode
2960     * @since  Moodle 3.3
2961     */
2962    public function is_in_review_mode() {
2963        global $DB, $USER;
2964
2965        $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2966        if ($userhasgrade && !$this->properties->retake) {
2967            return true;
2968        }
2969        return false;
2970    }
2971
2972    /**
2973     * Return the last page the current user saw.
2974     *
2975     * @param int $retriescount the number of retries for the lesson (the last retry number).
2976     * @return mixed false if the user didn't see the lesson or the last page id
2977     */
2978    public function get_last_page_seen($retriescount) {
2979        global $DB, $USER;
2980
2981        $lastpageseen = false;
2982        $allattempts = $this->get_attempts($retriescount);
2983        if (!empty($allattempts)) {
2984            $attempt = end($allattempts);
2985            $attemptpage = $this->load_page($attempt->pageid);
2986            $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2987            // Convert the jumpto to a proper page id.
2988            if ($jumpto == 0) {
2989                // Check if a question has been incorrectly answered AND no more attempts at it are left.
2990                $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2991                if (count($nattempts) >= $this->properties->maxattempts) {
2992                    $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2993                } else {
2994                    $lastpageseen = $attempt->pageid;
2995                }
2996            } else if ($jumpto == LESSON_NEXTPAGE) {
2997                $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2998            } else if ($jumpto == LESSON_CLUSTERJUMP) {
2999                $lastpageseen = $this->cluster_jump($attempt->pageid);
3000            } else {
3001                $lastpageseen = $jumpto;
3002            }
3003        }
3004
3005        if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
3006            // In here, user has viewed a branch table.
3007            $lastbranchtable = current($branchtables);
3008            if (count($allattempts) > 0) {
3009                if ($lastbranchtable->timeseen > $attempt->timeseen) {
3010                    // This branch table was viewed more recently than the question page.
3011                    if (!empty($lastbranchtable->nextpageid)) {
3012                        $lastpageseen = $lastbranchtable->nextpageid;
3013                    } else {
3014                        // Next page ID did not exist prior to MDL-34006.
3015                        $lastpageseen = $lastbranchtable->pageid;
3016                    }
3017                }
3018            } else {
3019                // Has not answered any questions but has viewed a branch table.
3020                if (!empty($lastbranchtable->nextpageid)) {
3021                    $lastpageseen = $lastbranchtable->nextpageid;
3022                } else {
3023                    // Next page ID did not exist prior to MDL-34006.
3024                    $lastpageseen = $lastbranchtable->pageid;
3025                }
3026            }
3027        }
3028        return $lastpageseen;
3029    }
3030
3031    /**
3032     * Return the number of retries in a lesson for a given user.
3033     *
3034     * @param  int $userid the user id
3035     * @return int the retries count
3036     * @since  Moodle 3.3
3037     */
3038    public function count_user_retries($userid) {
3039        global $DB;
3040
3041        return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
3042    }
3043
3044    /**
3045     * Check if a user left a timed session.
3046     *
3047     * @param int $retriescount the number of retries for the lesson (the last retry number).
3048     * @return true if the user left the timed session
3049     * @since  Moodle 3.3
3050     */
3051    public function left_during_timed_session($retriescount) {
3052        global $DB, $USER;
3053
3054        $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
3055        return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
3056    }
3057
3058    /**
3059     * Trigger module viewed event and set the module viewed for completion.
3060     *
3061     * @since  Moodle 3.3
3062     */
3063    public function set_module_viewed() {
3064        global $CFG;
3065        require_once($CFG->libdir . '/completionlib.php');
3066
3067        // Trigger module viewed event.
3068        $event = \mod_lesson\event\course_module_viewed::create(array(
3069            'objectid' => $this->properties->id,
3070            'context' => $this->get_context()
3071        ));
3072        $event->add_record_snapshot('course_modules', $this->get_cm());
3073        $event->add_record_snapshot('course', $this->get_courserecord());
3074        $event->trigger();
3075
3076        // Mark as viewed.
3077        $completion = new completion_info($this->get_courserecord());
3078        $completion->set_module_viewed($this->get_cm());
3079    }
3080
3081    /**
3082     * Return the timers in the current lesson for the given user.
3083     *
3084     * @param  int      $userid    the user id
3085     * @param  string   $sort      an order to sort the results in (optional, a valid SQL ORDER BY parameter).
3086     * @param  string   $fields    a comma separated list of fields to return
3087     * @param  int      $limitfrom return a subset of records, starting at this point (optional).
3088     * @param  int      $limitnum  return a subset comprising this many records in total (optional, required if $limitfrom is set).
3089     * @return array    list of timers for the given user in the lesson
3090     * @since  Moodle 3.3
3091     */
3092    public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
3093        global $DB, $USER;
3094
3095        if ($userid === null) {
3096            $userid = $USER->id;
3097        }
3098
3099        $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
3100        return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
3101    }
3102
3103    /**
3104     * Check if the user is out of time in a timed lesson.
3105     *
3106     * @param  stdClass $timer timer object
3107     * @return bool True if the user is on time, false is the user ran out of time
3108     * @since  Moodle 3.3
3109     */
3110    public function check_time($timer) {
3111        if ($this->properties->timelimit) {
3112            $timeleft = $timer->starttime + $this->properties->timelimit - time();
3113            if ($timeleft <= 0) {
3114                // Out of time.
3115                $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
3116                return false;
3117            } else if ($timeleft < 60) {
3118                // One minute warning.
3119                $this->add_message(get_string('studentoneminwarning', 'lesson'));
3120            }
3121        }
3122        return true;
3123    }
3124
3125    /**
3126     * Add different informative messages to the given page.
3127     *
3128     * @param lesson_page $page page object
3129     * @param reviewmode $bool whether we are in review mode or not
3130     * @since  Moodle 3.3
3131     */
3132    public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
3133        global $DB, $USER;
3134
3135        if (!$this->can_manage()) {
3136            if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
3137                // Tell student how many questions they have seen, how many are required and their grade.
3138                $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3139                $gradeinfo = lesson_grade($this, $ntries);
3140                if ($gradeinfo->attempts) {
3141                    if ($gradeinfo->nquestions < $this->properties->minquestions) {
3142                        $a = new stdClass;
3143                        $a->nquestions   = $gradeinfo->nquestions;
3144                        $a->minquestions = $this->properties->minquestions;
3145                        $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3146                    }
3147
3148                    if (!$reviewmode && $this->properties->ongoing) {
3149                        $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
3150                        if ($this->properties->grade != GRADE_TYPE_NONE) {
3151                            $a = new stdClass;
3152                            $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3153                            $a->total = $this->properties->grade;
3154                            $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3155                        }
3156                    }
3157                }
3158            }
3159        } else {
3160            if ($this->properties->timelimit) {
3161                $this->add_message(get_string('teachertimerwarning', 'lesson'));
3162            }
3163            if (lesson_display_teacher_warning($this)) {
3164                // This is the warning msg for teachers to inform them that cluster
3165                // and unseen does not work while logged in as a teacher.
3166                $warningvars = new stdClass();
3167                $warningvars->cluster = get_string('clusterjump', 'lesson');
3168                $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
3169                $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3170            }
3171        }
3172    }
3173
3174    /**
3175     * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3176     *
3177     * @return str the ongoing score message
3178     * @since  Moodle 3.3
3179     */
3180    public function get_ongoing_score_message() {
3181        global $USER, $DB;
3182
3183        $context = $this->get_context();
3184
3185        if (has_capability('mod/lesson:manage', $context)) {
3186            return get_string('teacherongoingwarning', 'lesson');
3187        } else {
3188            $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3189            if (isset($USER->modattempts[$this->properties->id])) {
3190                $ntries--;
3191            }
3192            $gradeinfo = lesson_grade($this, $ntries);
3193            $a = new stdClass;
3194            if ($this->properties->custom) {
3195                $a->score = $gradeinfo->earned;
3196                $a->currenthigh = $gradeinfo->total;
3197                return get_string("ongoingcustom", "lesson", $a);
3198            } else {
3199                $a->correct = $gradeinfo->earned;
3200                $a->viewed = $gradeinfo->attempts;
3201                return get_string("ongoingnormal", "lesson", $a);
3202            }
3203        }
3204    }
3205
3206    /**
3207     * Calculate the progress of the current user in the lesson.
3208     *
3209     * @return int the progress (scale 0-100)
3210     * @since  Moodle 3.3
3211     */
3212    public function calculate_progress() {
3213        global $USER, $DB;
3214
3215        // Check if the user is reviewing the attempt.
3216        if (isset($USER->modattempts[$this->properties->id])) {
3217            return 100;
3218        }
3219
3220        // All of the lesson pages.
3221        $pages = $this->load_all_pages();
3222        foreach ($pages as $page) {
3223            if ($page->prevpageid == 0) {
3224                $pageid = $page->id;  // Find the first page id.
3225                break;
3226            }
3227        }
3228
3229        // Current attempt number.
3230        if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
3231            $ntries = 0;  // May not be necessary.
3232        }
3233
3234        $viewedpageids = array();
3235        if ($attempts = $this->get_attempts($ntries, false)) {
3236            foreach ($attempts as $attempt) {
3237                $viewedpageids[$attempt->pageid] = $attempt;
3238            }
3239        }
3240
3241        $viewedbranches = array();
3242        // Collect all of the branch tables viewed.
3243        if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
3244            foreach ($branches as $branch) {
3245                $viewedbranches[$branch->pageid] = $branch;
3246            }
3247            $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3248        }
3249
3250        // Filter out the following pages:
3251        // - End of Cluster
3252        // - End of Branch
3253        // - Pages found inside of Clusters
3254        // Do not filter out Cluster Page(s) because we count a cluster as one.
3255        // By keeping the cluster page, we get our 1.
3256        $validpages = array();
3257        while ($pageid != 0) {
3258            $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3259        }
3260
3261        // Progress calculation as a percent.
3262        $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3263        return (int) $progress;
3264    }
3265
3266    /**
3267     * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3268     *
3269     * @param  int $pageid the given page id
3270     * @param  mod_lesson_renderer $lessonoutput the lesson output rendered
3271     * @param  bool $reviewmode whether we are in review mode or not
3272     * @param  bool $redirect  Optional, default to true. Set to false to avoid redirection and return the page to redirect.
3273     * @return array the page object and contents
3274     * @throws moodle_exception
3275     * @since  Moodle 3.3
3276     */
3277    public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
3278        global $USER, $CFG;
3279
3280        $page = $this->load_page($pageid);
3281        // Check if the page is of a special type and if so take any nessecary action.
3282        $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3283
3284        // Avoid redirections returning the jump to special page id.
3285        if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3286            return array($newpageid, null, null);
3287        }
3288
3289        if (is_numeric($newpageid)) {
3290            $page = $this->load_page($newpageid);
3291        }
3292
3293        // Add different informative messages to the given page.
3294        $this->add_messages_on_page_view($page, $reviewmode);
3295
3296        if (is_array($page->answers) && count($page->answers) > 0) {
3297            // This is for modattempts option.  Find the users previous answer to this page,
3298            // and then display it below in answer processing.
3299            if (isset($USER->modattempts[$this->properties->id])) {
3300                $retries = $this->count_user_retries($USER->id);
3301                if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
3302                    throw new moodle_exception('cannotfindpreattempt', 'lesson');
3303                }
3304                $attempt = end($attempts);
3305                $USER->modattempts[$this->properties->id] = $attempt;
3306            } else {
3307                $attempt = false;
3308            }
3309            $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3310        } else {
3311            require_once($CFG->dirroot . '/mod/lesson/view_form.php');
3312            $data = new stdClass;
3313            $data->id = $this->get_cm()->id;
3314            $data->pageid = $page->id;
3315            $data->newpageid = $this->get_next_page($page->nextpageid);
3316
3317            $customdata = array(
3318                'title'     => $page->title,
3319                'contents'  => $page->get_contents()
3320            );
3321            $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
3322            $mform->set_data($data);
3323            ob_start();
3324            $mform->display();
3325            $lessoncontent = ob_get_contents();
3326            ob_end_clean();
3327        }
3328
3329        return array($page->id, $page, $lessoncontent);
3330    }
3331
3332    /**
3333     * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
3334     *
3335     * @param  lesson_page $page      lesson page
3336     * @param  int         $newpageid the new page id
3337     * @return int the real page to jump to (or end of lesson)
3338     * @since  Moodle 3.3
3339     */
3340    public function calculate_new_page_on_jump(lesson_page $page, $newpageid) {
3341        global $USER, $DB;
3342
3343        $canmanage = $this->can_manage();
3344
3345        if (isset($USER->modattempts[$this->properties->id])) {
3346            // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
3347            if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) {
3348                // Remember, this session variable holds the pageid of the last page that the user saw.
3349                $newpageid = LESSON_EOL;
3350            } else {
3351                $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3352                $nretakes--; // Make sure we are looking at the right try.
3353                $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
3354                $found = false;
3355                $temppageid = 0;
3356                // Make sure that the newpageid always defaults to something valid.
3357                $newpageid = LESSON_EOL;
3358                foreach ($attempts as $attempt) {
3359                    if ($found && $temppageid != $attempt->pageid) {
3360                        // Now try to find the next page, make sure next few attempts do no belong to current page.
3361                        $newpageid = $attempt->pageid;
3362                        break;
3363                    }
3364                    if ($attempt->pageid == $page->id) {
3365                        $found = true; // If found current page.
3366                        $temppageid = $attempt->pageid;
3367                    }
3368                }
3369            }
3370        } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) {
3371            // Going to check to see if the page that the user is going to view next, is a cluster page.
3372            // If so, dont display, go into the cluster.
3373            // The $newpageid > 0 is used to filter out all of the negative code jumps.
3374            $newpage = $this->load_page($newpageid);
3375            if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3376                $newpageid = $overridenewpageid;
3377            }
3378        } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) {
3379            if ($canmanage) {
3380                if ($page->nextpageid == 0) {
3381                    $newpageid = LESSON_EOL;
3382                } else {
3383                    $newpageid = $page->nextpageid;
3384                }
3385            } else {
3386                $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id);
3387            }
3388        } else if ($newpageid == LESSON_PREVIOUSPAGE) {
3389            $newpageid = $page->prevpageid;
3390        } else if ($newpageid == LESSON_RANDOMPAGE) {
3391            $newpageid = lesson_random_question_jump($this, $page->id);
3392        } else if ($newpageid == LESSON_CLUSTERJUMP) {
3393            if ($canmanage) {
3394                if ($page->nextpageid == 0) {  // If teacher, go to next page.
3395                    $newpageid = LESSON_EOL;
3396                } else {
3397                    $newpageid = $page->nextpageid;
3398                }
3399            } else {
3400                $newpageid = $this->cluster_jump($page->id);
3401            }
3402        } else if ($newpageid == 0) {
3403            $newpageid = $page->id;
3404        } else if ($newpageid == LESSON_NEXTPAGE) {
3405            $newpageid = $this->get_next_page($page->nextpageid);
3406        }
3407
3408        return $newpageid;
3409    }
3410
3411    /**
3412     * Process page responses.
3413     *
3414     * @param lesson_page $page page object
3415     * @since  Moodle 3.3
3416     */
3417    public function process_page_responses(lesson_page $page) {
3418        $context = $this->get_context();
3419
3420        // Check the page has answers [MDL-25632].
3421        if (count($page->answers) > 0) {
3422            $result = $page->record_attempt($context);
3423        } else {
3424            // The page has no answers so we will just progress to the next page in the
3425            // sequence (as set by newpageid).
3426            $result = new stdClass;
3427            $result->newpageid       = optional_param('newpageid', $page->nextpageid, PARAM_INT);
3428            $result->nodefaultresponse  = true;
3429            $result->inmediatejump = false;
3430        }
3431
3432        if ($result->inmediatejump) {
3433            return $result;
3434        }
3435
3436        $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);
3437
3438        return $result;
3439    }
3440
3441    /**
3442     * Add different informative messages to the given page.
3443     *
3444     * @param lesson_page $page page object
3445     * @param stdClass $result the page processing result object
3446     * @param bool $reviewmode whether we are in review mode or not
3447     * @since  Moodle 3.3
3448     */
3449    public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
3450
3451        if ($this->can_manage()) {
3452            // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3453            if (lesson_display_teacher_warning($this)) {
3454                $warningvars = new stdClass();
3455                $warningvars->cluster = get_string("clusterjump", "lesson");
3456                $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
3457                $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3458            }
3459            // Inform teacher that s/he will not see the timer.
3460            if ($this->properties->timelimit) {
3461                $this->add_message(get_string("teachertimerwarning", "lesson"));
3462            }
3463        }
3464        // Report attempts remaining.
3465        if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
3466            $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
3467        }
3468    }
3469
3470    /**
3471     * Process and return all the information for the end of lesson page.
3472     *
3473     * @param string $outoftime used to check to see if the student ran out of time
3474     * @return stdclass an object with all the page data ready for rendering
3475     * @since  Moodle 3.3
3476     */
3477    public function process_eol_page($outoftime) {
3478        global $DB, $USER;
3479
3480        $course = $this->get_courserecord();
3481        $cm = $this->get_cm();
3482        $canmanage = $this->can_manage();
3483
3484        // Init all the possible fields and values.
3485        $data = (object) array(
3486            'gradelesson' => true,
3487            'notenoughtimespent' => false,
3488            'numberofpagesviewed' => false,
3489            'youshouldview' => false,
3490            'numberofcorrectanswers' => false,
3491            'displayscorewithessays' => false,
3492            'displayscorewithoutessays' => false,
3493            'yourcurrentgradeisoutof' => false,
3494            'eolstudentoutoftimenoanswers' => false,
3495            'welldone' => false,
3496            'progressbar' => false,
3497            'displayofgrade' => false,
3498            'reviewlesson' => false,
3499            'modattemptsnoteacher' => false,
3500            'activitylink' => false,
3501            'progresscompleted' => false,
3502        );
3503
3504        $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3505        if (isset($USER->modattempts[$this->properties->id])) {
3506            $ntries--;  // Need to look at the old attempts :).
3507        }
3508
3509        $gradeinfo = lesson_grade($this, $ntries);
3510        $data->gradeinfo = $gradeinfo;
3511        if ($this->properties->custom && !$canmanage) {
3512            // Before we calculate the custom score make sure they answered the minimum
3513            // number of questions. We only need to do this for custom scoring as we can
3514            // not get the miniumum score the user should achieve. If we are not using
3515            // custom scoring (so all questions are valued as 1) then we simply check if
3516            // they answered more than the minimum questions, if not, we mark it out of the
3517            // number specified in the minimum questions setting - which is done in lesson_grade().
3518            // Get the number of answers given.
3519            if ($gradeinfo->nquestions < $this->properties->minquestions) {
3520                $data->gradelesson = false;
3521                $a = new stdClass;
3522                $a->nquestions = $gradeinfo->nquestions;
3523                $a->minquestions = $this->properties->minquestions;
3524                $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3525            }
3526        }
3527
3528        if (!$canmanage) {
3529            if ($data->gradelesson) {
3530                // Store this now before any modifications to pages viewed.
3531                $progresscompleted = $this->calculate_progress();
3532
3533                // Update the clock / get time information for this user.
3534                $this->stop_timer();
3535
3536                // Update completion state.
3537                $completion = new completion_info($course);
3538                if ($completion->is_enabled($cm) && $this->properties->completionendreached) {
3539                    $completion->update_state($cm, COMPLETION_COMPLETE);
3540                }
3541
3542                if ($this->properties->completiontimespent > 0) {
3543                    $duration = $DB->get_field_sql(
3544                        "SELECT SUM(lessontime - starttime)
3545                                       FROM {lesson_timer}
3546                                      WHERE lessonid = :lessonid
3547                                        AND userid = :userid",
3548                        array('userid' => $USER->id, 'lessonid' => $this->properties->id));
3549                    if (!$duration) {
3550                        $duration = 0;
3551                    }
3552
3553                    // If student has not spend enough time in the lesson, display a message.
3554                    if ($duration < $this->properties->completiontimespent) {
3555                        $a = new stdClass;
3556                        $a->timespentraw = $duration;
3557                        $a->timespent = format_time($duration);
3558                        $a->timerequiredraw = $this->properties->completiontimespent;
3559                        $a->timerequired = format_time($this->properties->completiontimespent);
3560                        $data->notenoughtimespent = $a;
3561                    }
3562                }
3563
3564                if ($gradeinfo->attempts) {
3565                    if (!$this->properties->custom) {
3566                        $data->numberofpagesviewed = $gradeinfo->nquestions;
3567                        if ($this->properties->minquestions) {
3568                            if ($gradeinfo->nquestions < $this->properties->minquestions) {
3569                                $data->youshouldview = $this->properties->minquestions;
3570                            }
3571                        }
3572                        $data->numberofcorrectanswers = $gradeinfo->earned;
3573                    }
3574                    $a = new stdClass;
3575                    $a->score = $gradeinfo->earned;
3576                    $a->grade = $gradeinfo->total;
3577                    if ($gradeinfo->nmanual) {
3578                        $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
3579                        $a->essayquestions = $gradeinfo->nmanual;
3580                        $data->displayscorewithessays = $a;
3581                    } else {
3582                        $data->displayscorewithoutessays = $a;
3583                    }
3584                    if ($this->properties->grade != GRADE_TYPE_NONE) {
3585                        $a = new stdClass;
3586                        $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3587                        $a->total = $this->properties->grade;
3588                        $data->yourcurrentgradeisoutof = $a;
3589                    }
3590
3591                    $grade = new stdClass();
3592                    $grade->lessonid = $this->properties->id;
3593                    $grade->userid = $USER->id;
3594                    $grade->grade = $gradeinfo->grade;
3595                    $grade->completed = time();
3596                    if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record.
3597                        if (!$grades = $DB->get_records("lesson_grades",
3598                            array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
3599                            throw new moodle_exception('cannotfindgrade', 'lesson');
3600                        }
3601                        $oldgrade = array_shift($grades);
3602                        $grade->id = $oldgrade->id;
3603                        $DB->update_record("lesson_grades", $grade);
3604                    } else {
3605                        $newgradeid = $DB->insert_record("lesson_grades", $grade);
3606                    }
3607                } else {
3608                    if ($this->properties->timelimit) {
3609                        if ($outoftime == 'normal') {
3610                            $grade = new stdClass();
3611                            $grade->lessonid = $this->properties->id;
3612                            $grade->userid = $USER->id;
3613                            $grade->grade = 0;
3614                            $grade->completed = time();
3615                            $newgradeid = $DB->insert_record("lesson_grades", $grade);
3616                            $data->eolstudentoutoftimenoanswers = true;
3617                        }
3618                    } else {
3619                        $data->welldone = true;
3620                    }
3621                }
3622
3623                // Update central gradebook.
3624                lesson_update_grades($this, $USER->id);
3625                $data->progresscompleted = $progresscompleted;
3626            }
3627        } else {
3628            // Display for teacher.
3629            if ($this->properties->grade != GRADE_TYPE_NONE) {
3630                $data->displayofgrade = true;
3631            }
3632        }
3633
3634        if ($this->properties->modattempts && !$canmanage) {
3635            // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3636            // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3637            // to pass to view again.  This is slick cause it wont call the empty($pageid) code
3638            // $ntries is decremented above.
3639            if (!$attempts = $this->get_attempts($ntries)) {
3640                $attempts = array();
3641                $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id));
3642            } else {
3643                $firstattempt = current($attempts);
3644                $pageid = $firstattempt->pageid;
3645                // If the student wishes to review, need to know the last question page that the student answered.
3646                // This will help to make sure that the student can leave the lesson via pushing the continue button.
3647                $lastattempt = end($attempts);
3648                $USER->modattempts[$this->properties->id] = $lastattempt->pageid;
3649
3650                $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid));
3651            }
3652            $data->reviewlesson = $url->out(false);
3653        } else if ($this->properties->modattempts && $canmanage) {
3654            $data->modattemptsnoteacher = true;
3655        }
3656
3657        if ($this->properties->activitylink) {
3658            $data->activitylink = $this->link_for_activitylink();
3659        }
3660        return $data;
3661    }
3662}
3663
3664
3665/**
3666 * Abstract class to provide a core functions to the all lesson classes
3667 *
3668 * This class should be abstracted by ALL classes with the lesson module to ensure
3669 * that all classes within this module can be interacted with in the same way.
3670 *
3671 * This class provides the user with a basic properties array that can be fetched
3672 * or set via magic methods, or alternatively by defining methods get_blah() or
3673 * set_blah() within the extending object.
3674 *
3675 * @copyright  2009 Sam Hemelryk
3676 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3677 */
3678abstract class lesson_base {
3679
3680    /**
3681     * An object containing properties
3682     * @var stdClass
3683     */
3684    protected $properties;
3685
3686    /**
3687     * The constructor
3688     * @param stdClass $properties
3689     */
3690    public function __construct($properties) {
3691        $this->properties = (object)$properties;
3692    }
3693
3694    /**
3695     * Magic property method
3696     *
3697     * Attempts to call a set_$key method if one exists otherwise falls back
3698     * to simply set the property
3699     *
3700     * @param string $key
3701     * @param mixed $value
3702     */
3703    public function __set($key, $value) {
3704        if (method_exists($this, 'set_'.$key)) {
3705            $this->{'set_'.$key}($value);
3706        }
3707        $this->properties->{$key} = $value;
3708    }
3709
3710    /**
3711     * Magic get method
3712     *
3713     * Attempts to call a get_$key method to return the property and ralls over
3714     * to return the raw property
3715     *
3716     * @param str $key
3717     * @return mixed
3718     */
3719    public function __get($key) {
3720        if (method_exists($this, 'get_'.$key)) {
3721            return $this->{'get_'.$key}();
3722        }
3723        return $this->properties->{$key};
3724    }
3725
3726    /**
3727     * Stupid PHP needs an isset magic method if you use the get magic method and
3728     * still want empty calls to work.... blah ~!
3729     *
3730     * @param string $key
3731     * @return bool
3732     */
3733    public function __isset($key) {
3734        if (method_exists($this, 'get_'.$key)) {
3735            $val = $this->{'get_'.$key}();
3736            return !empty($val);
3737        }
3738        return !empty($this->properties->{$key});
3739    }
3740
3741    //NOTE: E_STRICT does not allow to change function signature!
3742
3743    /**
3744     * If implemented should create a new instance, save it in the DB and return it
3745     */
3746    //public static function create() {}
3747    /**
3748     * If implemented should load an instance from the DB and return it
3749     */
3750    //public static function load() {}
3751    /**
3752     * Fetches all of the properties of the object
3753     * @return stdClass
3754     */
3755    public function properties() {
3756        return $this->properties;
3757    }
3758}
3759
3760
3761/**
3762 * Abstract class representation of a page associated with a lesson.
3763 *
3764 * This class should MUST be extended by all specialised page types defined in
3765 * mod/lesson/pagetypes/.
3766 * There are a handful of abstract methods that need to be defined as well as
3767 * severl methods that can optionally be defined in order to make the page type
3768 * operate in the desired way
3769 *
3770 * Database properties
3771 * @property int $id The id of this lesson page
3772 * @property int $lessonid The id of the lesson this page belongs to
3773 * @property int $prevpageid The id of the page before this one
3774 * @property int $nextpageid The id of the next page in the page sequence
3775 * @property int $qtype Identifies the page type of this page
3776 * @property int $qoption Used to record page type specific options
3777 * @property int $layout Used to record page specific layout selections
3778 * @property int $display Used to record page specific display selections
3779 * @property int $timecreated Timestamp for when the page was created
3780 * @property int $timemodified Timestamp for when the page was last modified
3781 * @property string $title The title of this page
3782 * @property string $contents The rich content shown to describe the page
3783 * @property int $contentsformat The format of the contents field
3784 *
3785 * Calculated properties
3786 * @property-read array $answers An array of answers for this page
3787 * @property-read bool $displayinmenublock Toggles display in the left menu block
3788 * @property-read array $jumps An array containing all the jumps this page uses
3789 * @property-read lesson $lesson The lesson this page belongs to
3790 * @property-read int $type The type of the page [question | structure]
3791 * @property-read typeid The unique identifier for the page type
3792 * @property-read typestring The string that describes this page type
3793 *
3794 * @abstract
3795 * @copyright  2009 Sam Hemelryk
3796 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3797 */
3798abstract class lesson_page extends lesson_base {
3799
3800    /**
3801     * A reference to the lesson this page belongs to
3802     * @var lesson
3803     */
3804    protected $lesson = null;
3805    /**
3806     * Contains the answers to this lesson_page once loaded
3807     * @var null|array
3808     */
3809    protected $answers = null;
3810    /**
3811     * This sets the type of the page, can be one of the constants defined below
3812     * @var int
3813     */
3814    protected $type = 0;
3815
3816    /**
3817     * Constants used to identify the type of the page
3818     */
3819    const TYPE_QUESTION = 0;
3820    const TYPE_STRUCTURE = 1;
3821
3822    /**
3823     * Constant used as a delimiter when parsing multianswer questions
3824     */
3825    const MULTIANSWER_DELIMITER = '@^#|';
3826
3827    /**
3828     * This method should return the integer used to identify the page type within
3829     * the database and throughout code. This maps back to the defines used in 1.x
3830     * @abstract
3831     * @return int
3832     */
3833    abstract protected function get_typeid();
3834    /**
3835     * This method should return the string that describes the pagetype
3836     * @abstract
3837     * @return string
3838     */
3839    abstract protected function get_typestring();
3840
3841    /**
3842     * This method gets called to display the page to the user taking the lesson
3843     * @abstract
3844     * @param object $renderer
3845     * @param object $attempt
3846     * @return string
3847     */
3848    abstract public function display($renderer, $attempt);
3849
3850    /**
3851     * Creates a new lesson_page within the database and returns the correct pagetype
3852     * object to use to interact with the new lesson
3853     *
3854     * @final
3855     * @static
3856     * @param object $properties
3857     * @param lesson $lesson
3858     * @return lesson_page Specialised object that extends lesson_page
3859     */
3860    final public static function create($properties, lesson $lesson, $context, $maxbytes) {
3861        global $DB;
3862        $newpage = new stdClass;
3863        $newpage->title = $properties->title;
3864        $newpage->contents = $properties->contents_editor['text'];
3865        $newpage->contentsformat = $properties->contents_editor['format'];
3866        $newpage->lessonid = $lesson->id;
3867        $newpage->timecreated = time();
3868        $newpage->qtype = $properties->qtype;
3869        $newpage->qoption = (isset($properties->qoption))?1:0;
3870        $newpage->layout = (isset($properties->layout))?1:0;
3871        $newpage->display = (isset($properties->display))?1:0;
3872        $newpage->prevpageid = 0; // this is a first page
3873        $newpage->nextpageid = 0; // this is the only page
3874
3875        if ($properties->pageid) {
3876            $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
3877            if (!$prevpage) {
3878                print_error('cannotfindpages', 'lesson');
3879            }
3880            $newpage->prevpageid = $prevpage->id;
3881            $newpage->nextpageid = $prevpage->nextpageid;
3882        } else {
3883            $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
3884            if ($nextpage) {
3885                // This is the first page, there are existing pages put this at the start
3886                $newpage->nextpageid = $nextpage->id;
3887            }
3888        }
3889
3890        $newpage->id = $DB->insert_record("lesson_pages", $newpage);
3891
3892        $editor = new stdClass;
3893        $editor->id = $newpage->id;
3894        $editor->contents_editor = $properties->contents_editor;
3895        $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
3896        $DB->update_record("lesson_pages", $editor);
3897
3898        if ($newpage->prevpageid > 0) {
3899            $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
3900        }
3901        if ($newpage->nextpageid > 0) {
3902            $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
3903        }
3904
3905        $page = lesson_page::load($newpage, $lesson);
3906        $page->create_answers($properties);
3907
3908        // Trigger an event: page created.
3909        $eventparams = array(
3910            'context' => $context,
3911            'objectid' => $newpage->id,
3912            'other' => array(
3913                'pagetype' => $page->get_typestring()
3914                )
3915            );
3916        $event = \mod_lesson\event\page_created::create($eventparams);
3917        $snapshot = clone($newpage);
3918        $snapshot->timemodified = 0;
3919        $event->add_record_snapshot('lesson_pages', $snapshot);
3920        $event->trigger();
3921
3922        $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
3923
3924        return $page;
3925    }
3926
3927    /**
3928     * This method loads a page object from the database and returns it as a
3929     * specialised object that extends lesson_page
3930     *
3931     * @final
3932     * @static
3933     * @param int $id
3934     * @param lesson $lesson
3935     * @return lesson_page Specialised lesson_page object
3936     */
3937    final public static function load($id, lesson $lesson) {
3938        global $DB;
3939
3940        if (is_object($id) && !empty($id->qtype)) {
3941            $page = $id;
3942        } else {
3943            $page = $DB->get_record("lesson_pages", array("id" => $id));
3944            if (!$page) {
3945                print_error('cannotfindpages', 'lesson');
3946            }
3947        }
3948        $manager = lesson_page_type_manager::get($lesson);
3949
3950        $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
3951        if (!class_exists($class)) {
3952            $class = 'lesson_page';
3953        }
3954
3955        return new $class($page, $lesson);
3956    }
3957
3958    /**
3959     * Deletes a lesson_page from the database as well as any associated records.
3960     * @final
3961     * @return bool
3962     */
3963    final public function delete() {
3964        global $DB;
3965
3966        $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3967        $context = context_module::instance($cm->id);
3968
3969        // Delete files associated with attempts.
3970        $fs = get_file_storage();
3971        if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
3972            foreach ($attempts as $attempt) {
3973                $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
3974                $fs->delete_area_files($context->id, 'mod_lesson', 'essay_answers', $attempt->id);
3975            }
3976        }
3977
3978        // Then delete all the associated records...
3979        $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
3980
3981        $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
3982
3983        // Delete files related to answers and responses.
3984        if ($answers = $DB->get_records("lesson_answers", array("pageid" => $this->properties->id))) {
3985            foreach ($answers as $answer) {
3986                $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $answer->id);
3987                $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $answer->id);
3988            }
3989        }
3990
3991        // ...now delete the answers...
3992        $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
3993        // ..and the page itself
3994        $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
3995
3996        // Trigger an event: page deleted.
3997        $eventparams = array(
3998            'context' => $context,
3999            'objectid' => $this->properties->id,
4000            'other' => array(
4001                'pagetype' => $this->get_typestring()
4002                )
4003            );
4004        $event = \mod_lesson\event\page_deleted::create($eventparams);
4005        $event->add_record_snapshot('lesson_pages', $this->properties);
4006        $event->trigger();
4007
4008        // Delete files associated with this page.
4009        $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
4010
4011        // repair the hole in the linkage
4012        if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
4013            //This is the only page, no repair needed
4014        } elseif (!$this->properties->prevpageid) {
4015            // this is the first page...
4016            $page = $this->lesson->load_page($this->properties->nextpageid);
4017            $page->move(null, 0);
4018        } elseif (!$this->properties->nextpageid) {
4019            // this is the last page...
4020            $page = $this->lesson->load_page($this->properties->prevpageid);
4021            $page->move(0);
4022        } else {
4023            // page is in the middle...
4024            $prevpage = $this->lesson->load_page($this->properties->prevpageid);
4025            $nextpage = $this->lesson->load_page($this->properties->nextpageid);
4026
4027            $prevpage->move($nextpage->id);
4028            $nextpage->move(null, $prevpage->id);
4029        }
4030        return true;
4031    }
4032
4033    /**
4034     * Moves a page by updating its nextpageid and prevpageid values within
4035     * the database
4036     *
4037     * @final
4038     * @param int $nextpageid
4039     * @param int $prevpageid
4040     */
4041    final public function move($nextpageid=null, $prevpageid=null) {
4042        global $DB;
4043        if ($nextpageid === null) {
4044            $nextpageid = $this->properties->nextpageid;
4045        }
4046        if ($prevpageid === null) {
4047            $prevpageid = $this->properties->prevpageid;
4048        }
4049        $obj = new stdClass;
4050        $obj->id = $this->properties->id;
4051        $obj->prevpageid = $prevpageid;
4052        $obj->nextpageid = $nextpageid;
4053        $DB->update_record('lesson_pages', $obj);
4054    }
4055
4056    /**
4057     * Returns the answers that are associated with this page in the database
4058     *
4059     * @final
4060     * @return array
4061     */
4062    final public function get_answers() {
4063        global $DB;
4064        if ($this->answers === null) {
4065            $this->answers = array();
4066            $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
4067            if (!$answers) {
4068                // It is possible that a lesson upgraded from Moodle 1.9 still
4069                // contains questions without any answers [MDL-25632].
4070                // debugging(get_string('cannotfindanswer', 'lesson'));
4071                return array();
4072            }
4073            foreach ($answers as $answer) {
4074                $this->answers[count($this->answers)] = new lesson_page_answer($answer);
4075            }
4076        }
4077        return $this->answers;
4078    }
4079
4080    /**
4081     * Returns the lesson this page is associated with
4082     * @final
4083     * @return lesson
4084     */
4085    final protected function get_lesson() {
4086        return $this->lesson;
4087    }
4088
4089    /**
4090     * Returns the type of page this is. Not to be confused with page type
4091     * @final
4092     * @return int
4093     */
4094    final protected function get_type() {
4095        return $this->type;
4096    }
4097
4098    /**
4099     * Records an attempt at this page
4100     *
4101     * @final
4102     * @global moodle_database $DB
4103     * @param stdClass $context
4104     * @return stdClass Returns the result of the attempt
4105     */
4106    final public function record_attempt($context) {
4107        global $DB, $USER, $OUTPUT, $PAGE;
4108
4109        /**
4110         * This should be overridden by each page type to actually check the response
4111         * against what ever custom criteria they have defined
4112         */
4113        $result = $this->check_answer();
4114
4115        // Processes inmediate jumps.
4116        if ($result->inmediatejump) {
4117            return $result;
4118        }
4119
4120        $result->attemptsremaining  = 0;
4121        $result->maxattemptsreached = false;
4122
4123        if ($result->noanswer) {
4124            $result->newpageid = $this->properties->id; // display same page again
4125            $result->feedback  = get_string('noanswer', 'lesson');
4126        } else {
4127            if (!has_capability('mod/lesson:manage', $context)) {
4128                $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4129
4130                // Get the number of attempts that have been made on this question for this student and retake,
4131                $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
4132                    'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
4133
4134                // Check if they have reached (or exceeded) the maximum number of attempts allowed.
4135                if ($nattempts >= $this->lesson->maxattempts) {
4136                    $result->maxattemptsreached = true;
4137                    $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
4138                    $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
4139                    return $result;
4140                }
4141
4142                // record student's attempt
4143                $attempt = new stdClass;
4144                $attempt->lessonid = $this->lesson->id;
4145                $attempt->pageid = $this->properties->id;
4146                $attempt->userid = $USER->id;
4147                $attempt->answerid = $result->answerid;
4148                $attempt->retry = $nretakes;
4149                $attempt->correct = $result->correctanswer;
4150                if($result->userresponse !== null) {
4151                    $attempt->useranswer = $result->userresponse;
4152                }
4153
4154                $attempt->timeseen = time();
4155                // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
4156                $userisreviewing = false;
4157                if (isset($USER->modattempts[$this->lesson->id])) {
4158                    $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
4159                    $userisreviewing = true;
4160                }
4161
4162                // Only insert a record if we are not reviewing the lesson.
4163                if (!$userisreviewing) {
4164                    if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
4165                        $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
4166
4167                        list($updatedattempt, $updatedresult) = $this->on_after_write_attempt($attempt, $result);
4168                        if ($updatedattempt) {
4169                            $attempt = $updatedattempt;
4170                            $result = $updatedresult;
4171                            $DB->update_record("lesson_attempts", $attempt);
4172                        }
4173
4174                        // Trigger an event: question answered.
4175                        $eventparams = array(
4176                            'context' => context_module::instance($PAGE->cm->id),
4177                            'objectid' => $this->properties->id,
4178                            'other' => array(
4179                                'pagetype' => $this->get_typestring()
4180                                )
4181                            );
4182                        $event = \mod_lesson\event\question_answered::create($eventparams);
4183                        $event->add_record_snapshot('lesson_attempts', $attempt);
4184                        $event->trigger();
4185
4186                        // Increase the number of attempts made.
4187                        $nattempts++;
4188                    }
4189                } else {
4190                    // When reviewing the lesson, the existing attemptid is also needed for the filearea options.
4191                    $params = [
4192                        'lessonid' => $attempt->lessonid,
4193                        'pageid' => $attempt->pageid,
4194                        'userid' => $attempt->userid,
4195                        'answerid' => $attempt->answerid,
4196                        'retry' => $attempt->retry
4197                    ];
4198                    $attempt->id = $DB->get_field('lesson_attempts', 'id', $params);
4199                }
4200                // "number of attempts remaining" message if $this->lesson->maxattempts > 1
4201                // displaying of message(s) is at the end of page for more ergonomic display
4202                if (!$result->correctanswer && ($result->newpageid == 0)) {
4203                    // retreive the number of attempts left counter for displaying at bottom of feedback page
4204                    if ($nattempts >= $this->lesson->maxattempts) {
4205                        if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4206                            $result->maxattemptsreached = true;
4207                        }
4208                        $result->newpageid = LESSON_NEXTPAGE;
4209                    } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4210                        $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
4211                    }
4212                }
4213            }
4214
4215            // Determine default feedback if necessary
4216            if (empty($result->response)) {
4217                if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
4218                    // These conditions have been met:
4219                    //  1. The lesson manager has not supplied feedback to the student
4220                    //  2. Not displaying default feedback
4221                    //  3. The user did provide an answer
4222                    //  4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
4223
4224                    $result->nodefaultresponse = true;  // This will cause a redirect below
4225                } else if ($result->isessayquestion) {
4226                    $result->response = get_string('defaultessayresponse', 'lesson');
4227                } else if ($result->correctanswer) {
4228                    $result->response = get_string('thatsthecorrectanswer', 'lesson');
4229                } else {
4230                    $result->response = get_string('thatsthewronganswer', 'lesson');
4231                }
4232            }
4233
4234            if ($result->response) {
4235                if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
4236                    $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4237                    $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
4238                    if ($qattempts == 1) {
4239                        $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
4240                    } else {
4241                        if (!$result->maxattemptsreached) {
4242                            $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
4243                        } else {
4244                            $result->feedback = $OUTPUT->box(get_string("finalwrong", "lesson"), 'feedback');
4245                        }
4246                    }
4247                } else {
4248                    $result->feedback = '';
4249                }
4250                $class = 'response';
4251                if ($result->correctanswer) {
4252                    $class .= ' correct'; // CSS over-ride this if they exist (!important).
4253                } else if (!$result->isessayquestion) {
4254                    $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
4255                }
4256                $options = new stdClass;
4257                $options->noclean = true;
4258                $options->para = true;
4259                $options->overflowdiv = true;
4260                $options->context = $context;
4261                $options->attemptid = isset($attempt) ? $attempt->id : null;
4262
4263                $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
4264                        'generalbox boxaligncenter p-y-1');
4265                $result->feedback .= '<div class="correctanswer generalbox"><em>'
4266                        . get_string("youranswer", "lesson").'</em> : <div class="studentanswer mt-2 mb-2">';
4267
4268                // Create a table containing the answers and responses.
4269                $table = new html_table();
4270                // Multianswer allowed.
4271                if ($this->properties->qoption) {
4272                    $studentanswerarray = explode(self::MULTIANSWER_DELIMITER, $result->studentanswer);
4273                    $responsearr = explode(self::MULTIANSWER_DELIMITER, $result->response);
4274                    $studentanswerresponse = array_combine($studentanswerarray, $responsearr);
4275
4276                    foreach ($studentanswerresponse as $answer => $response) {
4277                        // Add a table row containing the answer.
4278                        $studentanswer = $this->format_answer($answer, $context, $result->studentanswerformat, $options);
4279                        $table->data[] = array($studentanswer);
4280                        // If the response exists, add a table row containing the response. If not, add en empty row.
4281                        if (!empty(trim($response))) {
4282                            $studentresponse = isset($result->responseformat) ?
4283                                $this->format_response($response, $context, $result->responseformat, $options) : $response;
4284                            $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") .
4285                                '</em>: <br/>' . $studentresponse, $class);
4286                            $table->data[] = array($studentresponsecontent);
4287                        } else {
4288                            $table->data[] = array('');
4289                        }
4290                    }
4291                } else {
4292                    // Add a table row containing the answer.
4293                    $studentanswer = $this->format_answer($result->studentanswer, $context, $result->studentanswerformat, $options);
4294                    $table->data[] = array($studentanswer);
4295                    // If the response exists, add a table row containing the response. If not, add en empty row.
4296                    if (!empty(trim($result->response))) {
4297                        $studentresponse = isset($result->responseformat) ?
4298                            $this->format_response($result->response, $context, $result->responseformat,
4299                                $result->answerid, $options) : $result->response;
4300                        $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") .
4301                            '</em>: <br/>' . $studentresponse, $class);
4302                        $table->data[] = array($studentresponsecontent);
4303                    } else {
4304                        $table->data[] = array('');
4305                    }
4306                }
4307
4308                $result->feedback .= html_writer::table($table).'</div></div>';
4309            }
4310        }
4311        return $result;
4312    }
4313
4314    /**
4315     * Formats the answer. Override for custom formatting.
4316     *
4317     * @param string $answer
4318     * @param context $context
4319     * @param int $answerformat
4320     * @return string Returns formatted string
4321     */
4322    public function format_answer($answer, $context, $answerformat, $options = []) {
4323
4324        if (is_object($options)) {
4325            $options = (array) $options;
4326        }
4327
4328        if (empty($options['context'])) {
4329            $options['context'] = $context;
4330        }
4331
4332        if (empty($options['para'])) {
4333            $options['para'] = true;
4334        }
4335
4336        return format_text($answer, $answerformat, $options);
4337    }
4338
4339    /**
4340     * Formats the response
4341     *
4342     * @param string $response
4343     * @param context $context
4344     * @param int $responseformat
4345     * @param int $answerid
4346     * @param stdClass $options
4347     * @return string Returns formatted string
4348     */
4349    private function format_response($response, $context, $responseformat, $answerid, $options) {
4350
4351        $convertstudentresponse = file_rewrite_pluginfile_urls($response, 'pluginfile.php',
4352            $context->id, 'mod_lesson', 'page_responses', $answerid);
4353
4354        return format_text($convertstudentresponse, $responseformat, $options);
4355    }
4356
4357    /**
4358     * Returns the string for a jump name
4359     *
4360     * @final
4361     * @param int $jumpto Jump code or page ID
4362     * @return string
4363     **/
4364    final protected function get_jump_name($jumpto) {
4365        global $DB;
4366        static $jumpnames = array();
4367
4368        if (!array_key_exists($jumpto, $jumpnames)) {
4369            if ($jumpto == LESSON_THISPAGE) {
4370                $jumptitle = get_string('thispage', 'lesson');
4371            } elseif ($jumpto == LESSON_NEXTPAGE) {
4372                $jumptitle = get_string('nextpage', 'lesson');
4373            } elseif ($jumpto == LESSON_EOL) {
4374                $jumptitle = get_string('endoflesson', 'lesson');
4375            } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
4376                $jumptitle = get_string('unseenpageinbranch', 'lesson');
4377            } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
4378                $jumptitle = get_string('previouspage', 'lesson');
4379            } elseif ($jumpto == LESSON_RANDOMPAGE) {
4380                $jumptitle = get_string('randompageinbranch', 'lesson');
4381            } elseif ($jumpto == LESSON_RANDOMBRANCH) {
4382                $jumptitle = get_string('randombranch', 'lesson');
4383            } elseif ($jumpto == LESSON_CLUSTERJUMP) {
4384                $jumptitle = get_string('clusterjump', 'lesson');
4385            } else {
4386                if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
4387                    $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
4388                }
4389            }
4390            $jumpnames[$jumpto] = format_string($jumptitle,true);
4391        }
4392
4393        return $jumpnames[$jumpto];
4394    }
4395
4396    /**
4397     * Constructor method
4398     * @param object $properties
4399     * @param lesson $lesson
4400     */
4401    public function __construct($properties, lesson $lesson) {
4402        parent::__construct($properties);
4403        $this->lesson = $lesson;
4404    }
4405
4406    /**
4407     * Returns the score for the attempt
4408     * This may be overridden by page types that require manual grading
4409     * @param array $answers
4410     * @param object $attempt
4411     * @return int
4412     */
4413    public function earned_score($answers, $attempt) {
4414        return $answers[$attempt->answerid]->score;
4415    }
4416
4417    /**
4418     * This is a callback method that can be override and gets called when ever a page
4419     * is viewed
4420     *
4421     * @param bool $canmanage True if the user has the manage cap
4422     * @param bool $redirect  Optional, default to true. Set to false to avoid redirection and return the page to redirect.
4423     * @return mixed
4424     */
4425    public function callback_on_view($canmanage, $redirect = true) {
4426        return true;
4427    }
4428
4429    /**
4430     * save editor answers files and update answer record
4431     *
4432     * @param object $context
4433     * @param int $maxbytes
4434     * @param object $answer
4435     * @param object $answereditor
4436     * @param object $responseeditor
4437     */
4438    public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
4439        global $DB;
4440        if (isset($answereditor['itemid'])) {
4441            $answer->answer = file_save_draft_area_files($answereditor['itemid'],
4442                    $context->id, 'mod_lesson', 'page_answers', $answer->id,
4443                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4444                    $answer->answer, null);
4445            $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
4446        }
4447        if (isset($responseeditor['itemid'])) {
4448            $answer->response = file_save_draft_area_files($responseeditor['itemid'],
4449                    $context->id, 'mod_lesson', 'page_responses', $answer->id,
4450                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4451                    $answer->response, null);
4452            $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
4453        }
4454    }
4455
4456    /**
4457     * Rewrite urls in response and optionality answer of a question answer
4458     *
4459     * @param object $answer
4460     * @param bool $rewriteanswer must rewrite answer
4461     * @return object answer with rewritten urls
4462     */
4463    public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
4464        global $PAGE;
4465
4466        $context = context_module::instance($PAGE->cm->id);
4467        if ($rewriteanswer) {
4468            $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
4469                    'mod_lesson', 'page_answers', $answer->id);
4470        }
4471        $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
4472                'mod_lesson', 'page_responses', $answer->id);
4473
4474        return $answer;
4475    }
4476
4477    /**
4478     * Updates a lesson page and its answers within the database
4479     *
4480     * @param object $properties
4481     * @return bool
4482     */
4483    public function update($properties, $context = null, $maxbytes = null) {
4484        global $DB, $PAGE;
4485        $answers  = $this->get_answers();
4486        $properties->id = $this->properties->id;
4487        $properties->lessonid = $this->lesson->id;
4488        if (empty($properties->qoption)) {
4489            $properties->qoption = '0';
4490        }
4491        if (empty($context)) {
4492            $context = $PAGE->context;
4493        }
4494        if ($maxbytes === null) {
4495            $maxbytes = get_user_max_upload_file_size($context);
4496        }
4497        $properties->timemodified = time();
4498        $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
4499        $DB->update_record("lesson_pages", $properties);
4500
4501        // Trigger an event: page updated.
4502        \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
4503
4504        if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
4505            // These page types have only one answer to save the jump and score.
4506            if (count($answers) > 1) {
4507                $answer = array_shift($answers);
4508                foreach ($answers as $a) {
4509                    $DB->delete_records('lesson_answers', array('id' => $a->id));
4510                }
4511            } else if (count($answers) == 1) {
4512                $answer = array_shift($answers);
4513            } else {
4514                $answer = new stdClass;
4515                $answer->lessonid = $properties->lessonid;
4516                $answer->pageid = $properties->id;
4517                $answer->timecreated = time();
4518            }
4519
4520            $answer->timemodified = time();
4521            if (isset($properties->jumpto[0])) {
4522                $answer->jumpto = $properties->jumpto[0];
4523            }
4524            if (isset($properties->score[0])) {
4525                $answer->score = $properties->score[0];
4526            }
4527            if (!empty($answer->id)) {
4528                $DB->update_record("lesson_answers", $answer->properties());
4529            } else {
4530                $DB->insert_record("lesson_answers", $answer);
4531            }
4532        } else {
4533            for ($i = 0; $i < count($properties->answer_editor); $i++) {
4534                if (!array_key_exists($i, $this->answers)) {
4535                    $this->answers[$i] = new stdClass;
4536                    $this->answers[$i]->lessonid = $this->lesson->id;
4537                    $this->answers[$i]->pageid = $this->id;
4538                    $this->answers[$i]->timecreated = $this->timecreated;
4539                    $this->answers[$i]->answer = null;
4540                }
4541
4542                if (isset($properties->answer_editor[$i])) {
4543                    if (is_array($properties->answer_editor[$i])) {
4544                        // Multichoice and true/false pages have an HTML editor.
4545                        $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
4546                        $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
4547                    } else {
4548                        // Branch tables, shortanswer and mumerical pages have only a text field.
4549                        $this->answers[$i]->answer = $properties->answer_editor[$i];
4550                        $this->answers[$i]->answerformat = FORMAT_MOODLE;
4551                    }
4552                } else {
4553                    // If there is no data posted which means we want to reset the stored values.
4554                    $this->answers[$i]->answer = null;
4555                }
4556
4557                if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4558                    $this->answers[$i]->response = $properties->response_editor[$i]['text'];
4559                    $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
4560                }
4561
4562                if ($this->answers[$i]->answer !== null && $this->answers[$i]->answer !== '') {
4563                    if (isset($properties->jumpto[$i])) {
4564                        $this->answers[$i]->jumpto = $properties->jumpto[$i];
4565                    }
4566                    if ($this->lesson->custom && isset($properties->score[$i])) {
4567                        $this->answers[$i]->score = $properties->score[$i];
4568                    }
4569                    if (!isset($this->answers[$i]->id)) {
4570                        $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
4571                    } else {
4572                        $DB->update_record("lesson_answers", $this->answers[$i]->properties());
4573                    }
4574
4575                    // Save files in answers and responses.
4576                    if (isset($properties->response_editor[$i])) {
4577                        $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4578                                $properties->answer_editor[$i], $properties->response_editor[$i]);
4579                    } else {
4580                        $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4581                                $properties->answer_editor[$i]);
4582                    }
4583
4584                } else if (isset($this->answers[$i]->id)) {
4585                    $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
4586                    unset($this->answers[$i]);
4587                }
4588            }
4589        }
4590        return true;
4591    }
4592
4593    /**
4594     * Can be set to true if the page requires a static link to create a new instance
4595     * instead of simply being included in the dropdown
4596     * @param int $previd
4597     * @return bool
4598     */
4599    public function add_page_link($previd) {
4600        return false;
4601    }
4602
4603    /**
4604     * Returns true if a page has been viewed before
4605     *
4606     * @param array|int $param Either an array of pages that have been seen or the
4607     *                   number of retakes a user has had
4608     * @return bool
4609     */
4610    public function is_unseen($param) {
4611        global $USER, $DB;
4612        if (is_array($param)) {
4613            $seenpages = $param;
4614            return (!array_key_exists($this->properties->id, $seenpages));
4615        } else {
4616            $nretakes = $param;
4617            if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
4618                return true;
4619            }
4620        }
4621        return false;
4622    }
4623
4624    /**
4625     * Checks to see if a page has been answered previously
4626     * @param int $nretakes
4627     * @return bool
4628     */
4629    public function is_unanswered($nretakes) {
4630        global $DB, $USER;
4631        if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
4632            return true;
4633        }
4634        return false;
4635    }
4636
4637    /**
4638     * Creates answers within the database for this lesson_page. Usually only ever
4639     * called when creating a new page instance
4640     * @param object $properties
4641     * @return array
4642     */
4643    public function create_answers($properties) {
4644        global $DB, $PAGE;
4645        // now add the answers
4646        $newanswer = new stdClass;
4647        $newanswer->lessonid = $this->lesson->id;
4648        $newanswer->pageid = $this->properties->id;
4649        $newanswer->timecreated = $this->properties->timecreated;
4650
4651        $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
4652        $context = context_module::instance($cm->id);
4653
4654        $answers = array();
4655
4656        for ($i = 0; $i < ($this->lesson->maxanswers + 1); $i++) {
4657            $answer = clone($newanswer);
4658
4659            if (isset($properties->answer_editor[$i])) {
4660                if (is_array($properties->answer_editor[$i])) {
4661                    // Multichoice and true/false pages have an HTML editor.
4662                    $answer->answer = $properties->answer_editor[$i]['text'];
4663                    $answer->answerformat = $properties->answer_editor[$i]['format'];
4664                } else {
4665                    // Branch tables, shortanswer and mumerical pages have only a text field.
4666                    $answer->answer = $properties->answer_editor[$i];
4667                    $answer->answerformat = FORMAT_MOODLE;
4668                }
4669            }
4670            if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4671                $answer->response = $properties->response_editor[$i]['text'];
4672                $answer->responseformat = $properties->response_editor[$i]['format'];
4673            }
4674
4675            if (isset($answer->answer) && $answer->answer != '') {
4676                if (isset($properties->jumpto[$i])) {
4677                    $answer->jumpto = $properties->jumpto[$i];
4678                }
4679                if ($this->lesson->custom && isset($properties->score[$i])) {
4680                    $answer->score = $properties->score[$i];
4681                }
4682                $answer->id = $DB->insert_record("lesson_answers", $answer);
4683                if (isset($properties->response_editor[$i])) {
4684                    $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4685                            $properties->answer_editor[$i], $properties->response_editor[$i]);
4686                } else {
4687                    $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4688                            $properties->answer_editor[$i]);
4689                }
4690                $answers[$answer->id] = new lesson_page_answer($answer);
4691            }
4692        }
4693
4694        $this->answers = $answers;
4695        return $answers;
4696    }
4697
4698    /**
4699     * This method MUST be overridden by all question page types, or page types that
4700     * wish to score a page.
4701     *
4702     * The structure of result should always be the same so it is a good idea when
4703     * overriding this method on a page type to call
4704     * <code>
4705     * $result = parent::check_answer();
4706     * </code>
4707     * before modifying it as required.
4708     *
4709     * @return stdClass
4710     */
4711    public function check_answer() {
4712        $result = new stdClass;
4713        $result->answerid        = 0;
4714        $result->noanswer        = false;
4715        $result->correctanswer   = false;
4716        $result->isessayquestion = false;   // use this to turn off review button on essay questions
4717        $result->response        = '';
4718        $result->newpageid       = 0;       // stay on the page
4719        $result->studentanswer   = '';      // use this to store student's answer(s) in order to display it on feedback page
4720        $result->studentanswerformat = FORMAT_MOODLE;
4721        $result->userresponse    = null;
4722        $result->feedback        = '';
4723        // Store data that was POSTd by a form. This is currently used to perform any logic after the 1st write to the db
4724        // of the attempt.
4725        $result->postdata        = false;
4726        $result->nodefaultresponse  = false; // Flag for redirecting when default feedback is turned off
4727        $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing.
4728        return $result;
4729    }
4730
4731    /**
4732     * Do any post persistence processing logic of an attempt. E.g. in cases where we need update file urls in an editor
4733     * and we need to have the id of the stored attempt. Should be overridden in each individual child
4734     * pagetype on a as required basis
4735     *
4736     * @param object $attempt The attempt corresponding to the db record
4737     * @param object $result The result from the 'check_answer' method
4738     * @return array False if nothing to be modified, updated $attempt and $result if update required.
4739     */
4740    public function on_after_write_attempt($attempt, $result) {
4741        return [false, false];
4742    }
4743
4744    /**
4745     * True if the page uses a custom option
4746     *
4747     * Should be override and set to true if the page uses a custom option.
4748     *
4749     * @return bool
4750     */
4751    public function has_option() {
4752        return false;
4753    }
4754
4755    /**
4756     * Returns the maximum number of answers for this page given the maximum number
4757     * of answers permitted by the lesson.
4758     *
4759     * @param int $default
4760     * @return int
4761     */
4762    public function max_answers($default) {
4763        return $default;
4764    }
4765
4766    /**
4767     * Returns the properties of this lesson page as an object
4768     * @return stdClass;
4769     */
4770    public function properties() {
4771        $properties = clone($this->properties);
4772        if ($this->answers === null) {
4773            $this->get_answers();
4774        }
4775        if (count($this->answers)>0) {
4776            $count = 0;
4777            $qtype = $properties->qtype;
4778            foreach ($this->answers as $answer) {
4779                $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
4780                if ($qtype != LESSON_PAGE_MATCHING) {
4781                    $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
4782                } else {
4783                    $properties->{'response_editor['.$count.']'} = $answer->response;
4784                }
4785                $properties->{'jumpto['.$count.']'} = $answer->jumpto;
4786                $properties->{'score['.$count.']'} = $answer->score;
4787                $count++;
4788            }
4789        }
4790        return $properties;
4791    }
4792
4793    /**
4794     * Returns an array of options to display when choosing the jumpto for a page/answer
4795     * @static
4796     * @param int $pageid
4797     * @param lesson $lesson
4798     * @return array
4799     */
4800    public static function get_jumptooptions($pageid, lesson $lesson) {
4801        global $DB;
4802        $jump = array();
4803        $jump[0] = get_string("thispage", "lesson");
4804        $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
4805        $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
4806        $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
4807
4808        if ($pageid == 0) {
4809            return $jump;
4810        }
4811
4812        $pages = $lesson->load_all_pages();
4813        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))) {
4814            $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
4815            $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
4816        }
4817        if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
4818            $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
4819        }
4820        if (!optional_param('firstpage', 0, PARAM_INT)) {
4821            $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
4822            while (true) {
4823                if ($apageid) {
4824                    $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
4825                    $jump[$apageid] = strip_tags(format_string($title,true));
4826                    $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
4827                } else {
4828                    // last page reached
4829                    break;
4830                }
4831            }
4832        }
4833        return $jump;
4834    }
4835    /**
4836     * Returns the contents field for the page properly formatted and with plugin
4837     * file url's converted
4838     * @return string
4839     */
4840    public function get_contents() {
4841        global $PAGE;
4842        if (!empty($this->properties->contents)) {
4843            if (!isset($this->properties->contentsformat)) {
4844                $this->properties->contentsformat = FORMAT_HTML;
4845            }
4846            $context = context_module::instance($PAGE->cm->id);
4847            $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
4848                                                     'page_contents', $this->properties->id);  // Must do this BEFORE format_text()!
4849            return format_text($contents, $this->properties->contentsformat,
4850                               array('context' => $context, 'noclean' => true,
4851                                     'overflowdiv' => true));  // Page edit is marked with XSS, we want all content here.
4852        } else {
4853            return '';
4854        }
4855    }
4856
4857    /**
4858     * Set to true if this page should display in the menu block
4859     * @return bool
4860     */
4861    protected function get_displayinmenublock() {
4862        return false;
4863    }
4864
4865    /**
4866     * Get the string that describes the options of this page type
4867     * @return string
4868     */
4869    public function option_description_string() {
4870        return '';
4871    }
4872
4873    /**
4874     * Updates a table with the answers for this page
4875     * @param html_table $table
4876     * @return html_table
4877     */
4878    public function display_answers(html_table $table) {
4879        $answers = $this->get_answers();
4880        $i = 1;
4881        foreach ($answers as $answer) {
4882            $cells = array();
4883            $cells[] = '<label>' . get_string('jump', 'lesson') . ' ' . $i . '</label>:';
4884            $cells[] = $this->get_jump_name($answer->jumpto);
4885            $table->data[] = new html_table_row($cells);
4886            if ($i === 1){
4887                $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
4888            }
4889            $i++;
4890        }
4891        return $table;
4892    }
4893
4894    /**
4895     * Determines if this page should be grayed out on the management/report screens
4896     * @return int 0 or 1
4897     */
4898    protected function get_grayout() {
4899        return 0;
4900    }
4901
4902    /**
4903     * Adds stats for this page to the &pagestats object. This should be defined
4904     * for all page types that grade
4905     * @param array $pagestats
4906     * @param int $tries
4907     * @return bool
4908     */
4909    public function stats(array &$pagestats, $tries) {
4910        return true;
4911    }
4912
4913    /**
4914     * Formats the answers of this page for a report
4915     *
4916     * @param object $answerpage
4917     * @param object $answerdata
4918     * @param object $useranswer
4919     * @param array $pagestats
4920     * @param int $i Count of first level answers
4921     * @param int $n Count of second level answers
4922     * @return object The answer page for this
4923     */
4924    public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
4925        $answers = $this->get_answers();
4926        $formattextdefoptions = new stdClass;
4927        $formattextdefoptions->para = false;  //I'll use it widely in this page
4928        foreach ($answers as $answer) {
4929            $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
4930            $answerdata->answers[] = array($data, "");
4931            $answerpage->answerdata = $answerdata;
4932        }
4933        return $answerpage;
4934    }
4935
4936    /**
4937     * Gets an array of the jumps used by the answers of this page
4938     *
4939     * @return array
4940     */
4941    public function get_jumps() {
4942        global $DB;
4943        $jumps = array();
4944        $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
4945        if ($answers = $this->get_answers()) {
4946            foreach ($answers as $answer) {
4947                $jumps[] = $this->get_jump_name($answer->jumpto);
4948            }
4949        } else {
4950            $jumps[] = $this->get_jump_name($this->properties->nextpageid);
4951        }
4952        return $jumps;
4953    }
4954    /**
4955     * Informs whether this page type require manual grading or not
4956     * @return bool
4957     */
4958    public function requires_manual_grading() {
4959        return false;
4960    }
4961
4962    /**
4963     * A callback method that allows a page to override the next page a user will
4964     * see during when this page is being completed.
4965     * @return false|int
4966     */
4967    public function override_next_page() {
4968        return false;
4969    }
4970
4971    /**
4972     * This method is used to determine if this page is a valid page
4973     *
4974     * @param array $validpages
4975     * @param array $pageviews
4976     * @return int The next page id to check
4977     */
4978    public function valid_page_and_view(&$validpages, &$pageviews) {
4979        $validpages[$this->properties->id] = 1;
4980        return $this->properties->nextpageid;
4981    }
4982
4983    /**
4984     * Get files from the page area file.
4985     *
4986     * @param bool $includedirs whether or not include directories
4987     * @param int $updatedsince return files updated since this time
4988     * @return array list of stored_file objects
4989     * @since  Moodle 3.2
4990     */
4991    public function get_files($includedirs = true, $updatedsince = 0) {
4992        $fs = get_file_storage();
4993        return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id,
4994                                    'itemid, filepath, filename', $includedirs, $updatedsince);
4995    }
4996
4997    /**
4998     * Make updates to the form data if required.
4999     *
5000     * @since Moodle 3.7
5001     * @param stdClass $data The form data to update.
5002     * @return stdClass The updated fom data.
5003     */
5004    public function update_form_data(stdClass $data) : stdClass {
5005        return $data;
5006    }
5007}
5008
5009
5010
5011/**
5012 * Class used to represent an answer to a page
5013 *
5014 * @property int $id The ID of this answer in the database
5015 * @property int $lessonid The ID of the lesson this answer belongs to
5016 * @property int $pageid The ID of the page this answer belongs to
5017 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
5018 * @property int $grade The grade this answer is worth
5019 * @property int $score The score this answer will give
5020 * @property int $flags Used to store options for the answer
5021 * @property int $timecreated A timestamp of when the answer was created
5022 * @property int $timemodified A timestamp of when the answer was modified
5023 * @property string $answer The answer itself
5024 * @property string $response The response the user sees if selecting this answer
5025 *
5026 * @copyright  2009 Sam Hemelryk
5027 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5028 */
5029class lesson_page_answer extends lesson_base {
5030
5031    /**
5032     * Loads an page answer from the DB
5033     *
5034     * @param int $id
5035     * @return lesson_page_answer
5036     */
5037    public static function load($id) {
5038        global $DB;
5039        $answer = $DB->get_record("lesson_answers", array("id" => $id));
5040        return new lesson_page_answer($answer);
5041    }
5042
5043    /**
5044     * Given an object of properties and a page created answer(s) and saves them
5045     * in the database.
5046     *
5047     * @param stdClass $properties
5048     * @param lesson_page $page
5049     * @return array
5050     */
5051    public static function create($properties, lesson_page $page) {
5052        return $page->create_answers($properties);
5053    }
5054
5055    /**
5056     * Get files from the answer area file.
5057     *
5058     * @param bool $includedirs whether or not include directories
5059     * @param int $updatedsince return files updated since this time
5060     * @return array list of stored_file objects
5061     * @since  Moodle 3.2
5062     */
5063    public function get_files($includedirs = true, $updatedsince = 0) {
5064
5065        $lesson = lesson::load($this->properties->lessonid);
5066        $fs = get_file_storage();
5067        $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
5068                                            'itemid, filepath, filename', $includedirs, $updatedsince);
5069        $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
5070                                            'itemid, filepath, filename', $includedirs, $updatedsince);
5071        return array_merge($answerfiles, $responsefiles);
5072    }
5073
5074}
5075
5076/**
5077 * A management class for page types
5078 *
5079 * This class is responsible for managing the different pages. A manager object can
5080 * be retrieved by calling the following line of code:
5081 * <code>
5082 * $manager  = lesson_page_type_manager::get($lesson);
5083 * </code>
5084 * The first time the page type manager is retrieved the it includes all of the
5085 * different page types located in mod/lesson/pagetypes.
5086 *
5087 * @copyright  2009 Sam Hemelryk
5088 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5089 */
5090class lesson_page_type_manager {
5091
5092    /**
5093     * An array of different page type classes
5094     * @var array
5095     */
5096    protected $types = array();
5097
5098    /**
5099     * Retrieves the lesson page type manager object
5100     *
5101     * If the object hasn't yet been created it is created here.
5102     *
5103     * @staticvar lesson_page_type_manager $pagetypemanager
5104     * @param lesson $lesson
5105     * @return lesson_page_type_manager
5106     */
5107    public static function get(lesson $lesson) {
5108        static $pagetypemanager;
5109        if (!($pagetypemanager instanceof lesson_page_type_manager)) {
5110            $pagetypemanager = new lesson_page_type_manager();
5111            $pagetypemanager->load_lesson_types($lesson);
5112        }
5113        return $pagetypemanager;
5114    }
5115
5116    /**
5117     * Finds and loads all lesson page types in mod/lesson/pagetypes
5118     *
5119     * @param lesson $lesson
5120     */
5121    public function load_lesson_types(lesson $lesson) {
5122        global $CFG;
5123        $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
5124        $dir = dir($basedir);
5125        while (false !== ($entry = $dir->read())) {
5126            if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
5127                continue;
5128            }
5129            require_once($basedir.$entry);
5130            $class = 'lesson_page_type_'.strtok($entry,'.');
5131            if (class_exists($class)) {
5132                $pagetype = new $class(new stdClass, $lesson);
5133                $this->types[$pagetype->typeid] = $pagetype;
5134            }
5135        }
5136
5137    }
5138
5139    /**
5140     * Returns an array of strings to describe the loaded page types
5141     *
5142     * @param int $type Can be used to return JUST the string for the requested type
5143     * @return array
5144     */
5145    public function get_page_type_strings($type=null, $special=true) {
5146        $types = array();
5147        foreach ($this->types as $pagetype) {
5148            if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
5149                $types[$pagetype->typeid] = $pagetype->typestring;
5150            }
5151        }
5152        return $types;
5153    }
5154
5155    /**
5156     * Returns the basic string used to identify a page type provided with an id
5157     *
5158     * This string can be used to instantiate or identify the page type class.
5159     * If the page type id is unknown then 'unknown' is returned
5160     *
5161     * @param int $id
5162     * @return string
5163     */
5164    public function get_page_type_idstring($id) {
5165        foreach ($this->types as $pagetype) {
5166            if ((int)$pagetype->typeid === (int)$id) {
5167                return $pagetype->idstring;
5168            }
5169        }
5170        return 'unknown';
5171    }
5172
5173    /**
5174     * Loads a page for the provided lesson given it's id
5175     *
5176     * This function loads a page from the lesson when given both the lesson it belongs
5177     * to as well as the page's id.
5178     * If the page doesn't exist an error is thrown
5179     *
5180     * @param int $pageid The id of the page to load
5181     * @param lesson $lesson The lesson the page belongs to
5182     * @return lesson_page A class that extends lesson_page
5183     */
5184    public function load_page($pageid, lesson $lesson) {
5185        global $DB;
5186        if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
5187            print_error('cannotfindpages', 'lesson');
5188        }
5189        $pagetype = get_class($this->types[$page->qtype]);
5190        $page = new $pagetype($page, $lesson);
5191        return $page;
5192    }
5193
5194    /**
5195     * This function detects errors in the ordering between 2 pages and updates the page records.
5196     *
5197     * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
5198     * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
5199     */
5200    protected function check_page_order($page1, $page2) {
5201        global $DB;
5202        if (empty($page1)) {
5203            if ($page2->prevpageid != 0) {
5204                debugging("***prevpageid of page " . $page2->id . " set to 0***");
5205                $page2->prevpageid = 0;
5206                $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
5207            }
5208        } else if (empty($page2)) {
5209            if ($page1->nextpageid != 0) {
5210                debugging("***nextpageid of page " . $page1->id . " set to 0***");
5211                $page1->nextpageid = 0;
5212                $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
5213            }
5214        } else {
5215            if ($page1->nextpageid != $page2->id) {
5216                debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
5217                $page1->nextpageid = $page2->id;
5218                $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
5219            }
5220            if ($page2->prevpageid != $page1->id) {
5221                debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
5222                $page2->prevpageid = $page1->id;
5223                $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
5224            }
5225        }
5226    }
5227
5228    /**
5229     * This function loads ALL pages that belong to the lesson.
5230     *
5231     * @param lesson $lesson
5232     * @return array An array of lesson_page_type_*
5233     */
5234    public function load_all_pages(lesson $lesson) {
5235        global $DB;
5236        if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
5237            return array(); // Records returned empty.
5238        }
5239        foreach ($pages as $key=>$page) {
5240            $pagetype = get_class($this->types[$page->qtype]);
5241            $pages[$key] = new $pagetype($page, $lesson);
5242        }
5243
5244        $orderedpages = array();
5245        $lastpageid = 0;
5246        $morepages = true;
5247        while ($morepages) {
5248            $morepages = false;
5249            foreach ($pages as $page) {
5250                if ((int)$page->prevpageid === (int)$lastpageid) {
5251                    // Check for errors in page ordering and fix them on the fly.
5252                    $prevpage = null;
5253                    if ($lastpageid !== 0) {
5254                        $prevpage = $orderedpages[$lastpageid];
5255                    }
5256                    $this->check_page_order($prevpage, $page);
5257                    $morepages = true;
5258                    $orderedpages[$page->id] = $page;
5259                    unset($pages[$page->id]);
5260                    $lastpageid = $page->id;
5261                    if ((int)$page->nextpageid===0) {
5262                        break 2;
5263                    } else {
5264                        break 1;
5265                    }
5266                }
5267            }
5268        }
5269
5270        // Add remaining pages and fix the nextpageid links for each page.
5271        foreach ($pages as $page) {
5272            // Check for errors in page ordering and fix them on the fly.
5273            $prevpage = null;
5274            if ($lastpageid !== 0) {
5275                $prevpage = $orderedpages[$lastpageid];
5276            }
5277            $this->check_page_order($prevpage, $page);
5278            $orderedpages[$page->id] = $page;
5279            unset($pages[$page->id]);
5280            $lastpageid = $page->id;
5281        }
5282
5283        if ($lastpageid !== 0) {
5284            $this->check_page_order($orderedpages[$lastpageid], null);
5285        }
5286
5287        return $orderedpages;
5288    }
5289
5290    /**
5291     * Fetches an mform that can be used to create/edit an page
5292     *
5293     * @param int $type The id for the page type
5294     * @param array $arguments Any arguments to pass to the mform
5295     * @return lesson_add_page_form_base
5296     */
5297    public function get_page_form($type, $arguments) {
5298        $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
5299        if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
5300            debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
5301            $class = 'lesson_add_page_form_selection';
5302        } else if ($class === 'lesson_add_page_form_unknown') {
5303            $class = 'lesson_add_page_form_selection';
5304        }
5305        return new $class(null, $arguments);
5306    }
5307
5308    /**
5309     * Returns an array of links to use as add page links
5310     * @param int $previd The id of the previous page
5311     * @return array
5312     */
5313    public function get_add_page_type_links($previd) {
5314        global $OUTPUT;
5315
5316        $links = array();
5317
5318        foreach ($this->types as $key=>$type) {
5319            if ($link = $type->add_page_link($previd)) {
5320                $links[$key] = $link;
5321            }
5322        }
5323
5324        return $links;
5325    }
5326}
5327