3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Local library file for Lesson. These are non-standard functions that are used
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
27 /** Make sure this isn't being directly accessed */
28 defined('MOODLE_INTERNAL') ||
die();
30 /** Include the files that are required by this module */
31 require_once($CFG->dirroot
.'/course/moodleform_mod.php');
32 require_once($CFG->dirroot
. '/mod/lesson/lib.php');
33 require_once($CFG->libdir
. '/filelib.php');
36 define('LESSON_THISPAGE', 0);
37 /** Next page -> any page not seen before */
38 define("LESSON_UNSEENPAGE", 1);
39 /** Next page -> any page not answered correctly */
40 define("LESSON_UNANSWEREDPAGE", 2);
41 /** Jump to Next Page */
42 define("LESSON_NEXTPAGE", -1);
44 define("LESSON_EOL", -9);
45 /** Jump to an unseen page within a branch and end of branch or end of lesson */
46 define("LESSON_UNSEENBRANCHPAGE", -50);
47 /** Jump to Previous Page */
48 define("LESSON_PREVIOUSPAGE", -40);
49 /** Jump to a random page within a branch and end of branch or end of lesson */
50 define("LESSON_RANDOMPAGE", -60);
51 /** Jump to a random Branch */
52 define("LESSON_RANDOMBRANCH", -70);
54 define("LESSON_CLUSTERJUMP", -80);
56 define("LESSON_UNDEFINED", -99);
58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59 define("LESSON_MAX_EVENT_LENGTH", "432000");
61 /** Answer format is HTML */
62 define("LESSON_ANSWER_HTML", "HTML");
64 /** Placeholder answer for all other answers. */
65 define("LESSON_OTHER_ANSWERS", "@#wronganswer#@");
67 //////////////////////////////////////////////////////////////////////////////////////
68 /// Any other lesson functions go here. Each of them must have a name that
69 /// starts with lesson_
72 * Checks to see if a LESSON_CLUSTERJUMP or
73 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
75 * This function is only executed when a teacher is
76 * checking the navigation for a lesson.
78 * @param stdClass $lesson Id of the lesson that is to be checked.
79 * @return boolean True or false.
81 function lesson_display_teacher_warning($lesson) {
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
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
) {
97 // if no answers use either of the two jumps
102 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
104 * will return the pageid of a random unseen page that is within a branch
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.
111 function lesson_unseen_question_jump($lesson, $user, $pageid) {
114 // get the number of retakes
115 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id
, "userid"=>$user))) {
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
;
125 $seenpages = array();
128 // get the lesson pages
129 $lessonpages = $lesson->load_all_pages();
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
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
) {
140 $pageid = $lessonpages[$pageid]->prevpageid
;
143 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
145 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
147 foreach($pagesinbranch as $page) {
148 if (!in_array($page->id
, $seenpages)) {
149 $unseen[] = $page->id
;
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
158 // there are no pages inside the branch, so return the next page
159 $nextpage = $lessonpages[$pageid]->nextpageid
;
161 if ($nextpage == 0) {
167 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
172 * Handles the unseen branch table jump.
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
178 function lesson_unseen_branch_jump($lesson, $userid) {
181 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id
, "userid"=>$userid))) {
185 if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
186 throw new \
moodle_exception('cannotfindrecords', 'lesson');
189 // get the lesson pages
190 $lessonpages = $lesson->load_all_pages();
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
195 foreach ($seenbranches as $seenbranch) {
196 if (!$seenbranch->flag
) {
197 $seen[$seenbranch->pageid
] = $seenbranch->pageid
;
199 $start = $seenbranch->pageid
;
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
;
211 $pageid = $lessonpages[$pageid]->nextpageid
;
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;
220 if (count($unseen) > 0) {
221 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
223 return LESSON_EOL
; // has viewed all of the branch tables
228 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
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
234 function lesson_random_question_jump($lesson, $pageid) {
237 // get the lesson pages
238 $params = array ("lessonid" => $lesson->id
);
239 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
240 throw new \
moodle_exception('cannotfindpages', 'lesson');
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
246 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_BRANCHTABLE
) {
249 $pageid = $lessonpages[$pageid]->prevpageid
;
252 // get the pages within the branch
253 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
255 if(count($pagesinbranch) == 0) {
256 // there are no pages inside the branch, so return the next page
257 return $lessonpages[$pageid]->nextpageid
;
259 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id
; // returns a random page id for the next page
264 * Calculates a user's grade for a lesson.
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 }
277 function lesson_grade($lesson, $ntries, $userid = 0) {
280 if (empty($userid)) {
284 // Zero out everything
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;
304 if (!empty($lesson->maxattempts
)) {
305 // Drop all attempts that go beyond max attempts for the lesson.
306 foreach ($attemptset as $key => $set) {
307 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts
);
311 // get only the pages and their answers that the user answered
312 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
313 array_unshift($parameters, $lesson->id
);
314 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
315 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
317 // Number of pages answered
318 $nquestions = count($pages);
320 foreach ($attemptset as $attempts) {
321 $page = lesson_page
::load($pages[end($attempts)->pageid
], $lesson);
322 if ($lesson->custom
) {
323 $attempt = end($attempts);
324 // If essay question, handle it, otherwise add to score
325 if ($page->requires_manual_grading()) {
326 $useranswerobj = unserialize_object($attempt->useranswer
);
327 if (isset($useranswerobj->score
)) {
328 $earned +
= $useranswerobj->score
;
331 $manualpoints +
= $answers[$attempt->answerid
]->score
;
332 } else if (!empty($attempt->answerid
)) {
333 $earned +
= $page->earned_score($answers, $attempt);
336 foreach ($attempts as $attempt) {
337 $earned +
= $attempt->correct
;
339 $attempt = end($attempts); // doesn't matter which one
340 // If essay question, increase numbers
341 if ($page->requires_manual_grading()) {
346 // Number of times answered
347 $nviewed +
= count($attempts);
350 if ($lesson->custom
) {
351 $bestscores = array();
352 // Find the highest possible score per page to get our total
353 foreach ($answers as $answer) {
354 if(!isset($bestscores[$answer->pageid
])) {
355 $bestscores[$answer->pageid
] = $answer->score
;
356 } else if ($bestscores[$answer->pageid
] < $answer->score
) {
357 $bestscores[$answer->pageid
] = $answer->score
;
360 $total = array_sum($bestscores);
362 // Check to make sure the student has answered the minimum questions
363 if ($lesson->minquestions
and $nquestions < $lesson->minquestions
) {
364 // Nope, increase number viewed by the amount of unanswered questions
365 $total = $nviewed +
($lesson->minquestions
- $nquestions);
372 if ($total) { // not zero
373 $thegrade = round(100 * $earned / $total, 5);
376 // Build the grade information object
377 $gradeinfo = new stdClass
;
378 $gradeinfo->nquestions
= $nquestions;
379 $gradeinfo->attempts
= $nviewed;
380 $gradeinfo->total
= $total;
381 $gradeinfo->earned
= $earned;
382 $gradeinfo->grade
= $thegrade;
383 $gradeinfo->nmanual
= $nmanual;
384 $gradeinfo->manualpoints
= $manualpoints;
390 * Determines if a user can view the left menu. The determining factor
391 * is whether a user has a grade greater than or equal to the lesson setting
394 * @param object $lesson Lesson object of the current lesson
395 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
397 function lesson_displayleftif($lesson) {
398 global $CFG, $USER, $DB;
400 if (!empty($lesson->displayleftif
)) {
401 // get the current user's max grade for this lesson
402 $params = array ("userid" => $USER->id
, "lessonid" => $lesson->id
);
403 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)) {
404 if ($maxgrade->maxgrade
< $lesson->displayleftif
) {
405 return 0; // turn off the displayleft
408 return 0; // no grades
412 // if we get to here, keep the original state of displayleft lesson setting
413 return $lesson->displayleft
;
421 * @return unknown_type
423 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
424 $bc = lesson_menu_block_contents($cm->id
, $lesson);
426 $regions = $page->blocks
->get_regions();
427 $firstregion = reset($regions);
428 $page->blocks
->add_fake_block($bc, $firstregion);
431 $bc = lesson_mediafile_block_contents($cm->id
, $lesson);
433 $page->blocks
->add_fake_block($bc, $page->blocks
->get_default_region());
436 if (!empty($timer)) {
437 $bc = lesson_clock_block_contents($cm->id
, $lesson, $timer, $page);
439 $page->blocks
->add_fake_block($bc, $page->blocks
->get_default_region());
445 * If there is a media file associated with this
446 * lesson, return a block_contents that displays it.
448 * @param int $cmid Course Module ID for this lesson
449 * @param object $lesson Full lesson record object
450 * @return block_contents
452 function lesson_mediafile_block_contents($cmid, $lesson) {
454 if (empty($lesson->mediafile
)) {
459 $options['menubar'] = 0;
460 $options['location'] = 0;
461 $options['left'] = 5;
463 $options['scrollbars'] = 1;
464 $options['resizable'] = 1;
465 $options['width'] = $lesson->mediawidth
;
466 $options['height'] = $lesson->mediaheight
;
468 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
469 $action = new popup_action('click', $link, 'lessonmediafile', $options);
470 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
472 $bc = new block_contents();
473 $bc->title
= get_string('linkedmedia', 'lesson');
474 $bc->attributes
['class'] = 'mediafile block';
475 $bc->content
= $content;
481 * If a timed lesson and not a teacher, then
482 * return a block_contents containing the clock.
484 * @param int $cmid Course Module ID for this lesson
485 * @param object $lesson Full lesson record object
486 * @param object $timer Full timer record object
487 * @return block_contents
489 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
490 // Display for timed lessons and for students only
491 $context = context_module
::instance($cmid);
492 if ($lesson->timelimit
== 0 ||
has_capability('mod/lesson:manage', $context)) {
496 $content = '<div id="lesson-timer">';
497 $content .= $lesson->time_remaining($timer->starttime
);
498 $content .= '</div>';
500 $clocksettings = array('starttime' => $timer->starttime
, 'servertime' => time(), 'testlength' => $lesson->timelimit
);
501 $page->requires
->data_for_js('clocksettings', $clocksettings, true);
502 $page->requires
->strings_for_js(array('timeisup'), 'lesson');
503 $page->requires
->js('/mod/lesson/timer.js');
504 $page->requires
->js_init_call('show_clock');
506 $bc = new block_contents();
507 $bc->title
= get_string('timeremaining', 'lesson');
508 $bc->attributes
['class'] = 'clock block';
509 $bc->content
= $content;
515 * If left menu is turned on, then this will
516 * print the menu in a block
518 * @param int $cmid Course Module ID for this lesson
519 * @param lesson $lesson Full lesson record object
522 function lesson_menu_block_contents($cmid, $lesson) {
525 if (!$lesson->displayleft
) {
529 $pages = $lesson->load_all_pages();
530 foreach ($pages as $page) {
531 if ((int)$page->prevpageid
=== 0) {
536 $currentpageid = optional_param('pageid', $pageid, PARAM_INT
);
538 if (!$pageid ||
!$pages) {
542 $content = '<a href="#maincontent" class="accesshide">' .
543 get_string('skip', 'lesson') .
544 "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
546 while ($pageid != 0) {
547 $page = $pages[$pageid];
549 // Only process branch tables with display turned on
550 if ($page->displayinmenublock
&& $page->display
) {
551 if ($page->id
== $currentpageid) {
552 $content .= '<li class="selected">'.format_string($page->title
,true)."</li>\n";
554 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title
,true)."</a></li>\n";
558 $pageid = $page->nextpageid
;
560 $content .= "</ul>\n</div>\n";
562 $bc = new block_contents();
563 $bc->title
= get_string('lessonmenu', 'lesson');
564 $bc->attributes
['class'] = 'menu block';
565 $bc->content
= $content;
571 * This is a function used to detect media types and generate html code.
573 * @global object $CFG
574 * @global object $PAGE
575 * @param object $lesson
576 * @param object $context
577 * @return string $code the html code of media
579 function lesson_get_media_html($lesson, $context) {
580 global $CFG, $PAGE, $OUTPUT;
581 require_once("$CFG->libdir/resourcelib.php");
583 // get the media file link
584 if (strpos($lesson->mediafile
, '://') !== false) {
585 $url = new moodle_url($lesson->mediafile
);
587 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
588 $url = moodle_url
::make_pluginfile_url($context->id
, 'mod_lesson', 'mediafile', $lesson->timemodified
, '/', ltrim($lesson->mediafile
, '/'));
590 $title = $lesson->mediafile
;
592 $clicktoopen = html_writer
::link($url, get_string('download'));
594 $mimetype = resourcelib_guess_url_mimetype($url);
596 $extension = resourcelib_get_extension($url->out(false));
598 $mediamanager = core_media_manager
::instance($PAGE);
599 $embedoptions = array(
600 core_media_manager
::OPTION_TRUSTED
=> true,
601 core_media_manager
::OPTION_BLOCK
=> true
604 // find the correct type and print it out
605 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
606 $code = resourcelib_embed_image($url, $title);
608 } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
609 // Media (audio/video) file.
610 $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
613 // anything else - just try object tag enlarged as much as possible
614 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
621 * Logic to happen when a/some group(s) has/have been deleted in a course.
623 * @param int $courseid The course ID.
624 * @param int $groupid The group id if it is known
627 function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
630 $params = array('courseid' => $courseid);
632 $params['groupid'] = $groupid;
633 // We just update the group that was deleted.
634 $sql = "SELECT o.id, o.lessonid, o.groupid
635 FROM {lesson_overrides} o
636 JOIN {lesson} lesson ON lesson.id = o.lessonid
637 WHERE lesson.course = :courseid
638 AND o.groupid = :groupid";
640 // No groupid, we update all orphaned group overrides for all lessons in course.
641 $sql = "SELECT o.id, o.lessonid, o.groupid
642 FROM {lesson_overrides} o
643 JOIN {lesson} lesson ON lesson.id = o.lessonid
644 LEFT JOIN {groups} grp ON grp.id = o.groupid
645 WHERE lesson.course = :courseid
646 AND o.groupid IS NOT NULL
649 $records = $DB->get_records_sql($sql, $params);
651 return; // Nothing to do.
653 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
654 $cache = cache
::make('mod_lesson', 'overrides');
655 foreach ($records as $record) {
656 $cache->delete("{$record->lessonid}_g_{$record->groupid}");
661 * Return the overview report table and data.
663 * @param lesson $lesson lesson instance
664 * @param mixed $currentgroup false if not group used, 0 for all groups, group id (int) to filter by that groups
665 * @return mixed false if there is no information otherwise html_table and stdClass with the table and data
668 function lesson_get_overview_report_table_and_data(lesson
$lesson, $currentgroup) {
669 global $DB, $CFG, $OUTPUT;
670 require_once($CFG->dirroot
. '/mod/lesson/pagetypes/branchtable.php');
672 $context = $lesson->context
;
674 // Count the number of branch and question pages in this lesson.
675 $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id
, 'qtype' => LESSON_PAGE_BRANCHTABLE
));
676 $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id
)) - $branchcount);
678 // Only load students if there attempts for this lesson.
679 $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id
));
680 $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id
));
681 $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id
));
682 if ($attempts or $branches or $timer) {
683 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
684 list($sort, $sortparams) = users_order_by_sql('u');
686 // TODO Does not support custom user profile fields (MDL-70456).
687 $userfieldsapi = \core_user\fields
::for_identity($context, false)->with_userpic();
688 $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
689 $extrafields = $userfieldsapi->get_required_fields([\core_user\fields
::PURPOSE_IDENTITY
]);
691 $params['a1lessonid'] = $lesson->id
;
692 $params['b1lessonid'] = $lesson->id
;
693 $params['c1lessonid'] = $lesson->id
;
694 $sql = "SELECT DISTINCT $ufields
697 SELECT userid, lessonid FROM {lesson_attempts} a1
698 WHERE a1.lessonid = :a1lessonid
700 SELECT userid, lessonid FROM {lesson_branch} b1
701 WHERE b1.lessonid = :b1lessonid
703 SELECT userid, lessonid FROM {lesson_timer} c1
704 WHERE c1.lessonid = :c1lessonid
705 ) a ON u.id = a.userid
706 JOIN ($esql) ue ON ue.id = a.userid
709 $students = $DB->get_recordset_sql($sql, $params);
710 if (!$students->valid()) {
712 return array(false, false);
715 return array(false, false);
718 if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id
), 'completed')) {
722 if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id
), 'starttime')) {
726 // Build an array for output.
727 $studentdata = array();
729 $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id
), 'timeseen');
730 foreach ($attempts as $attempt) {
731 // 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.
732 if (empty($studentdata[$attempt->userid
]) ||
empty($studentdata[$attempt->userid
][$attempt->retry
])) {
733 // restore/setup defaults
740 // search for the grade record for this try. if not there, the nulls defined above will be used.
741 foreach($grades as $grade) {
742 // check to see if the grade matches the correct user
743 if ($grade->userid
== $attempt->userid
) {
744 // see if n is = to the retry
745 if ($n == $attempt->retry
) {
747 $usergrade = round($grade->grade
, 2); // round it here so we only have to do it once
750 $n++
; // if not equal, then increment n
754 // search for the time record for this try. if not there, the nulls defined above will be used.
755 foreach($times as $time) {
756 // check to see if the grade matches the correct user
757 if ($time->userid
== $attempt->userid
) {
758 // see if n is = to the retry
759 if ($n == $attempt->retry
) {
761 $timeend = $time->lessontime
;
762 $timestart = $time->starttime
;
763 $eol = $time->completed
;
766 $n++
; // if not equal, then increment n
770 // build up the array.
771 // this array represents each student and all of their tries at the lesson
772 $studentdata[$attempt->userid
][$attempt->retry
] = array( "timestart" => $timestart,
773 "timeend" => $timeend,
774 "grade" => $usergrade,
776 "try" => $attempt->retry
,
777 "userid" => $attempt->userid
);
782 $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id
), 'timeseen');
783 foreach ($branches as $branch) {
784 // 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.
785 if (empty($studentdata[$branch->userid
]) ||
empty($studentdata[$branch->userid
][$branch->retry
])) {
786 // Restore/setup defaults.
792 // Search for the time record for this try. if not there, the nulls defined above will be used.
793 foreach ($times as $time) {
794 // Check to see if the grade matches the correct user.
795 if ($time->userid
== $branch->userid
) {
796 // See if n is = to the retry.
797 if ($n == $branch->retry
) {
799 $timeend = $time->lessontime
;
800 $timestart = $time->starttime
;
801 $eol = $time->completed
;
804 $n++
; // If not equal, then increment n.
808 // Build up the array.
809 // This array represents each student and all of their tries at the lesson.
810 $studentdata[$branch->userid
][$branch->retry
] = array( "timestart" => $timestart,
811 "timeend" => $timeend,
812 "grade" => $usergrade,
814 "try" => $branch->retry
,
815 "userid" => $branch->userid
);
820 // Need the same thing for timed entries that were not completed.
821 foreach ($times as $time) {
822 $endoflesson = $time->completed
;
823 // If the time start is the same with another record then we shouldn't be adding another item to this array.
824 if (isset($studentdata[$time->userid
])) {
827 foreach ($studentdata[$time->userid
] as $key => $value) {
828 if ($value['timestart'] == $time->starttime
) {
829 // Don't add this to the array.
834 $n = count($studentdata[$time->userid
]) +
1;
837 $studentdata[$time->userid
][] = array(
838 "timestart" => $time->starttime
,
839 "timeend" => $time->lessontime
,
841 "end" => $endoflesson,
843 "userid" => $time->userid
847 $studentdata[$time->userid
][] = array(
848 "timestart" => $time->starttime
,
849 "timeend" => $time->lessontime
,
851 "end" => $endoflesson,
853 "userid" => $time->userid
858 // To store all the data to be returned by the function.
859 $data = new stdClass();
861 // Determine if lesson should have a score.
862 if ($branchcount > 0 AND $questioncount == 0) {
863 // This lesson only contains content pages and is not graded.
864 $data->lessonscored
= false;
866 // This lesson is graded.
867 $data->lessonscored
= true;
869 // set all the stats variables
870 $data->numofattempts
= 0;
873 $data->highscore
= null;
874 $data->lowscore
= null;
875 $data->hightime
= null;
876 $data->lowtime
= null;
877 $data->students
= array();
879 $table = new html_table();
881 $headers = [get_string('name')];
883 foreach ($extrafields as $field) {
884 $headers[] = \core_user\fields
::get_display_name($field);
887 $caneditlesson = has_capability('mod/lesson:edit', $context);
888 $attemptsheader = get_string('attempts', 'lesson');
889 if ($caneditlesson) {
890 $selectall = get_string('selectallattempts', 'lesson');
891 $deselectall = get_string('deselectallattempts', 'lesson');
892 // Build the select/deselect all control.
893 $selectallid = 'selectall-attempts';
894 $mastercheckbox = new \core\output\
checkbox_toggleall('lesson-attempts', true, [
895 'id' => $selectallid,
896 'name' => $selectallid,
898 'label' => $selectall,
899 'selectall' => $selectall,
900 'deselectall' => $deselectall,
901 'labelclasses' => 'form-check-label'
903 $attemptsheader = $OUTPUT->render($mastercheckbox);
905 $headers [] = $attemptsheader;
907 // Set up the table object.
908 if ($data->lessonscored
) {
909 $headers [] = get_string('highscore', 'lesson');
912 $colcount = count($headers);
914 $table->head
= $headers;
917 $table->align
= array_pad($table->align
, $colcount, 'center');
918 $table->align
[$colcount - 1] = 'left';
920 if ($data->lessonscored
) {
921 $table->align
[$colcount - 2] = 'left';
924 $table->attributes
['class'] = 'table table-striped';
926 // print out the $studentdata array
927 // going through each student that has attempted the lesson, so, each student should have something to be displayed
928 foreach ($students as $student) {
929 // check to see if the student has attempts to print out
930 if (array_key_exists($student->id
, $studentdata)) {
931 // set/reset some variables
933 $dataforstudent = new stdClass
;
934 $dataforstudent->attempts
= array();
935 // gather the data for each user attempt
938 // $tries holds all the tries/retries a student has done
939 $tries = $studentdata[$student->id
];
940 $studentname = fullname($student, true);
942 foreach ($tries as $try) {
943 $dataforstudent->attempts
[] = $try;
945 // Start to build up the checkbox and link.
946 $attempturlparams = [
948 'action' => 'reportdetail',
949 'userid' => $try['userid'],
950 'try' => $try['try'],
953 if ($try["grade"] !== null) { // if null then not done yet
954 // this is what the link does when the user has completed the try
955 $timetotake = $try["timeend"] - $try["timestart"];
957 if ($try["grade"] > $bestgrade) {
958 $bestgrade = $try["grade"];
961 $attemptdata = (object)[
962 'grade' => $try["grade"],
963 'timestart' => userdate($try["timestart"]),
964 'duration' => format_time($timetotake),
966 $attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata);
970 // User finished the lesson but has no grade. (Happens when there are only content pages).
971 $timetotake = $try["timeend"] - $try["timestart"];
972 $attemptdata = (object)[
973 'timestart' => userdate($try["timestart"]),
974 'duration' => format_time($timetotake),
976 $attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata);
978 // This is what the link does/looks like when the user has not completed the attempt.
979 if ($try['timestart'] !== 0) {
980 // Teacher previews do not track time spent.
981 $attemptlinkcontents = get_string("notcompletedwithdate", "lesson", userdate($try["timestart"]));
983 $attemptlinkcontents = get_string("notcompleted", "lesson");
988 $attempturl = new moodle_url('/mod/lesson/report.php', $attempturlparams);
989 $attemptlink = html_writer
::link($attempturl, $attemptlinkcontents, ['class' => 'lesson-attempt-link']);
991 if ($caneditlesson) {
992 $attemptid = 'attempt-' . $try['userid'] . '-' . $try['try'];
993 $attemptname = 'attempts[' . $try['userid'] . '][' . $try['try'] . ']';
995 $checkbox = new \core\output\
checkbox_toggleall('lesson-attempts', false, [
997 'name' => $attemptname,
998 'label' => $attemptlink
1000 $attemptlink = $OUTPUT->render($checkbox);
1003 // build up the attempts array
1004 $attempts[] = $attemptlink;
1006 // Run these lines for the stats only if the user finnished the lesson.
1008 // User has completed the lesson.
1009 $data->numofattempts++
;
1010 $data->avetime +
= $timetotake;
1011 if ($timetotake > $data->hightime ||
$data->hightime
== null) {
1012 $data->hightime
= $timetotake;
1014 if ($timetotake < $data->lowtime ||
$data->lowtime
== null) {
1015 $data->lowtime
= $timetotake;
1017 if ($try["grade"] !== null) {
1018 // The lesson was scored.
1019 $data->avescore +
= $try["grade"];
1020 if ($try["grade"] > $data->highscore ||
$data->highscore
=== null) {
1021 $data->highscore
= $try["grade"];
1023 if ($try["grade"] < $data->lowscore ||
$data->lowscore
=== null) {
1024 $data->lowscore
= $try["grade"];
1030 // get line breaks in after each attempt
1031 $attempts = implode("<br />\n", $attempts);
1032 $row = [$studentname];
1034 foreach ($extrafields as $field) {
1035 $row[] = s($student->$field);
1040 if ($data->lessonscored
) {
1041 // Add the grade if the lesson is graded.
1042 $row[] = $bestgrade."%";
1045 $table->data
[] = $row;
1047 // Add the student data.
1048 $dataforstudent->id
= $student->id
;
1049 $dataforstudent->fullname
= $studentname;
1050 $dataforstudent->bestgrade
= $bestgrade;
1051 $data->students
[] = $dataforstudent;
1055 if ($data->numofattempts
> 0) {
1056 $data->avescore
= $data->avescore
/ $data->numofattempts
;
1059 return array($table, $data);
1063 * Return information about one user attempt (including answers)
1064 * @param lesson $lesson lesson instance
1065 * @param int $userid the user id
1066 * @param int $attempt the attempt number
1067 * @return array the user answers (array) and user data stats (object)
1070 function lesson_get_user_detailed_report_data(lesson
$lesson, $userid, $attempt) {
1073 $context = $lesson->context
;
1074 if (!empty($userid)) {
1076 $lesson->update_effective_access($userid);
1080 $lessonpages = $lesson->load_all_pages();
1081 foreach ($lessonpages as $lessonpage) {
1082 if ($lessonpage->prevpageid
== 0) {
1083 $pageid = $lessonpage->id
;
1087 // now gather the stats into an object
1088 $firstpageid = $pageid;
1089 $pagestats = array();
1090 while ($pageid != 0) { // EOL
1091 $page = $lessonpages[$pageid];
1092 $params = array ("lessonid" => $lesson->id
, "pageid" => $page->id
);
1093 if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) {
1094 // get them ready for processing
1095 $orderedanswers = array();
1096 foreach ($allanswers as $singleanswer) {
1097 // ordering them like this, will help to find the single attempt record that we want to keep.
1098 $orderedanswers[$singleanswer->userid
][$singleanswer->retry
][] = $singleanswer;
1100 // this is foreach user and for each try for that user, keep one attempt record
1101 foreach ($orderedanswers as $orderedanswer) {
1102 foreach($orderedanswer as $tries) {
1103 $page->stats($pagestats, $tries);
1107 // no one answered yet...
1109 //unset($orderedanswers); initialized above now
1110 $pageid = $page->nextpageid
;
1113 $manager = lesson_page_type_manager
::get($lesson);
1114 $qtypes = $manager->get_page_type_strings();
1116 $answerpages = array();
1118 $pageid = $firstpageid;
1119 // cycle through all the pages
1120 // foreach page, add to the $answerpages[] array all the data that is needed
1121 // from the question, the users attempt, and the statistics
1122 // grayout pages that the user did not answer and Branch, end of branch, cluster
1123 // and end of cluster pages
1124 while ($pageid != 0) { // EOL
1125 $page = $lessonpages[$pageid];
1126 $answerpage = new stdClass
;
1127 // Keep the original page object.
1128 $answerpage->page
= $page;
1131 $answerdata = new stdClass
;
1132 // Set some defaults for the answer data.
1133 $answerdata->score
= null;
1134 $answerdata->response
= null;
1135 $answerdata->responseformat
= FORMAT_PLAIN
;
1137 $answerpage->title
= format_string($page->title
);
1139 $options = new stdClass
;
1140 $options->noclean
= true;
1141 $options->overflowdiv
= true;
1142 $options->context
= $context;
1143 $answerpage->contents
= format_text($page->contents
, $page->contentsformat
, $options);
1145 $answerpage->qtype
= $qtypes[$page->qtype
].$page->option_description_string();
1146 $answerpage->grayout
= $page->grayout
;
1147 $answerpage->context
= $context;
1149 if (empty($userid)) {
1150 // there is no userid, so set these vars and display stats.
1151 $answerpage->grayout
= 0;
1153 } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id
, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id
), "timeseen")) {
1154 // get the user's answer for this page
1155 // need to find the right one
1157 foreach ($useranswers as $userattempt) {
1158 $useranswer = $userattempt;
1160 if ($lesson->maxattempts
== $i) {
1161 break; // reached maxattempts, break out
1165 // user did not answer this page, gray it out and set some nulls
1166 $answerpage->grayout
= 1;
1171 $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
1172 $pageid = $page->nextpageid
;
1175 $userstats = new stdClass
;
1176 if (!empty($userid)) {
1177 $params = array("lessonid"=>$lesson->id
, "userid"=>$userid);
1179 $alreadycompleted = true;
1181 if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
1182 $userstats->grade
= -1;
1183 $userstats->completed
= -1;
1184 $alreadycompleted = false;
1186 $userstats->grade
= current($grades);
1187 $userstats->completed
= $userstats->grade
->completed
;
1188 $userstats->grade
= round($userstats->grade
->grade
, 2);
1191 if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
1192 $userstats->timetotake
= -1;
1193 $alreadycompleted = false;
1195 $userstats->timetotake
= current($times);
1196 $userstats->timetotake
= $userstats->timetotake
->lessontime
- $userstats->timetotake
->starttime
;
1199 if ($alreadycompleted) {
1200 $userstats->gradeinfo
= lesson_grade($lesson, $attempt, $userid);
1204 return array($answerpages, $userstats);
1208 * Return user's deadline for all lessons in a course, hereby taking into account group and user overrides.
1210 * @param int $courseid the course id.
1211 * @return object An object with of all lessonsids and close unixdates in this course,
1212 * taking into account the most lenient overrides, if existing and 0 if no close date is set.
1214 function lesson_get_user_deadline($courseid) {
1217 // For teacher and manager/admins return lesson's deadline.
1218 if (has_capability('moodle/course:update', context_course
::instance($courseid))) {
1219 $sql = "SELECT lesson.id, lesson.deadline AS userdeadline
1220 FROM {lesson} lesson
1221 WHERE lesson.course = :courseid";
1223 $results = $DB->get_records_sql($sql, array('courseid' => $courseid));
1227 $sql = "SELECT a.id,
1228 COALESCE(v.userclose, v.groupclose, a.deadline, 0) AS userdeadline
1230 SELECT lesson.id as lessonid,
1231 MAX(leo.deadline) AS userclose, MAX(qgo.deadline) AS groupclose
1232 FROM {lesson} lesson
1233 LEFT JOIN {lesson_overrides} leo on lesson.id = leo.lessonid AND leo.userid = :userid
1234 LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
1235 LEFT JOIN {lesson_overrides} qgo on lesson.id = qgo.lessonid AND qgo.groupid = gm.groupid
1236 WHERE lesson.course = :courseid
1239 JOIN {lesson} a ON a.id = v.lessonid";
1241 $results = $DB->get_records_sql($sql, array('userid' => $USER->id
, 'useringroupid' => $USER->id
, 'courseid' => $courseid));
1247 * Abstract class that page type's MUST inherit from.
1249 * This is the abstract class that ALL add page type forms must extend.
1250 * You will notice that all but two of the methods this class contains are final.
1251 * Essentially the only thing that extending classes can do is extend custom_definition.
1252 * OR if it has a special requirement on creation it can extend construction_override
1255 * @copyright 2009 Sam Hemelryk
1256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1258 abstract class lesson_add_page_form_base
extends moodleform
{
1261 * This is the classic define that is used to identify this pagetype.
1262 * Will be one of LESSON_*
1268 * The simple string that describes the page type e.g. truefalse, multichoice
1271 public $qtypestring;
1274 * An array of options used in the htmleditor
1277 protected $editoroptions = array();
1280 * True if this is a standard page of false if it does something special.
1281 * Questions are standard pages, branch tables are not
1284 protected $standard = true;
1287 * Answer format supported by question type.
1289 protected $answerformat = '';
1292 * Response format supported by question type.
1294 protected $responseformat = '';
1297 * Each page type can and should override this to add any custom elements to
1298 * the basic form that they want
1300 public function custom_definition() {}
1303 * Returns answer format used by question type.
1305 public function get_answer_format() {
1306 return $this->answerformat
;
1310 * Returns response format used by question type.
1312 public function get_response_format() {
1313 return $this->responseformat
;
1317 * Used to determine if this is a standard page or a special page
1320 final public function is_standard() {
1321 return (bool)$this->standard
;
1325 * Add the required basic elements to the form.
1327 * This method adds the basic elements to the form including title and contents
1328 * and then calls custom_definition();
1330 final public function definition() {
1332 $mform = $this->_form
;
1333 $editoroptions = $this->_customdata
['editoroptions'];
1335 if ($this->qtypestring
!= 'selectaqtype') {
1336 if ($this->_customdata
['edit']) {
1337 $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring
, 'lesson'));
1339 $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring
, 'lesson'));
1343 if (!empty($this->_customdata
['returnto'])) {
1344 $mform->addElement('hidden', 'returnto', $this->_customdata
['returnto']);
1345 $mform->setType('returnto', PARAM_LOCALURL
);
1348 $mform->addElement('hidden', 'id');
1349 $mform->setType('id', PARAM_INT
);
1351 $mform->addElement('hidden', 'pageid');
1352 $mform->setType('pageid', PARAM_INT
);
1354 if ($this->standard
=== true) {
1355 $mform->addElement('hidden', 'qtype');
1356 $mform->setType('qtype', PARAM_INT
);
1358 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), ['size' => 70, 'maxlength' => 255]);
1359 $mform->addRule('title', get_string('required'), 'required', null, 'client');
1360 $mform->addRule('title', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
1361 if (!empty($CFG->formatstringstriptags
)) {
1362 $mform->setType('title', PARAM_TEXT
);
1364 $mform->setType('title', PARAM_CLEANHTML
);
1367 $this->editoroptions
= array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$this->_customdata
['maxbytes']);
1368 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions
);
1369 $mform->setType('contents_editor', PARAM_RAW
);
1370 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1373 $this->custom_definition();
1375 if ($this->_customdata
['edit'] === true) {
1376 $mform->addElement('hidden', 'edit', 1);
1377 $mform->setType('edit', PARAM_BOOL
);
1378 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1379 } else if ($this->qtype
=== 'questiontype') {
1380 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1382 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1387 * Convenience function: Adds a jumpto select element
1389 * @param string $name
1390 * @param string|null $label
1391 * @param int $selected The page to select by default
1393 final protected function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE
) {
1394 $title = get_string("jump", "lesson");
1395 if ($label === null) {
1398 if (is_int($name)) {
1399 $name = "jumpto[$name]";
1401 $this->_form
->addElement('select', $name, $label, $this->_customdata
['jumpto']);
1402 $this->_form
->setDefault($name, $selected);
1403 $this->_form
->addHelpButton($name, 'jumps', 'lesson');
1407 * Convenience function: Adds a score input element
1409 * @param string $name
1410 * @param string|null $label
1411 * @param mixed $value The default value
1413 final protected function add_score($name, $label=null, $value=null) {
1414 if ($label === null) {
1415 $label = get_string("score", "lesson");
1418 if (is_int($name)) {
1419 $name = "score[$name]";
1421 $this->_form
->addElement('text', $name, $label, array('size'=>5));
1422 $this->_form
->setType($name, PARAM_INT
);
1423 if ($value !== null) {
1424 $this->_form
->setDefault($name, $value);
1426 $this->_form
->addHelpButton($name, 'score', 'lesson');
1428 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1429 if (!$this->_customdata
['lesson']->custom
) {
1430 $this->_form
->freeze($name);
1435 * Convenience function: Adds an answer editor
1437 * @param int $count The count of the element to add
1438 * @param string $label, null means default
1439 * @param bool $required
1440 * @param string $format
1441 * @param array $help Add help text via the addHelpButton. Must be an array which contains the string identifier and
1442 * component as it's elements
1445 final protected function add_answer($count, $label = null, $required = false, $format= '', array $help = []) {
1446 if ($label === null) {
1447 $label = get_string('answer', 'lesson');
1450 if ($format == LESSON_ANSWER_HTML
) {
1451 $this->_form
->addElement('editor', 'answer_editor['.$count.']', $label,
1452 array('rows' => '4', 'columns' => '80'),
1453 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES
, 'maxbytes' => $this->_customdata
['maxbytes']));
1454 $this->_form
->setType('answer_editor['.$count.']', PARAM_RAW
);
1455 $this->_form
->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML
));
1457 $this->_form
->addElement('text', 'answer_editor['.$count.']', $label,
1458 array('size' => '50', 'maxlength' => '200'));
1459 $this->_form
->setType('answer_editor['.$count.']', PARAM_TEXT
);
1463 $this->_form
->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1467 $this->_form
->addHelpButton("answer_editor[$count]", $help['identifier'], $help['component']);
1471 * Convenience function: Adds an response editor
1473 * @param int $count The count of the element to add
1474 * @param string $label, null means default
1475 * @param bool $required
1478 final protected function add_response($count, $label = null, $required = false) {
1479 if ($label === null) {
1480 $label = get_string('response', 'lesson');
1482 $this->_form
->addElement('editor', 'response_editor['.$count.']', $label,
1483 array('rows' => '4', 'columns' => '80'),
1484 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES
, 'maxbytes' => $this->_customdata
['maxbytes']));
1485 $this->_form
->setType('response_editor['.$count.']', PARAM_RAW
);
1486 $this->_form
->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML
));
1489 $this->_form
->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1494 * A function that gets called upon init of this object by the calling script.
1496 * This can be used to process an immediate action if required. Currently it
1497 * is only used in special cases by non-standard page types.
1501 public function construction_override($pageid, lesson
$lesson) {
1509 * Class representation of a lesson
1511 * This class is used the interact with, and manage a lesson once instantiated.
1512 * If you need to fetch a lesson object you can do so by calling
1515 * lesson::load($lessonid);
1517 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1518 * $lesson = new lesson($lessonrecord);
1521 * The class itself extends lesson_base as all classes within the lesson module should
1523 * These properties are from the database
1524 * @property int $id The id of this lesson
1525 * @property int $course The ID of the course this lesson belongs to
1526 * @property string $name The name of this lesson
1527 * @property int $practice Flag to toggle this as a practice lesson
1528 * @property int $modattempts Toggle to allow the user to go back and review answers
1529 * @property int $usepassword Toggle the use of a password for entry
1530 * @property string $password The password to require users to enter
1531 * @property int $dependency ID of another lesson this lesson is dependent on
1532 * @property string $conditions Conditions of the lesson dependency
1533 * @property int $grade The maximum grade a user can achieve (%)
1534 * @property int $custom Toggle custom scoring on or off
1535 * @property int $ongoing Toggle display of an ongoing score
1536 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1537 * @property int $maxanswers The max number of answers or branches
1538 * @property int $maxattempts The maximum number of attempts a user can record
1539 * @property int $review Toggle use or wrong answer review button
1540 * @property int $nextpagedefault Override the default next page
1541 * @property int $feedback Toggles display of default feedback
1542 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1543 * @property int $maxpages Maximum number of pages this lesson can contain
1544 * @property int $retake Flag to allow users to retake a lesson
1545 * @property int $activitylink Relate this lesson to another lesson
1546 * @property string $mediafile File to pop up to or webpage to display
1547 * @property int $mediaheight Sets the height of the media file popup
1548 * @property int $mediawidth Sets the width of the media file popup
1549 * @property int $mediaclose Toggle display of a media close button
1550 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1551 * @property int $width Width of slideshow
1552 * @property int $height Height of slideshow
1553 * @property string $bgcolor Background colour of slideshow
1554 * @property int $displayleft Display a left menu
1555 * @property int $displayleftif Sets the condition on which the left menu is displayed
1556 * @property int $progressbar Flag to toggle display of a lesson progress bar
1557 * @property int $available Timestamp of when this lesson becomes available
1558 * @property int $deadline Timestamp of when this lesson is no longer available
1559 * @property int $timemodified Timestamp when lesson was last modified
1560 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1562 * These properties are calculated
1563 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1564 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1566 * @copyright 2009 Sam Hemelryk
1567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1569 class lesson
extends lesson_base
{
1572 * The id of the first page (where prevpageid = 0) gets set and retrieved by
1573 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1576 protected $firstpageid = null;
1578 * The id of the last page (where nextpageid = 0) gets set and retrieved by
1579 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1582 protected $lastpageid = null;
1584 * An array used to cache the pages associated with this lesson after the first
1585 * time they have been loaded.
1586 * A note to developers: If you are going to be working with MORE than one or
1587 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1588 * in order to save excess database queries.
1589 * @var array An array of lesson_page objects
1591 protected $pages = array();
1593 * Flag that gets set to true once all of the pages associated with the lesson
1597 protected $loadedallpages = false;
1600 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1604 protected $cm = null;
1607 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1608 * @see get_courserecord()
1611 protected $courserecord = null;
1614 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1615 * @see get_context()
1618 protected $context = null;
1621 * Constructor method
1623 * @param object $properties
1624 * @param stdClass $cm course module object
1625 * @param stdClass $course course object
1628 public function __construct($properties, $cm = null, $course = null) {
1629 parent
::__construct($properties);
1631 $this->courserecord
= $course;
1635 * Simply generates a lesson object given an array/object of properties
1636 * Overrides {@see lesson_base->create()}
1638 * @param object|array $properties
1641 public static function create($properties) {
1642 return new lesson($properties);
1646 * Generates a lesson object from the database given its id
1648 * @param int $lessonid
1651 public static function load($lessonid) {
1654 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1655 throw new \
moodle_exception('invalidcoursemodule');
1657 return new lesson($lesson);
1661 * Deletes this lesson from the database
1663 public function delete() {
1665 require_once($CFG->libdir
.'/gradelib.php');
1666 require_once($CFG->dirroot
.'/calendar/lib.php');
1668 $cm = get_coursemodule_from_instance('lesson', $this->properties
->id
, $this->properties
->course
);
1669 $context = context_module
::instance($cm->id
);
1671 $this->delete_all_overrides();
1673 grade_update('mod/lesson', $this->properties
->course
, 'mod', 'lesson', $this->properties
->id
, 0, null, array('deleted'=>1));
1675 // We must delete the module record after we delete the grade item.
1676 $DB->delete_records("lesson", array("id"=>$this->properties
->id
));
1677 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties
->id
));
1678 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties
->id
));
1679 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties
->id
));
1680 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties
->id
));
1681 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties
->id
));
1682 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties
->id
));
1683 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties
->id
))) {
1684 $coursecontext = context_course
::instance($cm->course
);
1685 foreach($events as $event) {
1686 $event->context
= $coursecontext;
1687 $event = calendar_event
::load($event);
1692 // Delete files associated with this module.
1693 $fs = get_file_storage();
1694 $fs->delete_area_files($context->id
);
1700 * Deletes a lesson override from the database and clears any corresponding calendar events
1702 * @param int $overrideid The id of the override being deleted
1703 * @return bool true on success
1705 public function delete_override($overrideid) {
1708 require_once($CFG->dirroot
. '/calendar/lib.php');
1710 $cm = get_coursemodule_from_instance('lesson', $this->properties
->id
, $this->properties
->course
);
1712 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST
);
1714 // Delete the events.
1715 $conds = array('modulename' => 'lesson',
1716 'instance' => $this->properties
->id
);
1717 if (isset($override->userid
)) {
1718 $conds['userid'] = $override->userid
;
1719 $cachekey = "{$cm->instance}_u_{$override->userid}";
1721 $conds['groupid'] = $override->groupid
;
1722 $cachekey = "{$cm->instance}_g_{$override->groupid}";
1724 $events = $DB->get_records('event', $conds);
1725 foreach ($events as $event) {
1726 $eventold = calendar_event
::load($event);
1727 $eventold->delete();
1730 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1731 cache
::make('mod_lesson', 'overrides')->delete($cachekey);
1733 // Set the common parameters for one of the events we will be triggering.
1735 'objectid' => $override->id
,
1736 'context' => context_module
::instance($cm->id
),
1738 'lessonid' => $override->lessonid
1741 // Determine which override deleted event to fire.
1742 if (!empty($override->userid
)) {
1743 $params['relateduserid'] = $override->userid
;
1744 $event = \mod_lesson\event\user_override_deleted
::create($params);
1746 $params['other']['groupid'] = $override->groupid
;
1747 $event = \mod_lesson\event\group_override_deleted
::create($params);
1750 // Trigger the override deleted event.
1751 $event->add_record_snapshot('lesson_overrides', $override);
1758 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1760 public function delete_all_overrides() {
1763 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties
->id
), 'id');
1764 foreach ($overrides as $override) {
1765 $this->delete_override($override->id
);
1770 * Checks user enrollment in the current course.
1772 * @param int $userid
1773 * @return null|stdClass user record
1775 public function is_participant($userid) {
1776 return is_enrolled($this->get_context(), $userid, 'mod/lesson:view', $this->show_only_active_users());
1780 * Check is only active users in course should be shown.
1782 * @return bool true if only active users should be shown.
1784 public function show_only_active_users() {
1785 return !has_capability('moodle/course:viewsuspendedusers', $this->get_context());
1789 * Updates the lesson properties with override information for a user.
1791 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1792 * then use that otherwise, if there are group-specific overrides, return the most
1793 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1795 * Special case: if there is more than one password that applies to the user, then
1796 * lesson->extrapasswords will contain an array of strings giving the remaining
1799 * @param int $userid The userid.
1801 public function update_effective_access($userid) {
1804 // Check for user override.
1805 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties
->id
, 'userid' => $userid));
1808 $override = new stdClass();
1809 $override->available
= null;
1810 $override->deadline
= null;
1811 $override->timelimit
= null;
1812 $override->review
= null;
1813 $override->maxattempts
= null;
1814 $override->retake
= null;
1815 $override->password
= null;
1818 // Check for group overrides.
1819 $groupings = groups_get_user_groups($this->properties
->course
, $userid);
1821 if (!empty($groupings[0])) {
1822 // Select all overrides that apply to the User's groups.
1823 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1824 $sql = "SELECT * FROM {lesson_overrides}
1825 WHERE groupid $extra AND lessonid = ?";
1826 $params[] = $this->properties
->id
;
1827 $records = $DB->get_records_sql($sql, $params);
1829 // Combine the overrides.
1830 $availables = array();
1831 $deadlines = array();
1832 $timelimits = array();
1834 $attempts = array();
1836 $passwords = array();
1838 foreach ($records as $gpoverride) {
1839 if (isset($gpoverride->available
)) {
1840 $availables[] = $gpoverride->available
;
1842 if (isset($gpoverride->deadline
)) {
1843 $deadlines[] = $gpoverride->deadline
;
1845 if (isset($gpoverride->timelimit
)) {
1846 $timelimits[] = $gpoverride->timelimit
;
1848 if (isset($gpoverride->review
)) {
1849 $reviews[] = $gpoverride->review
;
1851 if (isset($gpoverride->maxattempts
)) {
1852 $attempts[] = $gpoverride->maxattempts
;
1854 if (isset($gpoverride->retake
)) {
1855 $retakes[] = $gpoverride->retake
;
1857 if (isset($gpoverride->password
)) {
1858 $passwords[] = $gpoverride->password
;
1861 // If there is a user override for a setting, ignore the group override.
1862 if (is_null($override->available
) && count($availables)) {
1863 $override->available
= min($availables);
1865 if (is_null($override->deadline
) && count($deadlines)) {
1866 if (in_array(0, $deadlines)) {
1867 $override->deadline
= 0;
1869 $override->deadline
= max($deadlines);
1872 if (is_null($override->timelimit
) && count($timelimits)) {
1873 if (in_array(0, $timelimits)) {
1874 $override->timelimit
= 0;
1876 $override->timelimit
= max($timelimits);
1879 if (is_null($override->review
) && count($reviews)) {
1880 $override->review
= max($reviews);
1882 if (is_null($override->maxattempts
) && count($attempts)) {
1883 $override->maxattempts
= max($attempts);
1885 if (is_null($override->retake
) && count($retakes)) {
1886 $override->retake
= max($retakes);
1888 if (is_null($override->password
) && count($passwords)) {
1889 $override->password
= array_shift($passwords);
1890 if (count($passwords)) {
1891 $override->extrapasswords
= $passwords;
1897 // Merge with lesson defaults.
1898 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1899 foreach ($keys as $key) {
1900 if (isset($override->{$key})) {
1901 $this->properties
->{$key} = $override->{$key};
1905 // Special handling of lesson usepassword and password.
1906 if (isset($override->password
)) {
1907 if ($override->password
== '') {
1908 $this->properties
->usepassword
= 0;
1910 $this->properties
->usepassword
= 1;
1911 $this->properties
->password
= $override->password
;
1912 if (isset($override->extrapasswords
)) {
1913 $this->properties
->extrapasswords
= $override->extrapasswords
;
1920 * Fetches messages from the session that may have been set in previous page
1924 * // Do not call this method directly instead use
1925 * $lesson->messages;
1930 protected function get_messages() {
1933 $messages = array();
1934 if (!empty($SESSION->lesson_messages
) && is_array($SESSION->lesson_messages
) && array_key_exists($this->properties
->id
, $SESSION->lesson_messages
)) {
1935 $messages = $SESSION->lesson_messages
[$this->properties
->id
];
1936 unset($SESSION->lesson_messages
[$this->properties
->id
]);
1943 * Get all of the attempts for the current user.
1945 * @param int $retries
1946 * @param bool $correct Optional: only fetch correct attempts
1947 * @param int $pageid Optional: only fetch attempts at the given page
1948 * @param int $userid Optional: defaults to the current user if not set
1949 * @return array|false
1951 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1953 $params = array("lessonid"=>$this->properties
->id
, "userid"=>$userid, "retry"=>$retries);
1955 $params['correct'] = 1;
1957 if ($pageid !== null) {
1958 $params['pageid'] = $pageid;
1960 if ($userid === null) {
1961 $params['userid'] = $USER->id
;
1963 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1968 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1970 * @param int $lessonattempt the lesson attempt number (also known as retries)
1971 * @param int $userid the user id to retrieve the data from
1972 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter)
1973 * @param string $fields a comma separated list of fields to return
1974 * @return array of pages
1977 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1980 if ($userid === null) {
1981 $userid = $USER->id
;
1983 $conditions = array("lessonid" => $this->properties
->id
, "userid" => $userid, "retry" => $lessonattempt);
1984 return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1988 * Returns the first page for the lesson or false if there isn't one.
1990 * This method should be called via the magic method __get();
1992 * $firstpage = $lesson->firstpage;
1995 * @return lesson_page|bool Returns the lesson_page specialised object or false
1997 protected function get_firstpage() {
1998 $pages = $this->load_all_pages();
1999 if (count($pages) > 0) {
2000 foreach ($pages as $page) {
2001 if ((int)$page->prevpageid
=== 0) {
2010 * Returns the last page for the lesson or false if there isn't one.
2012 * This method should be called via the magic method __get();
2014 * $lastpage = $lesson->lastpage;
2017 * @return lesson_page|bool Returns the lesson_page specialised object or false
2019 protected function get_lastpage() {
2020 $pages = $this->load_all_pages();
2021 if (count($pages) > 0) {
2022 foreach ($pages as $page) {
2023 if ((int)$page->nextpageid
=== 0) {
2032 * Returns the id of the first page of this lesson. (prevpageid = 0)
2035 protected function get_firstpageid() {
2037 if ($this->firstpageid
== null) {
2038 if (!$this->loadedallpages
) {
2039 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties
->id
, 'prevpageid'=>0));
2040 if (!$firstpageid) {
2041 throw new \
moodle_exception('cannotfindfirstpage', 'lesson');
2043 $this->firstpageid
= $firstpageid;
2045 $firstpage = $this->get_firstpage();
2046 $this->firstpageid
= $firstpage->id
;
2049 return $this->firstpageid
;
2053 * Returns the id of the last page of this lesson. (nextpageid = 0)
2056 public function get_lastpageid() {
2058 if ($this->lastpageid
== null) {
2059 if (!$this->loadedallpages
) {
2060 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties
->id
, 'nextpageid'=>0));
2062 throw new \
moodle_exception('cannotfindlastpage', 'lesson');
2064 $this->lastpageid
= $lastpageid;
2066 $lastpageid = $this->get_lastpage();
2067 $this->lastpageid
= $lastpageid->id
;
2071 return $this->lastpageid
;
2075 * Gets the next page id to display after the one that is provided.
2076 * @param int $nextpageid
2079 public function get_next_page($nextpageid) {
2081 $allpages = $this->load_all_pages();
2082 if ($this->properties
->nextpagedefault
) {
2083 // in Flash Card mode...first get number of retakes
2084 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
2087 if ($this->properties
->nextpagedefault
== LESSON_UNSEENPAGE
) {
2088 foreach ($allpages as $nextpage) {
2089 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id
, "userid" => $USER->id
, "retry" => $nretakes))) {
2094 } elseif ($this->properties
->nextpagedefault
== LESSON_UNANSWEREDPAGE
) {
2095 foreach ($allpages as $nextpage) {
2096 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id
, 'userid' => $USER->id
, 'correct' => 1, 'retry' => $nretakes))) {
2103 if ($this->properties
->maxpages
) {
2104 // check number of pages viewed (in the lesson)
2105 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
, "retry" => $nretakes)) >= $this->properties
->maxpages
) {
2109 return $nextpage->id
;
2112 // In a normal lesson mode
2113 foreach ($allpages as $nextpage) {
2114 if ((int)$nextpage->id
=== (int)$nextpageid) {
2115 return $nextpage->id
;
2122 * Sets a message against the session for this lesson that will displayed next
2123 * time the lesson processes messages
2125 * @param string $message
2126 * @param string $class
2127 * @param string $align
2130 public function add_message($message, $class="notifyproblem", $align='center') {
2133 if (empty($SESSION->lesson_messages
) ||
!is_array($SESSION->lesson_messages
)) {
2134 $SESSION->lesson_messages
= array();
2135 $SESSION->lesson_messages
[$this->properties
->id
] = array();
2136 } else if (!array_key_exists($this->properties
->id
, $SESSION->lesson_messages
)) {
2137 $SESSION->lesson_messages
[$this->properties
->id
] = array();
2140 $SESSION->lesson_messages
[$this->properties
->id
][] = array($message, $class, $align);
2146 * Check if the lesson is accessible at the present time
2147 * @return bool True if the lesson is accessible, false otherwise
2149 public function is_accessible() {
2150 $available = $this->properties
->available
;
2151 $deadline = $this->properties
->deadline
;
2152 return (($available == 0 ||
time() >= $available) && ($deadline == 0 ||
time() < $deadline));
2156 * Starts the lesson time for the current user
2157 * @return bool Returns true
2159 public function start_timer() {
2162 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id
, $this->properties()->course
,
2165 // Trigger lesson started event.
2166 $event = \mod_lesson\event\lesson_started
::create(array(
2167 'objectid' => $this->properties()->id
,
2168 'context' => context_module
::instance($cm->id
),
2169 'courseid' => $this->properties()->course
2173 $USER->startlesson
[$this->properties
->id
] = true;
2176 $startlesson = new stdClass
;
2177 $startlesson->lessonid
= $this->properties
->id
;
2178 $startlesson->userid
= $USER->id
;
2179 $startlesson->starttime
= $timenow;
2180 $startlesson->lessontime
= $timenow;
2182 $startlesson->timemodifiedoffline
= $timenow;
2184 $DB->insert_record('lesson_timer', $startlesson);
2185 if ($this->properties
->timelimit
) {
2186 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties
->timelimit
)), 'center');
2192 * Updates the timer to the current time and returns the new timer object
2193 * @param bool $restart If set to true the timer is restarted
2194 * @param bool $continue If set to true AND $restart=true then the timer
2195 * will continue from a previous attempt
2196 * @return stdClass The new timer
2198 public function update_timer($restart=false, $continue=false, $endreached =false) {
2201 $cm = get_coursemodule_from_instance('lesson', $this->properties
->id
, $this->properties
->course
);
2204 // get time information for this user
2205 if (!$timer = $this->get_user_timers($USER->id
, 'starttime DESC', '*', 0, 1)) {
2206 $this->start_timer();
2207 $timer = $this->get_user_timers($USER->id
, 'starttime DESC', '*', 0, 1);
2209 $timer = current($timer); // This will get the latest start time record.
2213 // continue a previous test, need to update the clock (think this option is disabled atm)
2214 $timer->starttime
= time() - ($timer->lessontime
- $timer->starttime
);
2216 // Trigger lesson resumed event.
2217 $event = \mod_lesson\event\lesson_resumed
::create(array(
2218 'objectid' => $this->properties
->id
,
2219 'context' => context_module
::instance($cm->id
),
2220 'courseid' => $this->properties
->course
2225 // starting over, so reset the clock
2226 $timer->starttime
= time();
2228 // Trigger lesson restarted event.
2229 $event = \mod_lesson\event\lesson_restarted
::create(array(
2230 'objectid' => $this->properties
->id
,
2231 'context' => context_module
::instance($cm->id
),
2232 'courseid' => $this->properties
->course
2240 $timer->lessontime
= $timenow;
2242 $timer->timemodifiedoffline
= $timenow;
2244 $timer->completed
= $endreached;
2245 $DB->update_record('lesson_timer', $timer);
2247 // Update completion state.
2248 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id
, $this->properties()->course
,
2250 $course = get_course($cm->course
);
2251 $completion = new completion_info($course);
2252 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent
> 0) {
2253 $completion->update_state($cm, COMPLETION_COMPLETE
);
2259 * Updates the timer to the current time then stops it by unsetting the user var
2260 * @return bool Returns true
2262 public function stop_timer() {
2264 unset($USER->startlesson
[$this->properties
->id
]);
2266 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id
, $this->properties()->course
,
2269 // Trigger lesson ended event.
2270 $event = \mod_lesson\event\lesson_ended
::create(array(
2271 'objectid' => $this->properties()->id
,
2272 'context' => context_module
::instance($cm->id
),
2273 'courseid' => $this->properties()->course
2277 return $this->update_timer(false, false, true);
2281 * Checks to see if the lesson has pages
2283 public function has_pages() {
2285 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties
->id
));
2286 return ($pagecount>0);
2290 * Returns the link for the related activity
2293 public function link_for_activitylink() {
2295 $module = $DB->get_record('course_modules', array('id' => $this->properties
->activitylink
));
2297 $modname = $DB->get_field('modules', 'name', array('id' => $module->module
));
2299 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance
));
2300 if ($instancename) {
2301 return html_writer
::link(
2302 new moodle_url('/mod/'.$modname.'/view.php', [
2303 'id' => $this->properties
->activitylink
,
2308 format_string($instancename, true, ['context' => $this->get_context()]),
2310 ['class' => 'centerpadded lessonbutton standardbutton pe-3'],
2319 * Loads the requested page.
2321 * This function will return the requested page id as either a specialised
2322 * lesson_page object OR as a generic lesson_page.
2323 * If the page has been loaded previously it will be returned from the pages
2324 * array, otherwise it will be loaded from the database first
2326 * @param int $pageid
2327 * @return lesson_page A lesson_page object or an object that extends it
2329 public function load_page($pageid) {
2330 if (!array_key_exists($pageid, $this->pages
)) {
2331 $manager = lesson_page_type_manager
::get($this);
2332 $this->pages
[$pageid] = $manager->load_page($pageid, $this);
2334 return $this->pages
[$pageid];
2338 * Loads ALL of the pages for this lesson
2340 * @return array An array containing all pages from this lesson
2342 public function load_all_pages() {
2343 if (!$this->loadedallpages
) {
2344 $manager = lesson_page_type_manager
::get($this);
2345 $this->pages
= $manager->load_all_pages($this);
2346 $this->loadedallpages
= true;
2348 return $this->pages
;
2352 * Duplicate the lesson page.
2354 * @param int $pageid Page ID of the page to duplicate.
2357 public function duplicate_page($pageid) {
2359 $cm = get_coursemodule_from_instance('lesson', $this->properties
->id
, $this->properties
->course
);
2360 $context = context_module
::instance($cm->id
);
2362 $page = $this->load_page($pageid);
2363 $properties = $page->properties();
2364 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2365 if (!$properties->qoption
) {
2366 unset($properties->qoption
);
2368 if (!$properties->layout
) {
2369 unset($properties->layout
);
2371 if (!$properties->display
) {
2372 unset($properties->display
);
2375 $properties->pageid
= $pageid;
2376 // Add text and format into the format required to create a new page.
2377 $properties->contents_editor
= array(
2378 'text' => $properties->contents
,
2379 'format' => $properties->contentsformat
2381 $answers = $page->get_answers();
2382 // Answers need to be added to $properties.
2384 $answerids = array();
2385 foreach ($answers as $answer) {
2386 // Needs to be rearranged to work with the create function.
2387 $properties->answer_editor
[$i] = array(
2388 'text' => $answer->answer
,
2389 'format' => $answer->answerformat
2392 $properties->response_editor
[$i] = array(
2393 'text' => $answer->response
,
2394 'format' => $answer->responseformat
2396 $answerids[] = $answer->id
;
2398 $properties->jumpto
[$i] = $answer->jumpto
;
2399 $properties->score
[$i] = $answer->score
;
2403 // Create the duplicate page.
2404 $newlessonpage = lesson_page
::create($properties, $this, $context, $PAGE->course
->maxbytes
);
2405 $newanswers = $newlessonpage->get_answers();
2406 // Copy over the file areas as well.
2407 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id
, $context->id
);
2409 foreach ($newanswers as $answer) {
2410 if (isset($answer->answer
) && strpos($answer->answer
, '@@PLUGINFILE@@') !== false) {
2411 $this->copy_page_files('page_answers', $answerids[$j], $answer->id
, $context->id
);
2413 if (isset($answer->response
) && !is_array($answer->response
) && strpos($answer->response
, '@@PLUGINFILE@@') !== false) {
2414 $this->copy_page_files('page_responses', $answerids[$j], $answer->id
, $context->id
);
2421 * Copy the files from one page to another.
2423 * @param string $filearea Area that the files are stored.
2424 * @param int $itemid Item ID.
2425 * @param int $newitemid The item ID for the new page.
2426 * @param int $contextid Context ID for this page.
2429 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2430 $fs = get_file_storage();
2431 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2432 foreach ($files as $file) {
2433 $fieldupdates = array('itemid' => $newitemid);
2434 $fs->create_file_from_storedfile($fieldupdates, $file);
2439 * Determines if a jumpto value is correct or not.
2441 * returns true if jumpto page is (logically) after the pageid page or
2442 * if the jumpto value is a special value. Returns false in all other cases.
2444 * @param int $pageid Id of the page from which you are jumping from.
2445 * @param int $jumpto The jumpto number.
2446 * @return boolean True or false after a series of tests.
2448 public function jumpto_is_correct($pageid, $jumpto) {
2451 // first test the special values
2455 } elseif ($jumpto == LESSON_NEXTPAGE
) {
2457 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE
) {
2459 } elseif ($jumpto == LESSON_RANDOMPAGE
) {
2461 } elseif ($jumpto == LESSON_CLUSTERJUMP
) {
2463 } elseif ($jumpto == LESSON_EOL
) {
2467 $pages = $this->load_all_pages();
2468 $apageid = $pages[$pageid]->nextpageid
;
2469 while ($apageid != 0) {
2470 if ($jumpto == $apageid) {
2473 $apageid = $pages[$apageid]->nextpageid
;
2479 * Returns the time a user has remaining on this lesson
2480 * @param int $starttime Starttime timestamp
2483 public function time_remaining($starttime) {
2484 $timeleft = $starttime +
$this->properties
->timelimit
- time();
2485 $hours = floor($timeleft/3600);
2486 $timeleft = $timeleft - ($hours * 3600);
2487 $minutes = floor($timeleft/60);
2488 $secs = $timeleft - ($minutes * 60);
2490 if ($minutes < 10) {
2491 $minutes = "0$minutes";
2498 $output[] = $minutes;
2500 $output = implode(':', $output);
2505 * Interprets LESSON_CLUSTERJUMP jumpto value.
2507 * This will select a page randomly
2508 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
2509 * and the page selected will be a page that has not been viewed already
2510 * and if any pages are within a branch table or end of branch then only 1 page within
2511 * the branch table or end of branch will be randomly selected (sub clustering).
2513 * @param int $pageid Id of the current page from which we are jumping from.
2514 * @param int $userid Id of the user.
2515 * @return int The id of the next page.
2517 public function cluster_jump($pageid, $userid=null) {
2520 if ($userid===null) {
2521 $userid = $USER->id
;
2523 // get the number of retakes
2524 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties
->id
, "userid"=>$userid))) {
2527 // get all the lesson_attempts aka what the user has seen
2528 $seenpages = array();
2529 if ($attempts = $this->get_attempts($retakes)) {
2530 foreach ($attempts as $attempt) {
2531 $seenpages[$attempt->pageid
] = $attempt->pageid
;
2536 // get the lesson pages
2537 $lessonpages = $this->load_all_pages();
2538 // find the start of the cluster
2539 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2540 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_CLUSTER
) {
2543 $pageid = $lessonpages[$pageid]->prevpageid
;
2546 $clusterpages = array();
2547 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER
));
2549 foreach ($clusterpages as $key=>$cluster) {
2550 // Remove the page if it is in a branch table or is an endofbranch.
2551 if ($this->is_sub_page_of_type($cluster->id
,
2552 array(LESSON_PAGE_BRANCHTABLE
), array(LESSON_PAGE_ENDOFBRANCH
, LESSON_PAGE_CLUSTER
))
2553 ||
$cluster->qtype
== LESSON_PAGE_ENDOFBRANCH
) {
2554 unset($clusterpages[$key]);
2555 } else if ($cluster->qtype
== LESSON_PAGE_BRANCHTABLE
) {
2556 // If branchtable, check to see if any pages inside have been viewed.
2557 $branchpages = $this->get_sub_pages_of($cluster->id
, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
2559 foreach ($branchpages as $branchpage) {
2560 if (array_key_exists($branchpage->id
, $seenpages)) { // Check if any of the pages have been viewed.
2564 if ($flag && count($branchpages) > 0) {
2565 // Add branch table.
2566 $unseen[] = $cluster;
2568 } elseif ($cluster->is_unseen($seenpages)) {
2569 $unseen[] = $cluster;
2573 if (count($unseen) > 0) {
2574 // it does not contain elements, then use exitjump, otherwise find out next page/branch
2575 $nextpage = $unseen[rand(0, count($unseen)-1)];
2576 if ($nextpage->qtype
== LESSON_PAGE_BRANCHTABLE
) {
2577 // if branch table, then pick a random page inside of it
2578 $branchpages = $this->get_sub_pages_of($nextpage->id
, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
2579 return $branchpages[rand(0, count($branchpages)-1)]->id
;
2580 } else { // otherwise, return the page's id
2581 return $nextpage->id
;
2584 // seen all there is to see, leave the cluster
2585 if (end($clusterpages)->nextpageid
== 0) {
2588 $clusterendid = $pageid;
2589 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2590 if ($lessonpages[$clusterendid]->qtype
== LESSON_PAGE_ENDOFCLUSTER
) {
2593 $clusterendid = $lessonpages[$clusterendid]->nextpageid
;
2595 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties
->id
));
2596 if ($exitjump == LESSON_NEXTPAGE
) {
2597 $exitjump = $lessonpages[$clusterendid]->nextpageid
;
2599 if ($exitjump == 0) {
2601 } else if (in_array($exitjump, array(LESSON_EOL
, LESSON_PREVIOUSPAGE
))) {
2604 if (!array_key_exists($exitjump, $lessonpages)) {
2606 foreach ($lessonpages as $page) {
2607 if ($page->id
=== $clusterendid) {
2609 } else if ($page->qtype
== LESSON_PAGE_ENDOFCLUSTER
) {
2610 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id
, "lessonid" => $this->properties
->id
));
2611 if ($exitjump == LESSON_NEXTPAGE
) {
2612 $exitjump = $lessonpages[$page->id
]->nextpageid
;
2618 if (!array_key_exists($exitjump, $lessonpages)) {
2621 // Check to see that the return type is not a cluster.
2622 if ($lessonpages[$exitjump]->qtype
== LESSON_PAGE_CLUSTER
) {
2623 // If the exitjump is a cluster then go through this function again and try to find an unseen question.
2624 $exitjump = $this->cluster_jump($exitjump, $userid);
2633 * Finds all pages that appear to be a subtype of the provided pageid until
2634 * an end point specified within $ends is encountered or no more pages exist
2636 * @param int $pageid
2637 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2639 * @return array An array of specialised lesson_page objects
2641 public function get_sub_pages_of($pageid, array $ends) {
2642 $lessonpages = $this->load_all_pages();
2643 $pageid = $lessonpages[$pageid]->nextpageid
; // move to the first page after the branch table
2647 if ($pageid == 0 ||
in_array($lessonpages[$pageid]->qtype
, $ends)) {
2650 $pages[] = $lessonpages[$pageid];
2651 $pageid = $lessonpages[$pageid]->nextpageid
;
2658 * Checks to see if the specified page[id] is a subpage of a type specified in
2659 * the $types array, until either there are no more pages of we find a type
2660 * corresponding to that of a type specified in $ends
2662 * @param int $pageid The id of the page to check
2663 * @param array $types An array of types that would signify this page was a subpage
2664 * @param array $ends An array of types that mean this is not a subpage
2667 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2668 $pages = $this->load_all_pages();
2669 $pageid = $pages[$pageid]->prevpageid
; // move up one
2671 array_unshift($ends, 0);
2672 // go up the pages till branch table
2674 if ($pageid==0 ||
in_array($pages[$pageid]->qtype
, $ends)) {
2676 } else if (in_array($pages[$pageid]->qtype
, $types)) {
2679 $pageid = $pages[$pageid]->prevpageid
;
2684 * Move a page resorting all other pages.
2686 * @param int $pageid
2690 public function resort_pages($pageid, $after) {
2693 $cm = get_coursemodule_from_instance('lesson', $this->properties
->id
, $this->properties
->course
);
2694 $context = context_module
::instance($cm->id
);
2696 $pages = $this->load_all_pages();
2698 if (!array_key_exists($pageid, $pages) ||
($after!=0 && !array_key_exists($after, $pages))) {
2699 throw new \
moodle_exception('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2702 $pagetomove = clone($pages[$pageid]);
2703 unset($pages[$pageid]);
2707 $pageids['p0'] = $pageid;
2709 foreach ($pages as $page) {
2710 $pageids[] = $page->id
;
2711 if ($page->id
== $after) {
2712 $pageids[] = $pageid;
2716 $pageidsref = $pageids;
2719 $next = next($pageidsref);
2720 foreach ($pageids as $pid) {
2721 if ($pid === $pageid) {
2722 $page = $pagetomove;
2724 $page = $pages[$pid];
2726 if ($page->prevpageid
!= $prev ||
$page->nextpageid
!= $next) {
2727 $page->move($next, $prev);
2729 if ($pid === $pageid) {
2730 // We will trigger an event.
2731 $pageupdated = array('next' => $next, 'prev' => $prev);
2736 $next = next($pageidsref);
2742 // Trigger an event: page moved.
2743 if (!empty($pageupdated)) {
2744 $eventparams = array(
2745 'context' => $context,
2746 'objectid' => $pageid,
2748 'pagetype' => $page->get_typestring(),
2749 'prevpageid' => $pageupdated['prev'],
2750 'nextpageid' => $pageupdated['next']
2753 $event = \mod_lesson\event\page_moved
::create($eventparams);
2760 * Return the lesson context object.
2762 * @return stdClass context
2765 public function get_context() {
2766 if ($this->context
== null) {
2767 $this->context
= context_module
::instance($this->get_cm()->id
);
2769 return $this->context
;
2773 * Set the lesson course module object.
2775 * @param stdClass $cm course module objct
2778 private function set_cm($cm) {
2783 * Return the lesson course module object.
2785 * @return stdClass course module
2788 public function get_cm() {
2789 if ($this->cm
== null) {
2790 $this->cm
= get_coursemodule_from_instance('lesson', $this->properties
->id
);
2796 * Set the lesson course object.
2798 * @param stdClass $course course objct
2801 private function set_courserecord($course) {
2802 $this->courserecord
= $course;
2806 * Return the lesson course object.
2808 * @return stdClass course
2811 public function get_courserecord() {
2814 if ($this->courserecord
== null) {
2815 $this->courserecord
= $DB->get_record('course', array('id' => $this->properties
->course
));
2817 return $this->courserecord
;
2821 * Check if the user can manage the lesson activity.
2823 * @return bool true if the user can manage the lesson
2826 public function can_manage() {
2827 return has_capability('mod/lesson:manage', $this->get_context());
2831 * Check if time restriction is applied.
2833 * @return mixed false if there aren't restrictions or an object with the restriction information
2836 public function get_time_restriction_status() {
2837 if ($this->can_manage()) {
2841 if (!$this->is_accessible()) {
2842 if ($this->properties
->deadline
!= 0 && time() > $this->properties
->deadline
) {
2843 $status = ['reason' => 'lessonclosed', 'time' => $this->properties
->deadline
];
2845 $status = ['reason' => 'lessonopen', 'time' => $this->properties
->available
];
2847 return (object) $status;
2853 * Check if password restriction is applied.
2855 * @param string $userpassword the user password to check (if the restriction is set)
2856 * @return mixed false if there aren't restrictions or an object with the restriction information
2859 public function get_password_restriction_status($userpassword) {
2861 if ($this->can_manage()) {
2865 if ($this->properties
->usepassword
&& empty($USER->lessonloggedin
[$this->id
])) {
2866 $correctpass = false;
2868 $userpassword = trim((string) $userpassword);
2869 if ($userpassword !== '' &&
2870 ($this->properties
->password
=== md5($userpassword) ||
$this->properties
->password
=== $userpassword)) {
2871 // With or without md5 for backward compatibility (MDL-11090).
2872 $correctpass = true;
2873 $USER->lessonloggedin
[$this->id
] = true;
2874 } else if (isset($this->properties
->extrapasswords
)) {
2875 // Group overrides may have additional passwords.
2876 foreach ($this->properties
->extrapasswords
as $password) {
2877 if ($password === md5($userpassword) ||
$password === $userpassword) {
2878 $correctpass = true;
2879 $USER->lessonloggedin
[$this->id
] = true;
2883 return !$correctpass;
2889 * Check if dependencies restrictions are applied.
2891 * @return mixed false if there aren't restrictions or an object with the restriction information
2894 public function get_dependencies_restriction_status() {
2896 if ($this->can_manage()) {
2900 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties
->dependency
))) {
2901 // Lesson exists, so we can proceed.
2902 $conditions = unserialize_object($this->properties
->conditions
);
2903 // Assume false for all.
2905 // Check for the timespent condition.
2906 if (!empty($conditions->timespent
)) {
2908 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id
, "lessonid" => $dependentlesson->id
))) {
2909 // Go through all the times and test to see if any of them satisfy the condition.
2910 foreach ($attempttimes as $attempttime) {
2911 $duration = $attempttime->lessontime
- $attempttime->starttime
;
2912 if ($conditions->timespent
< $duration / 60) {
2918 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent
);
2921 // Check for the gradebetterthan condition.
2922 if (!empty($conditions->gradebetterthan
)) {
2923 $gradebetterthan = false;
2924 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id
, "lessonid" => $dependentlesson->id
))) {
2925 // Go through all the grades and test to see if any of them satisfy the condition.
2926 foreach ($studentgrades as $studentgrade) {
2927 if ($studentgrade->grade
>= $conditions->gradebetterthan
) {
2928 $gradebetterthan = true;
2932 if (!$gradebetterthan) {
2933 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan
);
2936 // Check for the completed condition.
2937 if (!empty($conditions->completed
)) {
2938 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id
, 'lessonid' => $dependentlesson->id
))) {
2939 $errors[] = get_string('completederror', 'lesson');
2942 if (!empty($errors)) {
2943 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2950 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2952 * @return bool true if is in review mode
2955 public function is_in_review_mode() {
2958 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
2959 if ($userhasgrade && !$this->properties
->retake
) {
2966 * Return the last page the current user saw.
2968 * @param int $retriescount the number of retries for the lesson (the last retry number).
2969 * @return mixed false if the user didn't see the lesson or the last page id
2971 public function get_last_page_seen($retriescount) {
2974 $lastpageseen = false;
2975 $allattempts = $this->get_attempts($retriescount);
2976 if (!empty($allattempts)) {
2977 $attempt = end($allattempts);
2978 $attemptpage = $this->load_page($attempt->pageid
);
2979 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid
));
2980 // Convert the jumpto to a proper page id.
2982 // Check if a question has been incorrectly answered AND no more attempts at it are left.
2983 $nattempts = $this->get_attempts($attempt->retry
, false, $attempt->pageid
, $USER->id
);
2984 if (count($nattempts) >= $this->properties
->maxattempts
) {
2985 $lastpageseen = $this->get_next_page($attemptpage->nextpageid
);
2987 $lastpageseen = $attempt->pageid
;
2989 } else if ($jumpto == LESSON_NEXTPAGE
) {
2990 $lastpageseen = $this->get_next_page($attemptpage->nextpageid
);
2991 } else if ($jumpto == LESSON_CLUSTERJUMP
) {
2992 $lastpageseen = $this->cluster_jump($attempt->pageid
);
2994 $lastpageseen = $jumpto;
2998 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id
, 'timeseen DESC')) {
2999 // In here, user has viewed a branch table.
3000 $lastbranchtable = current($branchtables);
3001 if (count($allattempts) > 0) {
3002 if ($lastbranchtable->timeseen
> $attempt->timeseen
) {
3003 // This branch table was viewed more recently than the question page.
3004 if (!empty($lastbranchtable->nextpageid
)) {
3005 $lastpageseen = $lastbranchtable->nextpageid
;
3007 // Next page ID did not exist prior to MDL-34006.
3008 $lastpageseen = $lastbranchtable->pageid
;
3012 // Has not answered any questions but has viewed a branch table.
3013 if (!empty($lastbranchtable->nextpageid
)) {
3014 $lastpageseen = $lastbranchtable->nextpageid
;
3016 // Next page ID did not exist prior to MDL-34006.
3017 $lastpageseen = $lastbranchtable->pageid
;
3021 return $lastpageseen;
3025 * Return the number of retries in a lesson for a given user.
3027 * @param int $userid the user id
3028 * @return int the retries count
3031 public function count_user_retries($userid) {
3034 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties
->id
, "userid" => $userid));
3038 * Check if a user left a timed session.
3040 * @param int $retriescount the number of retries for the lesson (the last retry number).
3041 * @return true if the user left the timed session
3044 public function left_during_timed_session($retriescount) {
3047 $conditions = array('lessonid' => $this->properties
->id
, 'userid' => $USER->id
, 'retry' => $retriescount);
3048 return $DB->count_records('lesson_attempts', $conditions) > 0 ||
$DB->count_records('lesson_branch', $conditions) > 0;
3052 * Trigger module viewed event and set the module viewed for completion.
3056 public function set_module_viewed() {
3058 require_once($CFG->libdir
. '/completionlib.php');
3060 // Trigger module viewed event.
3061 $event = \mod_lesson\event\course_module_viewed
::create(array(
3062 'objectid' => $this->properties
->id
,
3063 'context' => $this->get_context()
3065 $event->add_record_snapshot('course_modules', $this->get_cm());
3066 $event->add_record_snapshot('course', $this->get_courserecord());
3070 $completion = new completion_info($this->get_courserecord());
3071 $completion->set_module_viewed($this->get_cm());
3075 * Return the timers in the current lesson for the given user.
3077 * @param int $userid the user id
3078 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
3079 * @param string $fields a comma separated list of fields to return
3080 * @param int $limitfrom return a subset of records, starting at this point (optional).
3081 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
3082 * @return array list of timers for the given user in the lesson
3085 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
3088 if ($userid === null) {
3089 $userid = $USER->id
;
3092 $params = array('lessonid' => $this->properties
->id
, 'userid' => $userid);
3093 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
3097 * Check if the user is out of time in a timed lesson.
3099 * @param stdClass $timer timer object
3100 * @return bool True if the user is on time, false is the user ran out of time
3103 public function check_time($timer) {
3104 if ($this->properties
->timelimit
) {
3105 $timeleft = $timer->starttime +
$this->properties
->timelimit
- time();
3106 if ($timeleft <= 0) {
3108 $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
3110 } else if ($timeleft < 60) {
3111 // One minute warning.
3112 $this->add_message(get_string('studentoneminwarning', 'lesson'));
3119 * Add different informative messages to the given page.
3121 * @param lesson_page $page page object
3122 * @param reviewmode $bool whether we are in review mode or not
3125 public function add_messages_on_page_view(lesson_page
$page, $reviewmode) {
3128 if (!$this->can_manage()) {
3129 if ($page->qtype
== LESSON_PAGE_BRANCHTABLE
&& $this->properties
->minquestions
) {
3130 // Tell student how many questions they have seen, how many are required and their grade.
3131 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
3132 $gradeinfo = lesson_grade($this, $ntries);
3133 if ($gradeinfo->attempts
) {
3134 if ($gradeinfo->nquestions
< $this->properties
->minquestions
) {
3136 $a->nquestions
= $gradeinfo->nquestions
;
3137 $a->minquestions
= $this->properties
->minquestions
;
3138 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3141 if (!$reviewmode && $this->properties
->ongoing
) {
3142 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned
), 'notify');
3143 if ($this->properties
->grade
!= GRADE_TYPE_NONE
) {
3145 $a->grade
= format_float($gradeinfo->grade
* $this->properties
->grade
/ 100, 1);
3146 $a->total
= $this->properties
->grade
;
3147 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3153 if ($this->properties
->timelimit
) {
3154 $this->add_message(get_string('teachertimerwarning', 'lesson'));
3156 if (lesson_display_teacher_warning($this)) {
3157 // This is the warning msg for teachers to inform them that cluster
3158 // and unseen does not work while logged in as a teacher.
3159 $warningvars = new stdClass();
3160 $warningvars->cluster
= get_string('clusterjump', 'lesson');
3161 $warningvars->unseen
= get_string('unseenpageinbranch', 'lesson');
3162 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3168 * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3170 * @return str the ongoing score message
3173 public function get_ongoing_score_message() {
3176 $context = $this->get_context();
3178 if (has_capability('mod/lesson:manage', $context)) {
3179 return get_string('teacherongoingwarning', 'lesson');
3181 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
3182 if (isset($USER->modattempts
[$this->properties
->id
])) {
3185 $gradeinfo = lesson_grade($this, $ntries);
3187 if ($this->properties
->custom
) {
3188 $a->score
= $gradeinfo->earned
;
3189 $a->currenthigh
= $gradeinfo->total
;
3190 return get_string("ongoingcustom", "lesson", $a);
3192 $a->correct
= $gradeinfo->earned
;
3193 $a->viewed
= $gradeinfo->attempts
;
3194 return get_string("ongoingnormal", "lesson", $a);
3200 * Calculate the progress of the current user in the lesson.
3202 * @return int the progress (scale 0-100)
3205 public function calculate_progress() {
3208 // Check if the user is reviewing the attempt.
3209 if (isset($USER->modattempts
[$this->properties
->id
])) {
3213 // All of the lesson pages.
3214 $pages = $this->load_all_pages();
3215 foreach ($pages as $page) {
3216 if ($page->prevpageid
== 0) {
3217 $pageid = $page->id
; // Find the first page id.
3222 // Current attempt number.
3223 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
))) {
3224 $ntries = 0; // May not be necessary.
3227 $viewedpageids = array();
3228 if ($attempts = $this->get_attempts($ntries, false)) {
3229 foreach ($attempts as $attempt) {
3230 $viewedpageids[$attempt->pageid
] = $attempt;
3234 $viewedbranches = array();
3235 // Collect all of the branch tables viewed.
3236 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id
, 'timeseen ASC', 'id, pageid')) {
3237 foreach ($branches as $branch) {
3238 $viewedbranches[$branch->pageid
] = $branch;
3240 $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3243 // Filter out the following pages:
3246 // - Pages found inside of Clusters
3247 // Do not filter out Cluster Page(s) because we count a cluster as one.
3248 // By keeping the cluster page, we get our 1.
3249 $validpages = array();
3250 while ($pageid != 0) {
3251 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3254 // Progress calculation as a percent.
3255 $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3256 return (int) $progress;
3260 * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3262 * @param int $pageid the given page id
3263 * @param mod_lesson_renderer $lessonoutput the lesson output rendered
3264 * @param bool $reviewmode whether we are in review mode or not
3265 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
3266 * @return array the page object and contents
3267 * @throws moodle_exception
3270 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
3273 $page = $this->load_page($pageid);
3274 // Check if the page is of a special type and if so take any nessecary action.
3275 $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3277 // Avoid redirections returning the jump to special page id.
3278 if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3279 return array($newpageid, null, null);
3282 if (is_numeric($newpageid)) {
3283 $page = $this->load_page($newpageid);
3286 // Add different informative messages to the given page.
3287 $this->add_messages_on_page_view($page, $reviewmode);
3289 if (is_array($page->answers
) && count($page->answers
) > 0) {
3290 // This is for modattempts option. Find the users previous answer to this page,
3291 // and then display it below in answer processing.
3292 if (isset($USER->modattempts
[$this->properties
->id
])) {
3293 $retries = $this->count_user_retries($USER->id
);
3294 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id
)) {
3295 throw new moodle_exception('cannotfindpreattempt', 'lesson');
3297 $attempt = end($attempts);
3298 $USER->modattempts
[$this->properties
->id
] = $attempt;
3302 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3304 require_once($CFG->dirroot
. '/mod/lesson/view_form.php');
3305 $data = new stdClass
;
3306 $data->id
= $this->get_cm()->id
;
3307 $data->pageid
= $page->id
;
3308 $data->newpageid
= $this->get_next_page($page->nextpageid
);
3310 $customdata = array(
3311 'title' => $page->title
,
3312 'contents' => $page->get_contents()
3314 $mform = new lesson_page_without_answers($CFG->wwwroot
.'/mod/lesson/continue.php', $customdata);
3315 $mform->set_data($data);
3318 $lessoncontent = ob_get_contents();
3322 return array($page->id
, $page, $lessoncontent);
3326 * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
3328 * @param lesson_page $page lesson page
3329 * @param int $newpageid the new page id
3330 * @return int the real page to jump to (or end of lesson)
3333 public function calculate_new_page_on_jump(lesson_page
$page, $newpageid) {
3336 $canmanage = $this->can_manage();
3338 if (isset($USER->modattempts
[$this->properties
->id
])) {
3339 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
3340 if ($USER->modattempts
[$this->properties
->id
]->pageid
== $page->id
&& $page->nextpageid
== 0) {
3341 // Remember, this session variable holds the pageid of the last page that the user saw.
3342 $newpageid = LESSON_EOL
;
3344 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
3345 $nretakes--; // Make sure we are looking at the right try.
3346 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
, "retry" => $nretakes), "timeseen", "id, pageid");
3349 // Make sure that the newpageid always defaults to something valid.
3350 $newpageid = LESSON_EOL
;
3351 foreach ($attempts as $attempt) {
3352 if ($found && $temppageid != $attempt->pageid
) {
3353 // Now try to find the next page, make sure next few attempts do no belong to current page.
3354 $newpageid = $attempt->pageid
;
3357 if ($attempt->pageid
== $page->id
) {
3358 $found = true; // If found current page.
3359 $temppageid = $attempt->pageid
;
3363 } else if ($newpageid != LESSON_CLUSTERJUMP
&& $page->id
!= 0 && $newpageid > 0) {
3364 // Going to check to see if the page that the user is going to view next, is a cluster page.
3365 // If so, dont display, go into the cluster.
3366 // The $newpageid > 0 is used to filter out all of the negative code jumps.
3367 $newpage = $this->load_page($newpageid);
3368 if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3369 $newpageid = $overridenewpageid;
3371 } else if ($newpageid == LESSON_UNSEENBRANCHPAGE
) {
3373 if ($page->nextpageid
== 0) {
3374 $newpageid = LESSON_EOL
;
3376 $newpageid = $page->nextpageid
;
3379 $newpageid = lesson_unseen_question_jump($this, $USER->id
, $page->id
);
3381 } else if ($newpageid == LESSON_PREVIOUSPAGE
) {
3382 $newpageid = $page->prevpageid
;
3383 } else if ($newpageid == LESSON_RANDOMPAGE
) {
3384 $newpageid = lesson_random_question_jump($this, $page->id
);
3385 } else if ($newpageid == LESSON_CLUSTERJUMP
) {
3387 if ($page->nextpageid
== 0) { // If teacher, go to next page.
3388 $newpageid = LESSON_EOL
;
3390 $newpageid = $page->nextpageid
;
3393 $newpageid = $this->cluster_jump($page->id
);
3395 } else if ($newpageid == 0) {
3396 $newpageid = $page->id
;
3397 } else if ($newpageid == LESSON_NEXTPAGE
) {
3398 $newpageid = $this->get_next_page($page->nextpageid
);
3405 * Process page responses.
3407 * @param lesson_page $page page object
3410 public function process_page_responses(lesson_page
$page) {
3411 $context = $this->get_context();
3413 // Check the page has answers [MDL-25632].
3414 if (count($page->answers
) > 0) {
3415 $result = $page->record_attempt($context);
3417 // The page has no answers so we will just progress to the next page in the
3418 // sequence (as set by newpageid).
3419 $result = new stdClass
;
3420 $result->newpageid
= optional_param('newpageid', $page->nextpageid
, PARAM_INT
);
3421 $result->nodefaultresponse
= true;
3422 $result->inmediatejump
= false;
3425 if ($result->inmediatejump
) {
3429 $result->newpageid
= $this->calculate_new_page_on_jump($page, $result->newpageid
);
3435 * Add different informative messages to the given page.
3437 * @param lesson_page $page page object
3438 * @param stdClass $result the page processing result object
3439 * @param bool $reviewmode whether we are in review mode or not
3442 public function add_messages_on_page_process(lesson_page
$page, $result, $reviewmode) {
3444 if ($this->can_manage()) {
3445 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3446 if (lesson_display_teacher_warning($this)) {
3447 $warningvars = new stdClass();
3448 $warningvars->cluster
= get_string("clusterjump", "lesson");
3449 $warningvars->unseen
= get_string("unseenpageinbranch", "lesson");
3450 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3452 // Inform teacher that s/he will not see the timer.
3453 if ($this->properties
->timelimit
) {
3454 $this->add_message(get_string("teachertimerwarning", "lesson"));
3457 // Report attempts remaining.
3458 if ($result->attemptsremaining
!= 0 && $this->properties
->review
&& !$reviewmode) {
3459 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining
));
3464 * Process and return all the information for the end of lesson page.
3466 * @param string $outoftime used to check to see if the student ran out of time
3467 * @return stdclass an object with all the page data ready for rendering
3470 public function process_eol_page($outoftime) {
3473 $course = $this->get_courserecord();
3474 $cm = $this->get_cm();
3475 $canmanage = $this->can_manage();
3477 // Init all the possible fields and values.
3478 $data = (object) array(
3479 'gradelesson' => true,
3480 'notenoughtimespent' => false,
3481 'numberofpagesviewed' => false,
3482 'youshouldview' => false,
3483 'numberofcorrectanswers' => false,
3484 'displayscorewithessays' => false,
3485 'displayscorewithoutessays' => false,
3486 'yourcurrentgradeisoutof' => false,
3487 'yourcurrentgradeis' => false,
3488 'eolstudentoutoftimenoanswers' => false,
3489 'welldone' => false,
3490 'progressbar' => false,
3491 'displayofgrade' => false,
3492 'reviewlesson' => false,
3493 'modattemptsnoteacher' => false,
3494 'activitylink' => false,
3495 'progresscompleted' => false,
3498 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
3499 if (isset($USER->modattempts
[$this->properties
->id
])) {
3500 $ntries--; // Need to look at the old attempts :).
3503 $gradeinfo = lesson_grade($this, $ntries);
3504 $data->gradeinfo
= $gradeinfo;
3505 if ($this->properties
->custom
&& !$canmanage) {
3506 // Before we calculate the custom score make sure they answered the minimum
3507 // number of questions. We only need to do this for custom scoring as we can
3508 // not get the miniumum score the user should achieve. If we are not using
3509 // custom scoring (so all questions are valued as 1) then we simply check if
3510 // they answered more than the minimum questions, if not, we mark it out of the
3511 // number specified in the minimum questions setting - which is done in lesson_grade().
3512 // Get the number of answers given.
3513 if ($gradeinfo->nquestions
< $this->properties
->minquestions
) {
3514 $data->gradelesson
= false;
3516 $a->nquestions
= $gradeinfo->nquestions
;
3517 $a->minquestions
= $this->properties
->minquestions
;
3518 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3523 if ($data->gradelesson
) {
3524 // Store this now before any modifications to pages viewed.
3525 $progresscompleted = $this->calculate_progress();
3527 // Update the clock / get time information for this user.
3528 $this->stop_timer();
3530 // Update completion state.
3531 $completion = new completion_info($course);
3532 if ($completion->is_enabled($cm) && $this->properties
->completionendreached
) {
3533 $completion->update_state($cm, COMPLETION_COMPLETE
);
3536 if ($this->properties
->completiontimespent
> 0) {
3537 $duration = $DB->get_field_sql(
3538 "SELECT SUM(lessontime - starttime)
3540 WHERE lessonid = :lessonid
3541 AND userid = :userid",
3542 array('userid' => $USER->id
, 'lessonid' => $this->properties
->id
));
3547 // If student has not spend enough time in the lesson, display a message.
3548 if ($duration < $this->properties
->completiontimespent
) {
3550 $a->timespentraw
= $duration;
3551 $a->timespent
= format_time($duration);
3552 $a->timerequiredraw
= $this->properties
->completiontimespent
;
3553 $a->timerequired
= format_time($this->properties
->completiontimespent
);
3554 $data->notenoughtimespent
= $a;
3558 if ($gradeinfo->attempts
) {
3559 if (!$this->properties
->custom
) {
3560 $data->numberofpagesviewed
= $gradeinfo->nquestions
;
3561 if ($this->properties
->minquestions
) {
3562 if ($gradeinfo->nquestions
< $this->properties
->minquestions
) {
3563 $data->youshouldview
= $this->properties
->minquestions
;
3566 $data->numberofcorrectanswers
= $gradeinfo->earned
;
3569 $a->score
= $gradeinfo->earned
;
3570 $a->grade
= $gradeinfo->total
;
3571 if ($gradeinfo->nmanual
) {
3572 $a->tempmaxgrade
= $gradeinfo->total
- $gradeinfo->manualpoints
;
3573 $a->essayquestions
= $gradeinfo->nmanual
;
3574 $data->displayscorewithessays
= $a;
3576 $data->displayscorewithoutessays
= $a;
3579 $grade = new stdClass();
3580 $grade->lessonid
= $this->properties
->id
;
3581 $grade->userid
= $USER->id
;
3582 $grade->grade
= $gradeinfo->grade
;
3583 $grade->completed
= time();
3584 if (isset($USER->modattempts
[$this->properties
->id
])) { // If reviewing, make sure update old grade record.
3585 if (!$grades = $DB->get_records("lesson_grades",
3586 array("lessonid" => $this->properties
->id
, "userid" => $USER->id
), "completed DESC", '*', 0, 1)) {
3587 throw new moodle_exception('cannotfindgrade', 'lesson');
3589 $oldgrade = array_shift($grades);
3590 $grade->id
= $oldgrade->id
;
3591 $DB->update_record("lesson_grades", $grade);
3593 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3596 // Update central gradebook.
3597 lesson_update_grades($this, $USER->id
);
3599 // Print grade (grade type Point).
3600 if ($this->properties
->grade
> 0) {
3602 $a->grade
= format_float($gradeinfo->grade
* $this->properties
->grade
/ 100, 1);
3603 $a->total
= $this->properties
->grade
;
3604 $data->yourcurrentgradeisoutof
= $a;
3607 // Print grade (grade type Scale).
3608 if ($this->properties
->grade
< 0) {
3609 // Grade type is Scale.
3610 $grades = grade_get_grades($course->id
, 'mod', 'lesson', $cm->instance
, $USER->id
);
3611 $grade = reset($grades->items
[0]->grades
);
3612 $data->yourcurrentgradeis
= $grade->str_grade
;
3615 if ($this->properties
->timelimit
) {
3616 if ($outoftime == 'normal') {
3617 $grade = new stdClass();
3618 $grade->lessonid
= $this->properties
->id
;
3619 $grade->userid
= $USER->id
;
3621 $grade->completed
= time();
3622 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3623 $data->eolstudentoutoftimenoanswers
= true;
3625 // Update central gradebook.
3626 lesson_update_grades($this, $USER->id
);
3629 $data->welldone
= true;
3633 $data->progresscompleted
= $progresscompleted;
3636 // Display for teacher.
3637 if ($this->properties
->grade
!= GRADE_TYPE_NONE
) {
3638 $data->displayofgrade
= true;
3642 if ($this->properties
->modattempts
&& !$canmanage) {
3643 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3644 // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3645 // to pass to view again. This is slick cause it wont call the empty($pageid) code
3646 // $ntries is decremented above.
3647 if (!$attempts = $this->get_attempts($ntries)) {
3648 $attempts = array();
3649 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id
));
3651 $firstattempt = current($attempts);
3652 $pageid = $firstattempt->pageid
;
3653 // If the student wishes to review, need to know the last question page that the student answered.
3654 // This will help to make sure that the student can leave the lesson via pushing the continue button.
3655 $lastattempt = end($attempts);
3656 $USER->modattempts
[$this->properties
->id
] = $lastattempt->pageid
;
3658 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id
, 'pageid' => $pageid));
3660 $data->reviewlesson
= $url->out(false);
3661 } else if ($this->properties
->modattempts
&& $canmanage) {
3662 $data->modattemptsnoteacher
= true;
3665 if ($this->properties
->activitylink
) {
3666 $data->activitylink
= $this->link_for_activitylink();
3672 * Returns the last "legal" attempt from the list of student attempts.
3674 * @param array $attempts The list of student attempts.
3675 * @return stdClass The updated fom data.
3677 public function get_last_attempt(array $attempts): stdClass
{
3678 // If there are more tries than the max that is allowed, grab the last "legal" attempt.
3679 if (!empty($this->maxattempts
) && (count($attempts) > $this->maxattempts
)) {
3680 $lastattempt = $attempts[$this->maxattempts
- 1];
3682 // Grab the last attempt since there's no limit to the max attempts or the user has made fewer attempts than the max.
3683 $lastattempt = end($attempts);
3685 return $lastattempt;
3691 * Abstract class to provide a core functions to the all lesson classes
3693 * This class should be abstracted by ALL classes with the lesson module to ensure
3694 * that all classes within this module can be interacted with in the same way.
3696 * This class provides the user with a basic properties array that can be fetched
3697 * or set via magic methods, or alternatively by defining methods get_blah() or
3698 * set_blah() within the extending object.
3700 * @copyright 2009 Sam Hemelryk
3701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3703 abstract class lesson_base
{
3706 * An object containing properties
3709 protected $properties;
3713 * @param stdClass $properties
3715 public function __construct($properties) {
3716 $this->properties
= (object)$properties;
3720 * Magic property method
3722 * Attempts to call a set_$key method if one exists otherwise falls back
3723 * to simply set the property
3725 * @param string $key
3726 * @param mixed $value
3728 public function __set($key, $value) {
3729 if (method_exists($this, 'set_'.$key)) {
3730 $this->{'set_'.$key}($value);
3732 $this->properties
->{$key} = $value;
3738 * Attempts to call a get_$key method to return the property and ralls over
3739 * to return the raw property
3744 public function __get($key) {
3745 if (method_exists($this, 'get_'.$key)) {
3746 return $this->{'get_'.$key}();
3748 return $this->properties
->{$key};
3752 * Stupid PHP needs an isset magic method if you use the get magic method and
3753 * still want empty calls to work.... blah ~!
3755 * @param string $key
3758 public function __isset($key) {
3759 if (method_exists($this, 'get_'.$key)) {
3760 $val = $this->{'get_'.$key}();
3761 return !empty($val);
3763 return !empty($this->properties
->{$key});
3766 //NOTE: E_STRICT does not allow to change function signature!
3769 * If implemented should create a new instance, save it in the DB and return it
3771 //public static function create() {}
3773 * If implemented should load an instance from the DB and return it
3775 //public static function load() {}
3777 * Fetches all of the properties of the object
3780 public function properties() {
3781 return $this->properties
;
3787 * Abstract class representation of a page associated with a lesson.
3789 * This class should MUST be extended by all specialised page types defined in
3790 * mod/lesson/pagetypes/.
3791 * There are a handful of abstract methods that need to be defined as well as
3792 * severl methods that can optionally be defined in order to make the page type
3793 * operate in the desired way
3795 * Database properties
3796 * @property int $id The id of this lesson page
3797 * @property int $lessonid The id of the lesson this page belongs to
3798 * @property int $prevpageid The id of the page before this one
3799 * @property int $nextpageid The id of the next page in the page sequence
3800 * @property int $qtype Identifies the page type of this page
3801 * @property int $qoption Used to record page type specific options
3802 * @property int $layout Used to record page specific layout selections
3803 * @property int $display Used to record page specific display selections
3804 * @property int $timecreated Timestamp for when the page was created
3805 * @property int $timemodified Timestamp for when the page was last modified
3806 * @property string $title The title of this page
3807 * @property string $contents The rich content shown to describe the page
3808 * @property int $contentsformat The format of the contents field
3810 * Calculated properties
3811 * @property-read array $answers An array of answers for this page
3812 * @property-read bool $displayinmenublock Toggles display in the left menu block
3813 * @property-read array $jumps An array containing all the jumps this page uses
3814 * @property-read lesson $lesson The lesson this page belongs to
3815 * @property-read int $type The type of the page [question | structure]
3816 * @property-read typeid The unique identifier for the page type
3817 * @property-read typestring The string that describes this page type
3820 * @copyright 2009 Sam Hemelryk
3821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3823 abstract class lesson_page
extends lesson_base
{
3826 * A reference to the lesson this page belongs to
3829 protected $lesson = null;
3831 * Contains the answers to this lesson_page once loaded
3834 protected $answers = null;
3836 * This sets the type of the page, can be one of the constants defined below
3839 protected $type = 0;
3842 * Constants used to identify the type of the page
3844 const TYPE_QUESTION
= 0;
3845 const TYPE_STRUCTURE
= 1;
3848 * Constant used as a delimiter when parsing multianswer questions
3850 const MULTIANSWER_DELIMITER
= '@^#|';
3853 * This method should return the integer used to identify the page type within
3854 * the database and throughout code. This maps back to the defines used in 1.x
3858 abstract protected function get_typeid();
3860 * This method should return the string that describes the pagetype
3864 abstract protected function get_typestring();
3867 * This method gets called to display the page to the user taking the lesson
3869 * @param object $renderer
3870 * @param object $attempt
3873 abstract public function display($renderer, $attempt);
3876 * Creates a new lesson_page within the database and returns the correct pagetype
3877 * object to use to interact with the new lesson
3881 * @param object $properties
3882 * @param lesson $lesson
3883 * @return lesson_page Specialised object that extends lesson_page
3885 final public static function create($properties, lesson
$lesson, $context, $maxbytes) {
3887 $newpage = new stdClass
;
3888 $newpage->title
= $properties->title
;
3889 $newpage->contents
= $properties->contents_editor
['text'];
3890 $newpage->contentsformat
= $properties->contents_editor
['format'];
3891 $newpage->lessonid
= $lesson->id
;
3892 $newpage->timecreated
= time();
3893 $newpage->qtype
= $properties->qtype
;
3894 $newpage->qoption
= (isset($properties->qoption
))?
1:0;
3895 $newpage->layout
= (isset($properties->layout
))?
1:0;
3896 $newpage->display
= (isset($properties->display
))?
1:0;
3897 $newpage->prevpageid
= 0; // this is a first page
3898 $newpage->nextpageid
= 0; // this is the only page
3900 if ($properties->pageid
) {
3901 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid
), 'id, nextpageid');
3903 throw new \
moodle_exception('cannotfindpages', 'lesson');
3905 $newpage->prevpageid
= $prevpage->id
;
3906 $newpage->nextpageid
= $prevpage->nextpageid
;
3908 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id
, 'prevpageid'=>0), 'id');
3910 // This is the first page, there are existing pages put this at the start
3911 $newpage->nextpageid
= $nextpage->id
;
3915 $newpage->id
= $DB->insert_record("lesson_pages", $newpage);
3917 $editor = new stdClass
;
3918 $editor->id
= $newpage->id
;
3919 $editor->contents_editor
= $properties->contents_editor
;
3920 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id
);
3921 $DB->update_record("lesson_pages", $editor);
3923 if ($newpage->prevpageid
> 0) {
3924 $DB->set_field("lesson_pages", "nextpageid", $newpage->id
, array("id" => $newpage->prevpageid
));
3926 if ($newpage->nextpageid
> 0) {
3927 $DB->set_field("lesson_pages", "prevpageid", $newpage->id
, array("id" => $newpage->nextpageid
));
3930 $page = lesson_page
::load($newpage, $lesson);
3931 $page->create_answers($properties);
3933 // Trigger an event: page created.
3934 $eventparams = array(
3935 'context' => $context,
3936 'objectid' => $newpage->id
,
3938 'pagetype' => $page->get_typestring()
3941 $event = \mod_lesson\event\page_created
::create($eventparams);
3942 $snapshot = clone($newpage);
3943 $snapshot->timemodified
= 0;
3944 $event->add_record_snapshot('lesson_pages', $snapshot);
3947 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title
, true), 'notifysuccess');
3953 * This method loads a page object from the database and returns it as a
3954 * specialised object that extends lesson_page
3959 * @param lesson $lesson
3960 * @return lesson_page Specialised lesson_page object
3962 final public static function load($id, lesson
$lesson) {
3965 if (is_object($id) && !empty($id->qtype
)) {
3968 $page = $DB->get_record("lesson_pages", array("id" => $id));
3970 throw new \
moodle_exception('cannotfindpages', 'lesson');
3973 $manager = lesson_page_type_manager
::get($lesson);
3975 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype
);
3976 if (!class_exists($class)) {
3977 $class = 'lesson_page';
3980 return new $class($page, $lesson);
3984 * Deletes a lesson_page from the database as well as any associated records.
3988 final public function delete() {
3991 $cm = get_coursemodule_from_instance('lesson', $this->lesson
->id
, $this->lesson
->course
);
3992 $context = context_module
::instance($cm->id
);
3994 // Delete files associated with attempts.
3995 $fs = get_file_storage();
3996 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties
->id
))) {
3997 foreach ($attempts as $attempt) {
3998 $fs->delete_area_files($context->id
, 'mod_lesson', 'essay_responses', $attempt->id
);
3999 $fs->delete_area_files($context->id
, 'mod_lesson', 'essay_answers', $attempt->id
);
4003 // Then delete all the associated records...
4004 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties
->id
));
4006 $DB->delete_records("lesson_branch", array("pageid" => $this->properties
->id
));
4008 // Delete files related to answers and responses.
4009 if ($answers = $DB->get_records("lesson_answers", array("pageid" => $this->properties
->id
))) {
4010 foreach ($answers as $answer) {
4011 $fs->delete_area_files($context->id
, 'mod_lesson', 'page_answers', $answer->id
);
4012 $fs->delete_area_files($context->id
, 'mod_lesson', 'page_responses', $answer->id
);
4016 // ...now delete the answers...
4017 $DB->delete_records("lesson_answers", array("pageid" => $this->properties
->id
));
4018 // ..and the page itself
4019 $DB->delete_records("lesson_pages", array("id" => $this->properties
->id
));
4021 // Trigger an event: page deleted.
4022 $eventparams = array(
4023 'context' => $context,
4024 'objectid' => $this->properties
->id
,
4026 'pagetype' => $this->get_typestring()
4029 $event = \mod_lesson\event\page_deleted
::create($eventparams);
4030 $event->add_record_snapshot('lesson_pages', $this->properties
);
4033 // Delete files associated with this page.
4034 $fs->delete_area_files($context->id
, 'mod_lesson', 'page_contents', $this->properties
->id
);
4036 // repair the hole in the linkage
4037 if (!$this->properties
->prevpageid
&& !$this->properties
->nextpageid
) {
4038 //This is the only page, no repair needed
4039 } elseif (!$this->properties
->prevpageid
) {
4040 // this is the first page...
4041 $page = $this->lesson
->load_page($this->properties
->nextpageid
);
4042 $page->move(null, 0);
4043 } elseif (!$this->properties
->nextpageid
) {
4044 // this is the last page...
4045 $page = $this->lesson
->load_page($this->properties
->prevpageid
);
4048 // page is in the middle...
4049 $prevpage = $this->lesson
->load_page($this->properties
->prevpageid
);
4050 $nextpage = $this->lesson
->load_page($this->properties
->nextpageid
);
4052 $prevpage->move($nextpage->id
);
4053 $nextpage->move(null, $prevpage->id
);
4059 * Moves a page by updating its nextpageid and prevpageid values within
4063 * @param int $nextpageid
4064 * @param int $prevpageid
4066 final public function move($nextpageid=null, $prevpageid=null) {
4068 if ($nextpageid === null) {
4069 $nextpageid = $this->properties
->nextpageid
;
4071 if ($prevpageid === null) {
4072 $prevpageid = $this->properties
->prevpageid
;
4074 $obj = new stdClass
;
4075 $obj->id
= $this->properties
->id
;
4076 $obj->prevpageid
= $prevpageid;
4077 $obj->nextpageid
= $nextpageid;
4078 $DB->update_record('lesson_pages', $obj);
4082 * Returns the answers that are associated with this page in the database
4087 final public function get_answers() {
4089 if ($this->answers
=== null) {
4090 $this->answers
= array();
4091 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties
->id
, 'lessonid'=>$this->lesson
->id
), 'id');
4093 // It is possible that a lesson upgraded from Moodle 1.9 still
4094 // contains questions without any answers [MDL-25632].
4095 // debugging(get_string('cannotfindanswer', 'lesson'));
4098 foreach ($answers as $answer) {
4099 $this->answers
[count($this->answers
)] = new lesson_page_answer($answer);
4102 return $this->answers
;
4106 * Returns the lesson this page is associated with
4110 final protected function get_lesson() {
4111 return $this->lesson
;
4115 * Returns the type of page this is. Not to be confused with page type
4119 final protected function get_type() {
4124 * Records an attempt at this page
4127 * @global moodle_database $DB
4128 * @param stdClass $context
4129 * @return stdClass Returns the result of the attempt
4131 final public function record_attempt($context) {
4132 global $DB, $USER, $OUTPUT, $PAGE;
4135 * This should be overridden by each page type to actually check the response
4136 * against what ever custom criteria they have defined
4138 $result = $this->check_answer();
4140 // Processes inmediate jumps.
4141 if ($result->inmediatejump
) {
4145 $result->attemptsremaining
= 0;
4146 $result->maxattemptsreached
= false;
4148 if ($result->noanswer
) {
4149 $result->newpageid
= $this->properties
->id
; // display same page again
4150 $result->feedback
= get_string('noanswer', 'lesson');
4152 if (!has_capability('mod/lesson:manage', $context)) {
4153 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson
->id
, "userid"=>$USER->id
));
4155 // Get the number of attempts that have been made on this question for this student and retake,
4156 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson
->id
,
4157 'userid' => $USER->id
, 'pageid' => $this->properties
->id
, 'retry' => $nretakes));
4159 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
4160 if (!empty($this->lesson
->maxattempts
) && $nattempts >= $this->lesson
->maxattempts
) {
4161 $result->maxattemptsreached
= true;
4162 $result->feedback
= get_string('maximumnumberofattemptsreached', 'lesson');
4163 $result->newpageid
= $this->lesson
->get_next_page($this->properties
->nextpageid
);
4167 // record student's attempt
4168 $attempt = new stdClass
;
4169 $attempt->lessonid
= $this->lesson
->id
;
4170 $attempt->pageid
= $this->properties
->id
;
4171 $attempt->userid
= $USER->id
;
4172 $attempt->answerid
= $result->answerid
;
4173 $attempt->retry
= $nretakes;
4174 $attempt->correct
= $result->correctanswer
;
4175 if($result->userresponse
!== null) {
4176 $attempt->useranswer
= $result->userresponse
;
4179 $attempt->timeseen
= time();
4180 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
4181 $userisreviewing = false;
4182 if (isset($USER->modattempts
[$this->lesson
->id
])) {
4183 $attempt->retry
= $nretakes - 1; // they are going through on review, $nretakes will be too high
4184 $userisreviewing = true;
4187 // Only insert a record if we are not reviewing the lesson.
4188 if (!$userisreviewing) {
4189 if ($this->lesson
->retake ||
(!$this->lesson
->retake
&& $nretakes == 0)) {
4190 $attempt->id
= $DB->insert_record("lesson_attempts", $attempt);
4192 list($updatedattempt, $updatedresult) = $this->on_after_write_attempt($attempt, $result);
4193 if ($updatedattempt) {
4194 $attempt = $updatedattempt;
4195 $result = $updatedresult;
4196 $DB->update_record("lesson_attempts", $attempt);
4199 // Trigger an event: question answered.
4200 $eventparams = array(
4201 'context' => context_module
::instance($PAGE->cm
->id
),
4202 'objectid' => $this->properties
->id
,
4204 'pagetype' => $this->get_typestring()
4207 $event = \mod_lesson\event\question_answered
::create($eventparams);
4208 $event->add_record_snapshot('lesson_attempts', $attempt);
4211 // Increase the number of attempts made.
4215 // When reviewing the lesson, the existing attemptid is also needed for the filearea options.
4217 'lessonid' => $attempt->lessonid
,
4218 'pageid' => $attempt->pageid
,
4219 'userid' => $attempt->userid
,
4220 'answerid' => $attempt->answerid
,
4221 'retry' => $attempt->retry
4223 $attempt->id
= $DB->get_field('lesson_attempts', 'id', $params);
4225 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
4226 // displaying of message(s) is at the end of page for more ergonomic display
4227 // If we are showing the number of remaining attempts, we need to show it regardless of what the next
4229 if (!$result->correctanswer
) {
4230 // Retrieve the number of attempts left counter for displaying at bottom of feedback page.
4231 if ($result->newpageid
== 0 && !empty($this->lesson
->maxattempts
) && $nattempts >= $this->lesson
->maxattempts
) {
4232 if ($this->lesson
->maxattempts
> 1) { // don't bother with message if only one attempt
4233 $result->maxattemptsreached
= true;
4235 $result->newpageid
= LESSON_NEXTPAGE
;
4236 } else if ($this->lesson
->maxattempts
> 1) { // don't bother with message if only one attempt
4237 $result->attemptsremaining
= $this->lesson
->maxattempts
- $nattempts;
4238 if ($result->attemptsremaining
== 0) {
4239 $result->maxattemptsreached
= true;
4245 // Determine default feedback if necessary
4246 if (empty($result->response
)) {
4247 if (!$this->lesson
->feedback
&& !$result->noanswer
&& !($this->lesson
->review
& !$result->correctanswer
&& !$result->isessayquestion
)) {
4248 // These conditions have been met:
4249 // 1. The lesson manager has not supplied feedback to the student
4250 // 2. Not displaying default feedback
4251 // 3. The user did provide an answer
4252 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
4254 $result->nodefaultresponse
= true; // This will cause a redirect below
4255 } else if ($result->isessayquestion
) {
4256 $result->response
= get_string('defaultessayresponse', 'lesson');
4257 } else if ($result->correctanswer
) {
4258 $result->response
= get_string('thatsthecorrectanswer', 'lesson');
4260 $result->response
= get_string('thatsthewronganswer', 'lesson');
4264 if ($result->response
) {
4265 if ($this->lesson
->review
&& !$result->correctanswer
&& !$result->isessayquestion
) {
4266 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson
->id
, "userid"=>$USER->id
));
4267 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id
, "retry"=>$nretakes, "pageid"=>$this->properties
->id
));
4268 if ($qattempts == 1) {
4269 $result->feedback
= $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
4271 if (!$result->maxattemptsreached
) {
4272 $result->feedback
= $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
4274 $result->feedback
= $OUTPUT->box(get_string("finalwrong", "lesson"), 'feedback');
4278 $result->feedback
= '';
4280 $class = 'response';
4281 if ($result->correctanswer
) {
4282 $class .= ' correct'; // CSS over-ride this if they exist (!important).
4283 } else if (!$result->isessayquestion
) {
4284 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
4290 'overflowdiv' => true,
4291 'context' => $context,
4293 $answeroptions = (object) array_merge($options, [
4294 'attemptid' => $attempt->id ??
null,
4297 $result->feedback
.= $OUTPUT->box(format_text($this->get_contents(), $this->properties
->contentsformat
, $options),
4298 'generalbox boxaligncenter py-3');
4299 $result->feedback
.= '<div class="correctanswer generalbox"><em>'
4300 . get_string("youranswer", "lesson").'</em> : <div class="studentanswer mt-2 mb-2">';
4302 // Create a table containing the answers and responses.
4303 $table = new html_table();
4304 // Multianswer allowed.
4305 if ($this->properties
->qoption
) {
4306 $studentanswerarray = explode(self
::MULTIANSWER_DELIMITER
, $result->studentanswer
);
4307 $responsearr = explode(self
::MULTIANSWER_DELIMITER
, $result->response
);
4308 $studentanswerresponse = array_combine($studentanswerarray, $responsearr);
4310 foreach ($studentanswerresponse as $answer => $response) {
4311 // Add a table row containing the answer.
4312 $studentanswer = $this->format_answer($answer, $context, $result->studentanswerformat
, $answeroptions);
4313 $table->data
[] = array($studentanswer);
4314 // If the response exists, add a table row containing the response. If not, add en empty row.
4315 if (!empty(trim($response))) {
4316 $studentresponse = isset($result->responseformat
) ?
4317 $this->format_response($response, $context, $result->responseformat
, $options) : $response;
4318 $studentresponsecontent = html_writer
::div('<em>' . get_string("response", "lesson") .
4319 '</em>: <br/>' . $studentresponse, $class);
4320 $table->data
[] = array($studentresponsecontent);
4322 $table->data
[] = array('');
4326 // Add a table row containing the answer.
4327 $studentanswer = $this->format_answer($result->studentanswer
, $context, $result->studentanswerformat
, $answeroptions);
4328 $table->data
[] = array($studentanswer);
4329 // If the response exists, add a table row containing the response. If not, add en empty row.
4330 if (!empty(trim($result->response
))) {
4331 $studentresponse = isset($result->responseformat
) ?
4332 $this->format_response($result->response
, $context, $result->responseformat
,
4333 $result->answerid
, $options) : $result->response
;
4334 $studentresponsecontent = html_writer
::div('<em>' . get_string("response", "lesson") .
4335 '</em>: <br/>' . $studentresponse, $class);
4336 $table->data
[] = array($studentresponsecontent);
4338 $table->data
[] = array('');
4342 $result->feedback
.= html_writer
::table($table).'</div></div>';
4349 * Formats the answer. Override for custom formatting.
4351 * @param string $answer
4352 * @param context $context
4353 * @param int $answerformat
4354 * @return string Returns formatted string
4356 public function format_answer($answer, $context, $answerformat, $options = []) {
4357 if (is_object($options)) {
4358 $options = (array) $options;
4361 if (empty($options['context'])) {
4362 $options['context'] = $context;
4365 if (empty($options['para'])) {
4366 $options['para'] = true;
4369 // The attemptid is used by some plugins but is not a valid argument to format_text.
4370 unset($options['attemptid']);
4372 return format_text($answer, $answerformat, $options);
4376 * Formats the response
4378 * @param string $response
4379 * @param context $context
4380 * @param int $responseformat
4381 * @param int $answerid
4382 * @param stdClass $options
4383 * @return string Returns formatted string
4385 private function format_response($response, $context, $responseformat, $answerid, $options) {
4387 $convertstudentresponse = file_rewrite_pluginfile_urls($response, 'pluginfile.php',
4388 $context->id
, 'mod_lesson', 'page_responses', $answerid);
4390 return format_text($convertstudentresponse, $responseformat, $options);
4394 * Returns the string for a jump name
4397 * @param int $jumpto Jump code or page ID
4400 final protected function get_jump_name($jumpto) {
4402 static $jumpnames = array();
4404 if (!array_key_exists($jumpto, $jumpnames)) {
4405 if ($jumpto == LESSON_THISPAGE
) {
4406 $jumptitle = get_string('thispage', 'lesson');
4407 } elseif ($jumpto == LESSON_NEXTPAGE
) {
4408 $jumptitle = get_string('nextpage', 'lesson');
4409 } elseif ($jumpto == LESSON_EOL
) {
4410 $jumptitle = get_string('endoflesson', 'lesson');
4411 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE
) {
4412 $jumptitle = get_string('unseenpageinbranch', 'lesson');
4413 } elseif ($jumpto == LESSON_PREVIOUSPAGE
) {
4414 $jumptitle = get_string('previouspage', 'lesson');
4415 } elseif ($jumpto == LESSON_RANDOMPAGE
) {
4416 $jumptitle = get_string('randompageinbranch', 'lesson');
4417 } elseif ($jumpto == LESSON_RANDOMBRANCH
) {
4418 $jumptitle = get_string('randombranch', 'lesson');
4419 } elseif ($jumpto == LESSON_CLUSTERJUMP
) {
4420 $jumptitle = get_string('clusterjump', 'lesson');
4422 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
4423 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
4426 $jumpnames[$jumpto] = format_string($jumptitle,true);
4429 return $jumpnames[$jumpto];
4433 * Constructor method
4434 * @param object $properties
4435 * @param lesson $lesson
4437 public function __construct($properties, lesson
$lesson) {
4438 parent
::__construct($properties);
4439 $this->lesson
= $lesson;
4443 * Returns the score for the attempt
4444 * This may be overridden by page types that require manual grading
4445 * @param array $answers
4446 * @param object $attempt
4449 public function earned_score($answers, $attempt) {
4450 return $answers[$attempt->answerid
]->score
;
4454 * This is a callback method that can be override and gets called when ever a page
4457 * @param bool $canmanage True if the user has the manage cap
4458 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
4461 public function callback_on_view($canmanage, $redirect = true) {
4466 * save editor answers files and update answer record
4468 * @param object $context
4469 * @param int $maxbytes
4470 * @param object $answer
4471 * @param object $answereditor
4472 * @param object $responseeditor
4474 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
4476 if (isset($answereditor['itemid'])) {
4477 $answer->answer
= file_save_draft_area_files($answereditor['itemid'],
4478 $context->id
, 'mod_lesson', 'page_answers', $answer->id
,
4479 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES
, 'maxbytes' => $maxbytes),
4480 $answer->answer
, null);
4481 $DB->set_field('lesson_answers', 'answer', $answer->answer
, array('id' => $answer->id
));
4483 if (isset($responseeditor['itemid'])) {
4484 $answer->response
= file_save_draft_area_files($responseeditor['itemid'],
4485 $context->id
, 'mod_lesson', 'page_responses', $answer->id
,
4486 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES
, 'maxbytes' => $maxbytes),
4487 $answer->response
, null);
4488 $DB->set_field('lesson_answers', 'response', $answer->response
, array('id' => $answer->id
));
4493 * Rewrite urls in response and optionality answer of a question answer
4495 * @param object $answer
4496 * @param bool $rewriteanswer must rewrite answer
4497 * @return object answer with rewritten urls
4499 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
4502 $context = context_module
::instance($PAGE->cm
->id
);
4503 if ($rewriteanswer) {
4504 $answer->answer
= file_rewrite_pluginfile_urls($answer->answer
, 'pluginfile.php', $context->id
,
4505 'mod_lesson', 'page_answers', $answer->id
);
4507 $answer->response
= file_rewrite_pluginfile_urls($answer->response
, 'pluginfile.php', $context->id
,
4508 'mod_lesson', 'page_responses', $answer->id
);
4514 * Updates a lesson page and its answers within the database
4516 * @param object $properties
4519 public function update($properties, $context = null, $maxbytes = null) {
4521 $answers = $this->get_answers();
4522 $properties->id
= $this->properties
->id
;
4523 $properties->lessonid
= $this->lesson
->id
;
4524 if (empty($properties->qoption
)) {
4525 $properties->qoption
= '0';
4527 if (empty($context)) {
4528 $context = $PAGE->context
;
4530 if ($maxbytes === null) {
4531 $maxbytes = get_user_max_upload_file_size($context);
4533 $properties->timemodified
= time();
4534 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id
);
4535 $DB->update_record("lesson_pages", $properties);
4537 // Trigger an event: page updated.
4538 \mod_lesson\event\page_updated
::create_from_lesson_page($this, $context)->trigger();
4540 if ($this->type
== self
::TYPE_STRUCTURE
&& $this->get_typeid() != LESSON_PAGE_BRANCHTABLE
) {
4541 // These page types have only one answer to save the jump and score.
4542 if (count($answers) > 1) {
4543 $answer = array_shift($answers);
4544 foreach ($answers as $a) {
4545 $DB->delete_records('lesson_answers', array('id' => $a->id
));
4547 } else if (count($answers) == 1) {
4548 $answer = array_shift($answers);
4550 $answer = new stdClass
;
4551 $answer->lessonid
= $properties->lessonid
;
4552 $answer->pageid
= $properties->id
;
4553 $answer->timecreated
= time();
4556 $answer->timemodified
= time();
4557 if (isset($properties->jumpto
[0])) {
4558 $answer->jumpto
= $properties->jumpto
[0];
4560 if (isset($properties->score
[0])) {
4561 $answer->score
= $properties->score
[0];
4563 if (!empty($answer->id
)) {
4564 $DB->update_record("lesson_answers", $answer->properties());
4566 $DB->insert_record("lesson_answers", $answer);
4569 for ($i = 0; $i < count($properties->answer_editor
); $i++
) {
4570 if (!array_key_exists($i, $this->answers
)) {
4571 $this->answers
[$i] = new stdClass
;
4572 $this->answers
[$i]->lessonid
= $this->lesson
->id
;
4573 $this->answers
[$i]->pageid
= $this->id
;
4574 $this->answers
[$i]->timecreated
= $this->timecreated
;
4575 $this->answers
[$i]->answer
= null;
4578 if (isset($properties->answer_editor
[$i])) {
4579 if (is_array($properties->answer_editor
[$i])) {
4580 // Multichoice and true/false pages have an HTML editor.
4581 $this->answers
[$i]->answer
= $properties->answer_editor
[$i]['text'];
4582 $this->answers
[$i]->answerformat
= $properties->answer_editor
[$i]['format'];
4584 // Branch tables, shortanswer and mumerical pages have only a text field.
4585 $this->answers
[$i]->answer
= $properties->answer_editor
[$i];
4586 $this->answers
[$i]->answerformat
= FORMAT_MOODLE
;
4589 // If there is no data posted which means we want to reset the stored values.
4590 $this->answers
[$i]->answer
= null;
4593 if (!empty($properties->response_editor
[$i]) && is_array($properties->response_editor
[$i])) {
4594 $this->answers
[$i]->response
= $properties->response_editor
[$i]['text'];
4595 $this->answers
[$i]->responseformat
= $properties->response_editor
[$i]['format'];
4598 if ($this->answers
[$i]->answer
!== null && $this->answers
[$i]->answer
!== '') {
4599 if (isset($properties->jumpto
[$i])) {
4600 $this->answers
[$i]->jumpto
= $properties->jumpto
[$i];
4602 if ($this->lesson
->custom
&& isset($properties->score
[$i])) {
4603 $this->answers
[$i]->score
= $properties->score
[$i];
4605 if (!isset($this->answers
[$i]->id
)) {
4606 $this->answers
[$i]->id
= $DB->insert_record("lesson_answers", $this->answers
[$i]);
4608 $DB->update_record("lesson_answers", $this->answers
[$i]->properties());
4611 // Save files in answers and responses.
4612 if (isset($properties->response_editor
[$i])) {
4613 $this->save_answers_files($context, $maxbytes, $this->answers
[$i],
4614 $properties->answer_editor
[$i], $properties->response_editor
[$i]);
4616 $this->save_answers_files($context, $maxbytes, $this->answers
[$i],
4617 $properties->answer_editor
[$i]);
4620 } else if (isset($this->answers
[$i]->id
)) {
4621 $DB->delete_records('lesson_answers', array('id' => $this->answers
[$i]->id
));
4622 unset($this->answers
[$i]);
4630 * Can be set to true if the page requires a static link to create a new instance
4631 * instead of simply being included in the dropdown
4632 * @param int $previd
4635 public function add_page_link($previd) {
4640 * Returns true if a page has been viewed before
4642 * @param array|int $param Either an array of pages that have been seen or the
4643 * number of retakes a user has had
4646 public function is_unseen($param) {
4648 if (is_array($param)) {
4649 $seenpages = $param;
4650 return (!array_key_exists($this->properties
->id
, $seenpages));
4653 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties
->id
, "userid"=>$USER->id
, "retry"=>$nretakes))) {
4661 * Checks to see if a page has been answered previously
4662 * @param int $nretakes
4665 public function is_unanswered($nretakes) {
4667 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties
->id
, 'userid'=>$USER->id
, 'correct'=>1, 'retry'=>$nretakes))) {
4674 * Creates answers within the database for this lesson_page. Usually only ever
4675 * called when creating a new page instance
4676 * @param object $properties
4679 public function create_answers($properties) {
4681 // now add the answers
4682 $newanswer = new stdClass
;
4683 $newanswer->lessonid
= $this->lesson
->id
;
4684 $newanswer->pageid
= $this->properties
->id
;
4685 $newanswer->timecreated
= $this->properties
->timecreated
;
4687 $cm = get_coursemodule_from_instance('lesson', $this->lesson
->id
, $this->lesson
->course
);
4688 $context = context_module
::instance($cm->id
);
4692 for ($i = 0; $i < ($this->lesson
->maxanswers +
1); $i++
) {
4693 $answer = clone($newanswer);
4695 if (isset($properties->answer_editor
[$i])) {
4696 if (is_array($properties->answer_editor
[$i])) {
4697 // Multichoice and true/false pages have an HTML editor.
4698 $answer->answer
= $properties->answer_editor
[$i]['text'];
4699 $answer->answerformat
= $properties->answer_editor
[$i]['format'];
4701 // Branch tables, shortanswer and mumerical pages have only a text field.
4702 $answer->answer
= $properties->answer_editor
[$i];
4703 $answer->answerformat
= FORMAT_MOODLE
;
4706 if (!empty($properties->response_editor
[$i]) && is_array($properties->response_editor
[$i])) {
4707 $answer->response
= $properties->response_editor
[$i]['text'];
4708 $answer->responseformat
= $properties->response_editor
[$i]['format'];
4711 if (isset($answer->answer
) && $answer->answer
!= '') {
4712 if (isset($properties->jumpto
[$i])) {
4713 $answer->jumpto
= $properties->jumpto
[$i];
4715 if ($this->lesson
->custom
&& isset($properties->score
[$i])) {
4716 $answer->score
= $properties->score
[$i];
4718 $answer->id
= $DB->insert_record("lesson_answers", $answer);
4719 if (isset($properties->response_editor
[$i])) {
4720 $this->save_answers_files($context, $PAGE->course
->maxbytes
, $answer,
4721 $properties->answer_editor
[$i], $properties->response_editor
[$i]);
4723 $this->save_answers_files($context, $PAGE->course
->maxbytes
, $answer,
4724 $properties->answer_editor
[$i]);
4726 $answers[$answer->id
] = new lesson_page_answer($answer);
4730 $this->answers
= $answers;
4735 * This method MUST be overridden by all question page types, or page types that
4736 * wish to score a page.
4738 * The structure of result should always be the same so it is a good idea when
4739 * overriding this method on a page type to call
4741 * $result = parent::check_answer();
4743 * before modifying it as required.
4747 public function check_answer() {
4748 $result = new stdClass
;
4749 $result->answerid
= 0;
4750 $result->noanswer
= false;
4751 $result->correctanswer
= false;
4752 $result->isessayquestion
= false; // use this to turn off review button on essay questions
4753 $result->response
= '';
4754 $result->newpageid
= 0; // stay on the page
4755 $result->studentanswer
= ''; // use this to store student's answer(s) in order to display it on feedback page
4756 $result->studentanswerformat
= FORMAT_MOODLE
;
4757 $result->userresponse
= null;
4758 $result->feedback
= '';
4759 // Store data that was POSTd by a form. This is currently used to perform any logic after the 1st write to the db
4761 $result->postdata
= false;
4762 $result->nodefaultresponse
= false; // Flag for redirecting when default feedback is turned off
4763 $result->inmediatejump
= false; // Flag to detect when we should do a jump from the page without further processing.
4768 * Do any post persistence processing logic of an attempt. E.g. in cases where we need update file urls in an editor
4769 * and we need to have the id of the stored attempt. Should be overridden in each individual child
4770 * pagetype on a as required basis
4772 * @param object $attempt The attempt corresponding to the db record
4773 * @param object $result The result from the 'check_answer' method
4774 * @return array False if nothing to be modified, updated $attempt and $result if update required.
4776 public function on_after_write_attempt($attempt, $result) {
4777 return [false, false];
4781 * True if the page uses a custom option
4783 * Should be override and set to true if the page uses a custom option.
4787 public function has_option() {
4792 * Returns the maximum number of answers for this page given the maximum number
4793 * of answers permitted by the lesson.
4795 * @param int $default
4798 public function max_answers($default) {
4803 * Returns the properties of this lesson page as an object
4806 public function properties() {
4807 $properties = clone($this->properties
);
4808 if ($this->answers
=== null) {
4809 $this->get_answers();
4811 if (count($this->answers
)>0) {
4813 $qtype = $properties->qtype
;
4814 foreach ($this->answers
as $answer) {
4815 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer
, 'format' => $answer->answerformat
);
4816 if ($qtype != LESSON_PAGE_MATCHING
) {
4817 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response
, 'format' => $answer->responseformat
);
4819 $properties->{'response_editor['.$count.']'} = $answer->response
;
4821 $properties->{'jumpto['.$count.']'} = $answer->jumpto
;
4822 $properties->{'score['.$count.']'} = $answer->score
;
4830 * Returns an array of options to display when choosing the jumpto for a page/answer
4832 * @param int $pageid
4833 * @param lesson $lesson
4836 public static function get_jumptooptions($pageid, lesson
$lesson) {
4839 $jump[0] = get_string("thispage", "lesson");
4840 $jump[LESSON_NEXTPAGE
] = get_string("nextpage", "lesson");
4841 $jump[LESSON_PREVIOUSPAGE
] = get_string("previouspage", "lesson");
4842 $jump[LESSON_EOL
] = get_string("endoflesson", "lesson");
4848 $pages = $lesson->load_all_pages();
4849 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
))) {
4850 $jump[LESSON_UNSEENBRANCHPAGE
] = get_string("unseenpageinbranch", "lesson");
4851 $jump[LESSON_RANDOMPAGE
] = get_string("randompageinbranch", "lesson");
4853 if($pages[$pageid]->qtype
== LESSON_PAGE_CLUSTER ||
$lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER
), array(LESSON_PAGE_ENDOFCLUSTER
))) {
4854 $jump[LESSON_CLUSTERJUMP
] = get_string("clusterjump", "lesson");
4856 if (!optional_param('firstpage', 0, PARAM_INT
)) {
4857 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id
, "prevpageid" => 0));
4860 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
4861 $jump[$apageid] = strip_tags(format_string($title,true));
4862 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
4864 // last page reached
4872 * Returns the contents field for the page properly formatted and with plugin
4873 * file url's converted
4876 public function get_contents() {
4878 if (!empty($this->properties
->contents
)) {
4879 if (!isset($this->properties
->contentsformat
)) {
4880 $this->properties
->contentsformat
= FORMAT_HTML
;
4882 $context = context_module
::instance($PAGE->cm
->id
);
4883 $contents = file_rewrite_pluginfile_urls($this->properties
->contents
, 'pluginfile.php', $context->id
, 'mod_lesson',
4884 'page_contents', $this->properties
->id
); // Must do this BEFORE format_text()!
4885 return format_text($contents, $this->properties
->contentsformat
,
4886 array('context' => $context, 'noclean' => true,
4887 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
4894 * Set to true if this page should display in the menu block
4897 protected function get_displayinmenublock() {
4902 * Get the string that describes the options of this page type
4905 public function option_description_string() {
4910 * Updates a table with the answers for this page
4911 * @param html_table $table
4912 * @return html_table
4914 public function display_answers(html_table
$table) {
4915 $answers = $this->get_answers();
4917 foreach ($answers as $answer) {
4919 $cells[] = '<label>' . get_string('jump', 'lesson') . ' ' . $i . '</label>:';
4920 $cells[] = $this->get_jump_name($answer->jumpto
);
4921 $table->data
[] = new html_table_row($cells);
4923 $table->data
[count($table->data
)-1]->cells
[0]->style
= 'width:20%;';
4931 * Determines if this page should be grayed out on the management/report screens
4932 * @return int 0 or 1
4934 protected function get_grayout() {
4939 * Adds stats for this page to the &pagestats object. This should be defined
4940 * for all page types that grade
4941 * @param array $pagestats
4945 public function stats(array &$pagestats, $tries) {
4950 * Formats the answers of this page for a report
4952 * @param object $answerpage
4953 * @param object $answerdata
4954 * @param object $useranswer
4955 * @param array $pagestats
4956 * @param int $i Count of first level answers
4957 * @param int $n Count of second level answers
4958 * @return object The answer page for this
4960 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
4961 $answers = $this->get_answers();
4962 $formattextdefoptions = new stdClass
;
4963 $formattextdefoptions->para
= false; //I'll use it widely in this page
4964 foreach ($answers as $answer) {
4965 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto
));
4966 $answerdata->answers
[] = array($data, "");
4967 $answerpage->answerdata
= $answerdata;
4973 * Gets an array of the jumps used by the answers of this page
4977 public function get_jumps() {
4980 $params = array ("lessonid" => $this->lesson
->id
, "pageid" => $this->properties
->id
);
4981 if ($answers = $this->get_answers()) {
4982 foreach ($answers as $answer) {
4983 $jumps[] = $this->get_jump_name($answer->jumpto
);
4986 $jumps[] = $this->get_jump_name($this->properties
->nextpageid
);
4991 * Informs whether this page type require manual grading or not
4994 public function requires_manual_grading() {
4999 * A callback method that allows a page to override the next page a user will
5000 * see during when this page is being completed.
5003 public function override_next_page() {
5008 * This method is used to determine if this page is a valid page
5010 * @param array $validpages
5011 * @param array $pageviews
5012 * @return int The next page id to check
5014 public function valid_page_and_view(&$validpages, &$pageviews) {
5015 $validpages[$this->properties
->id
] = 1;
5016 return $this->properties
->nextpageid
;
5020 * Get files from the page area file.
5022 * @param bool $includedirs whether or not include directories
5023 * @param int $updatedsince return files updated since this time
5024 * @return array list of stored_file objects
5027 public function get_files($includedirs = true, $updatedsince = 0) {
5028 $fs = get_file_storage();
5029 return $fs->get_area_files($this->lesson
->context
->id
, 'mod_lesson', 'page_contents', $this->properties
->id
,
5030 'itemid, filepath, filename', $includedirs, $updatedsince);
5034 * Make updates to the form data if required.
5037 * @param stdClass $data The form data to update.
5038 * @return stdClass The updated fom data.
5040 public function update_form_data(stdClass
$data): stdClass
{
5048 * Class used to represent an answer to a page
5050 * @property int $id The ID of this answer in the database
5051 * @property int $lessonid The ID of the lesson this answer belongs to
5052 * @property int $pageid The ID of the page this answer belongs to
5053 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
5054 * @property int $grade The grade this answer is worth
5055 * @property int $score The score this answer will give
5056 * @property int $flags Used to store options for the answer
5057 * @property int $timecreated A timestamp of when the answer was created
5058 * @property int $timemodified A timestamp of when the answer was modified
5059 * @property string $answer The answer itself
5060 * @property string $response The response the user sees if selecting this answer
5062 * @copyright 2009 Sam Hemelryk
5063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 class lesson_page_answer
extends lesson_base
{
5068 * Loads an page answer from the DB
5071 * @return lesson_page_answer
5073 public static function load($id) {
5075 $answer = $DB->get_record("lesson_answers", array("id" => $id));
5076 return new lesson_page_answer($answer);
5080 * Given an object of properties and a page created answer(s) and saves them
5083 * @param stdClass $properties
5084 * @param lesson_page $page
5087 public static function create($properties, lesson_page
$page) {
5088 return $page->create_answers($properties);
5092 * Get files from the answer area file.
5094 * @param bool $includedirs whether or not include directories
5095 * @param int $updatedsince return files updated since this time
5096 * @return array list of stored_file objects
5099 public function get_files($includedirs = true, $updatedsince = 0) {
5101 $lesson = lesson
::load($this->properties
->lessonid
);
5102 $fs = get_file_storage();
5103 $answerfiles = $fs->get_area_files($lesson->context
->id
, 'mod_lesson', 'page_answers', $this->properties
->id
,
5104 'itemid, filepath, filename', $includedirs, $updatedsince);
5105 $responsefiles = $fs->get_area_files($lesson->context
->id
, 'mod_lesson', 'page_responses', $this->properties
->id
,
5106 'itemid, filepath, filename', $includedirs, $updatedsince);
5107 return array_merge($answerfiles, $responsefiles);
5113 * A management class for page types
5115 * This class is responsible for managing the different pages. A manager object can
5116 * be retrieved by calling the following line of code:
5118 * $manager = lesson_page_type_manager::get($lesson);
5120 * The first time the page type manager is retrieved the it includes all of the
5121 * different page types located in mod/lesson/pagetypes.
5123 * @copyright 2009 Sam Hemelryk
5124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5126 class lesson_page_type_manager
{
5129 * An array of different page type classes
5132 protected $types = array();
5135 * Retrieves the lesson page type manager object
5137 * If the object hasn't yet been created it is created here.
5139 * @staticvar lesson_page_type_manager $pagetypemanager
5140 * @param lesson $lesson
5141 * @return lesson_page_type_manager
5143 public static function get(lesson
$lesson) {
5144 static $pagetypemanager;
5145 if (!($pagetypemanager instanceof lesson_page_type_manager
)) {
5146 $pagetypemanager = new lesson_page_type_manager();
5147 $pagetypemanager->load_lesson_types($lesson);
5149 return $pagetypemanager;
5153 * Finds and loads all lesson page types in mod/lesson/pagetypes
5155 * @param lesson $lesson
5157 public function load_lesson_types(lesson
$lesson) {
5159 $basedir = $CFG->dirroot
.'/mod/lesson/pagetypes/';
5160 $dir = dir($basedir);
5161 while (false !== ($entry = $dir->read())) {
5162 if (strpos($entry, '.')===0 ||
!preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
5165 require_once($basedir.$entry);
5166 $class = 'lesson_page_type_'.strtok($entry,'.');
5167 if (class_exists($class)) {
5168 $pagetype = new $class(new stdClass
, $lesson);
5169 $this->types
[$pagetype->typeid
] = $pagetype;
5176 * Returns an array of strings to describe the loaded page types
5178 * @param int $type Can be used to return JUST the string for the requested type
5181 public function get_page_type_strings($type=null, $special=true) {
5183 foreach ($this->types
as $pagetype) {
5184 if (($type===null ||
$pagetype->type
===$type) && ($special===true ||
$pagetype->is_standard())) {
5185 $types[$pagetype->typeid
] = $pagetype->typestring
;
5192 * Returns the basic string used to identify a page type provided with an id
5194 * This string can be used to instantiate or identify the page type class.
5195 * If the page type id is unknown then 'unknown' is returned
5200 public function get_page_type_idstring($id) {
5201 foreach ($this->types
as $pagetype) {
5202 if ((int)$pagetype->typeid
=== (int)$id) {
5203 return $pagetype->idstring
;
5210 * Loads a page for the provided lesson given it's id
5212 * This function loads a page from the lesson when given both the lesson it belongs
5213 * to as well as the page's id.
5214 * If the page doesn't exist an error is thrown
5216 * @param int $pageid The id of the page to load
5217 * @param lesson $lesson The lesson the page belongs to
5218 * @return lesson_page A class that extends lesson_page
5220 public function load_page($pageid, lesson
$lesson) {
5222 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id
)))) {
5223 throw new \
moodle_exception('cannotfindpages', 'lesson');
5225 $pagetype = get_class($this->types
[$page->qtype
]);
5226 $page = new $pagetype($page, $lesson);
5231 * This function detects errors in the ordering between 2 pages and updates the page records.
5233 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
5234 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
5236 protected function check_page_order($page1, $page2) {
5238 if (empty($page1)) {
5239 if ($page2->prevpageid
!= 0) {
5240 debugging("***prevpageid of page " . $page2->id
. " set to 0***");
5241 $page2->prevpageid
= 0;
5242 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id
));
5244 } else if (empty($page2)) {
5245 if ($page1->nextpageid
!= 0) {
5246 debugging("***nextpageid of page " . $page1->id
. " set to 0***");
5247 $page1->nextpageid
= 0;
5248 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id
));
5251 if ($page1->nextpageid
!= $page2->id
) {
5252 debugging("***nextpageid of page " . $page1->id
. " set to " . $page2->id
. "***");
5253 $page1->nextpageid
= $page2->id
;
5254 $DB->set_field("lesson_pages", "nextpageid", $page2->id
, array("id" => $page1->id
));
5256 if ($page2->prevpageid
!= $page1->id
) {
5257 debugging("***prevpageid of page " . $page2->id
. " set to " . $page1->id
. "***");
5258 $page2->prevpageid
= $page1->id
;
5259 $DB->set_field("lesson_pages", "prevpageid", $page1->id
, array("id" => $page2->id
));
5265 * This function loads ALL pages that belong to the lesson.
5267 * @param lesson $lesson
5268 * @return array An array of lesson_page_type_*
5270 public function load_all_pages(lesson
$lesson) {
5272 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id
)))) {
5273 return array(); // Records returned empty.
5275 foreach ($pages as $key=>$page) {
5276 $pagetype = get_class($this->types
[$page->qtype
]);
5277 $pages[$key] = new $pagetype($page, $lesson);
5280 $orderedpages = array();
5283 while ($morepages) {
5285 foreach ($pages as $page) {
5286 if ((int)$page->prevpageid
=== (int)$lastpageid) {
5287 // Check for errors in page ordering and fix them on the fly.
5289 if ($lastpageid !== 0) {
5290 $prevpage = $orderedpages[$lastpageid];
5292 $this->check_page_order($prevpage, $page);
5294 $orderedpages[$page->id
] = $page;
5295 unset($pages[$page->id
]);
5296 $lastpageid = $page->id
;
5297 if ((int)$page->nextpageid
===0) {
5306 // Add remaining pages and fix the nextpageid links for each page.
5307 foreach ($pages as $page) {
5308 // Check for errors in page ordering and fix them on the fly.
5310 if ($lastpageid !== 0) {
5311 $prevpage = $orderedpages[$lastpageid];
5313 $this->check_page_order($prevpage, $page);
5314 $orderedpages[$page->id
] = $page;
5315 unset($pages[$page->id
]);
5316 $lastpageid = $page->id
;
5319 if ($lastpageid !== 0) {
5320 $this->check_page_order($orderedpages[$lastpageid], null);
5323 return $orderedpages;
5327 * Fetches an mform that can be used to create/edit an page
5329 * @param int $type The id for the page type
5330 * @param array $arguments Any arguments to pass to the mform
5331 * @return lesson_add_page_form_base
5333 public function get_page_form($type, $arguments) {
5334 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
5335 if (!class_exists($class) ||
get_parent_class($class)!=='lesson_add_page_form_base') {
5336 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER
);
5337 $class = 'lesson_add_page_form_selection';
5338 } else if ($class === 'lesson_add_page_form_unknown') {
5339 $class = 'lesson_add_page_form_selection';
5341 return new $class(null, $arguments);
5345 * Returns an array of links to use as add page links
5346 * @param int $previd The id of the previous page
5349 public function get_add_page_type_links($previd) {
5354 foreach ($this->types
as $key=>$type) {
5355 if ($link = $type->add_page_link($previd)) {
5356 $links[$key] = $link;