MDL-51569 mod_choice: Prevent users from updating choices with curl
[moodle.git] / mod / lesson / locallib.php
blobde3221bbbcaa9193dad15bf9a84155ba2e742eff
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Local library file for Lesson. These are non-standard functions that are used
20 * only by Lesson.
22 * @package mod_lesson
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
25 **/
27 /** Make sure this isn't being directly accessed */
28 defined('MOODLE_INTERNAL') || die();
30 /** Include the files that are required by this module */
31 require_once($CFG->dirroot.'/course/moodleform_mod.php');
32 require_once($CFG->dirroot . '/mod/lesson/lib.php');
33 require_once($CFG->libdir . '/filelib.php');
35 /** This page */
36 define('LESSON_THISPAGE', 0);
37 /** Next page -> any page not seen before */
38 define("LESSON_UNSEENPAGE", 1);
39 /** Next page -> any page not answered correctly */
40 define("LESSON_UNANSWEREDPAGE", 2);
41 /** Jump to Next Page */
42 define("LESSON_NEXTPAGE", -1);
43 /** End of Lesson */
44 define("LESSON_EOL", -9);
45 /** Jump to an unseen page within a branch and end of branch or end of lesson */
46 define("LESSON_UNSEENBRANCHPAGE", -50);
47 /** Jump to Previous Page */
48 define("LESSON_PREVIOUSPAGE", -40);
49 /** Jump to a random page within a branch and end of branch or end of lesson */
50 define("LESSON_RANDOMPAGE", -60);
51 /** Jump to a random Branch */
52 define("LESSON_RANDOMBRANCH", -70);
53 /** Cluster Jump */
54 define("LESSON_CLUSTERJUMP", -80);
55 /** Undefined */
56 define("LESSON_UNDEFINED", -99);
58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59 define("LESSON_MAX_EVENT_LENGTH", "432000");
62 //////////////////////////////////////////////////////////////////////////////////////
63 /// Any other lesson functions go here. Each of them must have a name that
64 /// starts with lesson_
66 /**
67 * Checks to see if a LESSON_CLUSTERJUMP or
68 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
70 * This function is only executed when a teacher is
71 * checking the navigation for a lesson.
73 * @param stdClass $lesson Id of the lesson that is to be checked.
74 * @return boolean True or false.
75 **/
76 function lesson_display_teacher_warning($lesson) {
77 global $DB;
79 // get all of the lesson answers
80 $params = array ("lessonid" => $lesson->id);
81 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
82 // no answers, then not using cluster or unseen
83 return false;
85 // just check for the first one that fulfills the requirements
86 foreach ($lessonanswers as $lessonanswer) {
87 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
88 return true;
92 // if no answers use either of the two jumps
93 return false;
96 /**
97 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
99 * will return the pageid of a random unseen page that is within a branch
101 * @param lesson $lesson
102 * @param int $userid Id of the user.
103 * @param int $pageid Id of the page from which we are jumping.
104 * @return int Id of the next page.
106 function lesson_unseen_question_jump($lesson, $user, $pageid) {
107 global $DB;
109 // get the number of retakes
110 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
111 $retakes = 0;
114 // get all the lesson_attempts aka what the user has seen
115 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
116 foreach($viewedpages as $viewed) {
117 $seenpages[] = $viewed->pageid;
119 } else {
120 $seenpages = array();
123 // get the lesson pages
124 $lessonpages = $lesson->load_all_pages();
126 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
127 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
130 // go up the pages till branch table
131 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
132 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
133 break;
135 $pageid = $lessonpages[$pageid]->prevpageid;
138 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
140 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
141 $unseen = array();
142 foreach($pagesinbranch as $page) {
143 if (!in_array($page->id, $seenpages)) {
144 $unseen[] = $page->id;
148 if(count($unseen) == 0) {
149 if(isset($pagesinbranch)) {
150 $temp = end($pagesinbranch);
151 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
152 } else {
153 // there are no pages inside the branch, so return the next page
154 $nextpage = $lessonpages[$pageid]->nextpageid;
156 if ($nextpage == 0) {
157 return LESSON_EOL;
158 } else {
159 return $nextpage;
161 } else {
162 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
167 * Handles the unseen branch table jump.
169 * @param lesson $lesson
170 * @param int $userid User id.
171 * @return int Will return the page id of a branch table or end of lesson
173 function lesson_unseen_branch_jump($lesson, $userid) {
174 global $DB;
176 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
177 $retakes = 0;
180 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
181 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
182 "timeseen DESC")) {
183 print_error('cannotfindrecords', 'lesson');
186 // get the lesson pages
187 $lessonpages = $lesson->load_all_pages();
189 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
190 // which is the branch table that starts the unseenbranch function
191 $seen = array();
192 foreach ($seenbranches as $seenbranch) {
193 if (!$seenbranch->flag) {
194 $seen[$seenbranch->pageid] = $seenbranch->pageid;
195 } else {
196 $start = $seenbranch->pageid;
197 break;
200 // this function searches through the lesson pages to find all the branch tables
201 // that follow the flagged branch table
202 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
203 $branchtables = array();
204 while ($pageid != 0) { // grab all of the branch table till eol
205 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
206 $branchtables[] = $lessonpages[$pageid]->id;
208 $pageid = $lessonpages[$pageid]->nextpageid;
210 $unseen = array();
211 foreach ($branchtables as $branchtable) {
212 // load all of the unseen branch tables into unseen
213 if (!array_key_exists($branchtable, $seen)) {
214 $unseen[] = $branchtable;
217 if (count($unseen) > 0) {
218 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
219 } else {
220 return LESSON_EOL; // has viewed all of the branch tables
225 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
227 * @param lesson $lesson
228 * @param int $pageid The id of the page that we are jumping from (?)
229 * @return int The pageid of a random page that is within a branch table
231 function lesson_random_question_jump($lesson, $pageid) {
232 global $DB;
234 // get the lesson pages
235 $params = array ("lessonid" => $lesson->id);
236 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
237 print_error('cannotfindpages', 'lesson');
240 // go up the pages till branch table
241 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
243 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
244 break;
246 $pageid = $lessonpages[$pageid]->prevpageid;
249 // get the pages within the branch
250 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
252 if(count($pagesinbranch) == 0) {
253 // there are no pages inside the branch, so return the next page
254 return $lessonpages[$pageid]->nextpageid;
255 } else {
256 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
261 * Calculates a user's grade for a lesson.
263 * @param object $lesson The lesson that the user is taking.
264 * @param int $retries The attempt number.
265 * @param int $userid Id of the user (optional, default current user).
266 * @return object { nquestions => number of questions answered
267 attempts => number of question attempts
268 total => max points possible
269 earned => points earned by student
270 grade => calculated percentage grade
271 nmanual => number of manually graded questions
272 manualpoints => point value for manually graded questions }
274 function lesson_grade($lesson, $ntries, $userid = 0) {
275 global $USER, $DB;
277 if (empty($userid)) {
278 $userid = $USER->id;
281 // Zero out everything
282 $ncorrect = 0;
283 $nviewed = 0;
284 $score = 0;
285 $nmanual = 0;
286 $manualpoints = 0;
287 $thegrade = 0;
288 $nquestions = 0;
289 $total = 0;
290 $earned = 0;
292 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
293 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
294 userid = :userid AND retry = :retry", $params, "timeseen")) {
295 // group each try with its page
296 $attemptset = array();
297 foreach ($useranswers as $useranswer) {
298 $attemptset[$useranswer->pageid][] = $useranswer;
301 // Drop all attempts that go beyond max attempts for the lesson
302 foreach ($attemptset as $key => $set) {
303 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
306 // get only the pages and their answers that the user answered
307 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
308 array_unshift($parameters, $lesson->id);
309 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
310 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
312 // Number of pages answered
313 $nquestions = count($pages);
315 foreach ($attemptset as $attempts) {
316 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
317 if ($lesson->custom) {
318 $attempt = end($attempts);
319 // If essay question, handle it, otherwise add to score
320 if ($page->requires_manual_grading()) {
321 $useranswerobj = unserialize($attempt->useranswer);
322 if (isset($useranswerobj->score)) {
323 $earned += $useranswerobj->score;
325 $nmanual++;
326 $manualpoints += $answers[$attempt->answerid]->score;
327 } else if (!empty($attempt->answerid)) {
328 $earned += $page->earned_score($answers, $attempt);
330 } else {
331 foreach ($attempts as $attempt) {
332 $earned += $attempt->correct;
334 $attempt = end($attempts); // doesn't matter which one
335 // If essay question, increase numbers
336 if ($page->requires_manual_grading()) {
337 $nmanual++;
338 $manualpoints++;
341 // Number of times answered
342 $nviewed += count($attempts);
345 if ($lesson->custom) {
346 $bestscores = array();
347 // Find the highest possible score per page to get our total
348 foreach ($answers as $answer) {
349 if(!isset($bestscores[$answer->pageid])) {
350 $bestscores[$answer->pageid] = $answer->score;
351 } else if ($bestscores[$answer->pageid] < $answer->score) {
352 $bestscores[$answer->pageid] = $answer->score;
355 $total = array_sum($bestscores);
356 } else {
357 // Check to make sure the student has answered the minimum questions
358 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
359 // Nope, increase number viewed by the amount of unanswered questions
360 $total = $nviewed + ($lesson->minquestions - $nquestions);
361 } else {
362 $total = $nviewed;
367 if ($total) { // not zero
368 $thegrade = round(100 * $earned / $total, 5);
371 // Build the grade information object
372 $gradeinfo = new stdClass;
373 $gradeinfo->nquestions = $nquestions;
374 $gradeinfo->attempts = $nviewed;
375 $gradeinfo->total = $total;
376 $gradeinfo->earned = $earned;
377 $gradeinfo->grade = $thegrade;
378 $gradeinfo->nmanual = $nmanual;
379 $gradeinfo->manualpoints = $manualpoints;
381 return $gradeinfo;
385 * Determines if a user can view the left menu. The determining factor
386 * is whether a user has a grade greater than or equal to the lesson setting
387 * of displayleftif
389 * @param object $lesson Lesson object of the current lesson
390 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
392 function lesson_displayleftif($lesson) {
393 global $CFG, $USER, $DB;
395 if (!empty($lesson->displayleftif)) {
396 // get the current user's max grade for this lesson
397 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
398 if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
399 if ($maxgrade->maxgrade < $lesson->displayleftif) {
400 return 0; // turn off the displayleft
402 } else {
403 return 0; // no grades
407 // if we get to here, keep the original state of displayleft lesson setting
408 return $lesson->displayleft;
413 * @param $cm
414 * @param $lesson
415 * @param $page
416 * @return unknown_type
418 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
419 $bc = lesson_menu_block_contents($cm->id, $lesson);
420 if (!empty($bc)) {
421 $regions = $page->blocks->get_regions();
422 $firstregion = reset($regions);
423 $page->blocks->add_fake_block($bc, $firstregion);
426 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
427 if (!empty($bc)) {
428 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
431 if (!empty($timer)) {
432 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
433 if (!empty($bc)) {
434 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
440 * If there is a media file associated with this
441 * lesson, return a block_contents that displays it.
443 * @param int $cmid Course Module ID for this lesson
444 * @param object $lesson Full lesson record object
445 * @return block_contents
447 function lesson_mediafile_block_contents($cmid, $lesson) {
448 global $OUTPUT;
449 if (empty($lesson->mediafile)) {
450 return null;
453 $options = array();
454 $options['menubar'] = 0;
455 $options['location'] = 0;
456 $options['left'] = 5;
457 $options['top'] = 5;
458 $options['scrollbars'] = 1;
459 $options['resizable'] = 1;
460 $options['width'] = $lesson->mediawidth;
461 $options['height'] = $lesson->mediaheight;
463 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
464 $action = new popup_action('click', $link, 'lessonmediafile', $options);
465 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
467 $bc = new block_contents();
468 $bc->title = get_string('linkedmedia', 'lesson');
469 $bc->attributes['class'] = 'mediafile block';
470 $bc->content = $content;
472 return $bc;
476 * If a timed lesson and not a teacher, then
477 * return a block_contents containing the clock.
479 * @param int $cmid Course Module ID for this lesson
480 * @param object $lesson Full lesson record object
481 * @param object $timer Full timer record object
482 * @return block_contents
484 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
485 // Display for timed lessons and for students only
486 $context = context_module::instance($cmid);
487 if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) {
488 return null;
491 $content = '<div id="lesson-timer">';
492 $content .= $lesson->time_remaining($timer->starttime);
493 $content .= '</div>';
495 $clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
496 $page->requires->data_for_js('clocksettings', $clocksettings, true);
497 $page->requires->strings_for_js(array('timeisup'), 'lesson');
498 $page->requires->js('/mod/lesson/timer.js');
499 $page->requires->js_init_call('show_clock');
501 $bc = new block_contents();
502 $bc->title = get_string('timeremaining', 'lesson');
503 $bc->attributes['class'] = 'clock block';
504 $bc->content = $content;
506 return $bc;
510 * If left menu is turned on, then this will
511 * print the menu in a block
513 * @param int $cmid Course Module ID for this lesson
514 * @param lesson $lesson Full lesson record object
515 * @return void
517 function lesson_menu_block_contents($cmid, $lesson) {
518 global $CFG, $DB;
520 if (!$lesson->displayleft) {
521 return null;
524 $pages = $lesson->load_all_pages();
525 foreach ($pages as $page) {
526 if ((int)$page->prevpageid === 0) {
527 $pageid = $page->id;
528 break;
531 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
533 if (!$pageid || !$pages) {
534 return null;
537 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
539 while ($pageid != 0) {
540 $page = $pages[$pageid];
542 // Only process branch tables with display turned on
543 if ($page->displayinmenublock && $page->display) {
544 if ($page->id == $currentpageid) {
545 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
546 } else {
547 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&amp;pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
551 $pageid = $page->nextpageid;
553 $content .= "</ul>\n</div>\n";
555 $bc = new block_contents();
556 $bc->title = get_string('lessonmenu', 'lesson');
557 $bc->attributes['class'] = 'menu block';
558 $bc->content = $content;
560 return $bc;
564 * Adds header buttons to the page for the lesson
566 * @param object $cm
567 * @param object $context
568 * @param bool $extraeditbuttons
569 * @param int $lessonpageid
571 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
572 global $CFG, $PAGE, $OUTPUT;
573 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
574 if ($lessonpageid === null) {
575 print_error('invalidpageid', 'lesson');
577 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
578 $url = new moodle_url('/mod/lesson/editpage.php', array(
579 'id' => $cm->id,
580 'pageid' => $lessonpageid,
581 'edit' => 1,
582 'returnto' => $PAGE->url->out(false)
584 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
590 * This is a function used to detect media types and generate html code.
592 * @global object $CFG
593 * @global object $PAGE
594 * @param object $lesson
595 * @param object $context
596 * @return string $code the html code of media
598 function lesson_get_media_html($lesson, $context) {
599 global $CFG, $PAGE, $OUTPUT;
600 require_once("$CFG->libdir/resourcelib.php");
602 // get the media file link
603 if (strpos($lesson->mediafile, '://') !== false) {
604 $url = new moodle_url($lesson->mediafile);
605 } else {
606 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
607 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
609 $title = $lesson->mediafile;
611 $clicktoopen = html_writer::link($url, get_string('download'));
613 $mimetype = resourcelib_guess_url_mimetype($url);
615 $extension = resourcelib_get_extension($url->out(false));
617 $mediarenderer = $PAGE->get_renderer('core', 'media');
618 $embedoptions = array(
619 core_media::OPTION_TRUSTED => true,
620 core_media::OPTION_BLOCK => true
623 // find the correct type and print it out
624 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
625 $code = resourcelib_embed_image($url, $title);
627 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
628 // Media (audio/video) file.
629 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
631 } else {
632 // anything else - just try object tag enlarged as much as possible
633 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
636 return $code;
641 * Abstract class that page type's MUST inherit from.
643 * This is the abstract class that ALL add page type forms must extend.
644 * You will notice that all but two of the methods this class contains are final.
645 * Essentially the only thing that extending classes can do is extend custom_definition.
646 * OR if it has a special requirement on creation it can extend construction_override
648 * @abstract
649 * @copyright 2009 Sam Hemelryk
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 abstract class lesson_add_page_form_base extends moodleform {
655 * This is the classic define that is used to identify this pagetype.
656 * Will be one of LESSON_*
657 * @var int
659 public $qtype;
662 * The simple string that describes the page type e.g. truefalse, multichoice
663 * @var string
665 public $qtypestring;
668 * An array of options used in the htmleditor
669 * @var array
671 protected $editoroptions = array();
674 * True if this is a standard page of false if it does something special.
675 * Questions are standard pages, branch tables are not
676 * @var bool
678 protected $standard = true;
681 * Each page type can and should override this to add any custom elements to
682 * the basic form that they want
684 public function custom_definition() {}
687 * Used to determine if this is a standard page or a special page
688 * @return bool
690 public final function is_standard() {
691 return (bool)$this->standard;
695 * Add the required basic elements to the form.
697 * This method adds the basic elements to the form including title and contents
698 * and then calls custom_definition();
700 public final function definition() {
701 $mform = $this->_form;
702 $editoroptions = $this->_customdata['editoroptions'];
704 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
706 if (!empty($this->_customdata['returnto'])) {
707 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
708 $mform->setType('returnto', PARAM_URL);
711 $mform->addElement('hidden', 'id');
712 $mform->setType('id', PARAM_INT);
714 $mform->addElement('hidden', 'pageid');
715 $mform->setType('pageid', PARAM_INT);
717 if ($this->standard === true) {
718 $mform->addElement('hidden', 'qtype');
719 $mform->setType('qtype', PARAM_INT);
721 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
722 $mform->setType('title', PARAM_TEXT);
723 $mform->addRule('title', get_string('required'), 'required', null, 'client');
725 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
726 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
727 $mform->setType('contents_editor', PARAM_RAW);
728 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
731 $this->custom_definition();
733 if ($this->_customdata['edit'] === true) {
734 $mform->addElement('hidden', 'edit', 1);
735 $mform->setType('edit', PARAM_BOOL);
736 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
737 } else if ($this->qtype === 'questiontype') {
738 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
739 } else {
740 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
745 * Convenience function: Adds a jumpto select element
747 * @param string $name
748 * @param string|null $label
749 * @param int $selected The page to select by default
751 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
752 $title = get_string("jump", "lesson");
753 if ($label === null) {
754 $label = $title;
756 if (is_int($name)) {
757 $name = "jumpto[$name]";
759 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
760 $this->_form->setDefault($name, $selected);
761 $this->_form->addHelpButton($name, 'jumps', 'lesson');
765 * Convenience function: Adds a score input element
767 * @param string $name
768 * @param string|null $label
769 * @param mixed $value The default value
771 protected final function add_score($name, $label=null, $value=null) {
772 if ($label === null) {
773 $label = get_string("score", "lesson");
776 if (is_int($name)) {
777 $name = "score[$name]";
779 $this->_form->addElement('text', $name, $label, array('size'=>5));
780 $this->_form->setType($name, PARAM_INT);
781 if ($value !== null) {
782 $this->_form->setDefault($name, $value);
784 $this->_form->addHelpButton($name, 'score', 'lesson');
786 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
787 if (!$this->_customdata['lesson']->custom) {
788 $this->_form->freeze($name);
793 * Convenience function: Adds an answer editor
795 * @param int $count The count of the element to add
796 * @param string $label, null means default
797 * @param bool $required
798 * @return void
800 protected final function add_answer($count, $label = null, $required = false) {
801 if ($label === null) {
802 $label = get_string('answer', 'lesson');
804 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
805 $this->_form->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
806 if ($required) {
807 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
811 * Convenience function: Adds an response editor
813 * @param int $count The count of the element to add
814 * @param string $label, null means default
815 * @param bool $required
816 * @return void
818 protected final function add_response($count, $label = null, $required = false) {
819 if ($label === null) {
820 $label = get_string('response', 'lesson');
822 $this->_form->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
823 $this->_form->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
824 if ($required) {
825 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
830 * A function that gets called upon init of this object by the calling script.
832 * This can be used to process an immediate action if required. Currently it
833 * is only used in special cases by non-standard page types.
835 * @return bool
837 public function construction_override($pageid, lesson $lesson) {
838 return true;
845 * Class representation of a lesson
847 * This class is used the interact with, and manage a lesson once instantiated.
848 * If you need to fetch a lesson object you can do so by calling
850 * <code>
851 * lesson::load($lessonid);
852 * // or
853 * $lessonrecord = $DB->get_record('lesson', $lessonid);
854 * $lesson = new lesson($lessonrecord);
855 * </code>
857 * The class itself extends lesson_base as all classes within the lesson module should
859 * These properties are from the database
860 * @property int $id The id of this lesson
861 * @property int $course The ID of the course this lesson belongs to
862 * @property string $name The name of this lesson
863 * @property int $practice Flag to toggle this as a practice lesson
864 * @property int $modattempts Toggle to allow the user to go back and review answers
865 * @property int $usepassword Toggle the use of a password for entry
866 * @property string $password The password to require users to enter
867 * @property int $dependency ID of another lesson this lesson is dependent on
868 * @property string $conditions Conditions of the lesson dependency
869 * @property int $grade The maximum grade a user can achieve (%)
870 * @property int $custom Toggle custom scoring on or off
871 * @property int $ongoing Toggle display of an ongoing score
872 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
873 * @property int $maxanswers The max number of answers or branches
874 * @property int $maxattempts The maximum number of attempts a user can record
875 * @property int $review Toggle use or wrong answer review button
876 * @property int $nextpagedefault Override the default next page
877 * @property int $feedback Toggles display of default feedback
878 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
879 * @property int $maxpages Maximum number of pages this lesson can contain
880 * @property int $retake Flag to allow users to retake a lesson
881 * @property int $activitylink Relate this lesson to another lesson
882 * @property string $mediafile File to pop up to or webpage to display
883 * @property int $mediaheight Sets the height of the media file popup
884 * @property int $mediawidth Sets the width of the media file popup
885 * @property int $mediaclose Toggle display of a media close button
886 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
887 * @property int $width Width of slideshow
888 * @property int $height Height of slideshow
889 * @property string $bgcolor Background colour of slideshow
890 * @property int $displayleft Display a left menu
891 * @property int $displayleftif Sets the condition on which the left menu is displayed
892 * @property int $progressbar Flag to toggle display of a lesson progress bar
893 * @property int $highscores Flag to toggle collection of high scores
894 * @property int $maxhighscores Number of high scores to limit to
895 * @property int $available Timestamp of when this lesson becomes available
896 * @property int $deadline Timestamp of when this lesson is no longer available
897 * @property int $timemodified Timestamp when lesson was last modified
899 * These properties are calculated
900 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
901 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
903 * @copyright 2009 Sam Hemelryk
904 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
906 class lesson extends lesson_base {
909 * The id of the first page (where prevpageid = 0) gets set and retrieved by
910 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
911 * @var int
913 protected $firstpageid = null;
915 * The id of the last page (where nextpageid = 0) gets set and retrieved by
916 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
917 * @var int
919 protected $lastpageid = null;
921 * An array used to cache the pages associated with this lesson after the first
922 * time they have been loaded.
923 * A note to developers: If you are going to be working with MORE than one or
924 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
925 * in order to save excess database queries.
926 * @var array An array of lesson_page objects
928 protected $pages = array();
930 * Flag that gets set to true once all of the pages associated with the lesson
931 * have been loaded.
932 * @var bool
934 protected $loadedallpages = false;
937 * Simply generates a lesson object given an array/object of properties
938 * Overrides {@see lesson_base->create()}
939 * @static
940 * @param object|array $properties
941 * @return lesson
943 public static function create($properties) {
944 return new lesson($properties);
948 * Generates a lesson object from the database given its id
949 * @static
950 * @param int $lessonid
951 * @return lesson
953 public static function load($lessonid) {
954 global $DB;
956 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
957 print_error('invalidcoursemodule');
959 return new lesson($lesson);
963 * Deletes this lesson from the database
965 public function delete() {
966 global $CFG, $DB;
967 require_once($CFG->libdir.'/gradelib.php');
968 require_once($CFG->dirroot.'/calendar/lib.php');
970 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
971 $context = context_module::instance($cm->id);
973 $DB->delete_records("lesson", array("id"=>$this->properties->id));
974 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
975 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
976 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
977 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
978 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
979 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
980 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
981 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
982 foreach($events as $event) {
983 $event = calendar_event::load($event);
984 $event->delete();
988 // Delete files associated with this module.
989 $fs = get_file_storage();
990 $fs->delete_area_files($context->id);
992 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
993 return true;
997 * Fetches messages from the session that may have been set in previous page
998 * actions.
1000 * <code>
1001 * // Do not call this method directly instead use
1002 * $lesson->messages;
1003 * </code>
1005 * @return array
1007 protected function get_messages() {
1008 global $SESSION;
1010 $messages = array();
1011 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1012 $messages = $SESSION->lesson_messages[$this->properties->id];
1013 unset($SESSION->lesson_messages[$this->properties->id]);
1016 return $messages;
1020 * Get all of the attempts for the current user.
1022 * @param int $retries
1023 * @param bool $correct Optional: only fetch correct attempts
1024 * @param int $pageid Optional: only fetch attempts at the given page
1025 * @param int $userid Optional: defaults to the current user if not set
1026 * @return array|false
1028 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1029 global $USER, $DB;
1030 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1031 if ($correct) {
1032 $params['correct'] = 1;
1034 if ($pageid !== null) {
1035 $params['pageid'] = $pageid;
1037 if ($userid === null) {
1038 $params['userid'] = $USER->id;
1040 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1044 * Returns the first page for the lesson or false if there isn't one.
1046 * This method should be called via the magic method __get();
1047 * <code>
1048 * $firstpage = $lesson->firstpage;
1049 * </code>
1051 * @return lesson_page|bool Returns the lesson_page specialised object or false
1053 protected function get_firstpage() {
1054 $pages = $this->load_all_pages();
1055 if (count($pages) > 0) {
1056 foreach ($pages as $page) {
1057 if ((int)$page->prevpageid === 0) {
1058 return $page;
1062 return false;
1066 * Returns the last page for the lesson or false if there isn't one.
1068 * This method should be called via the magic method __get();
1069 * <code>
1070 * $lastpage = $lesson->lastpage;
1071 * </code>
1073 * @return lesson_page|bool Returns the lesson_page specialised object or false
1075 protected function get_lastpage() {
1076 $pages = $this->load_all_pages();
1077 if (count($pages) > 0) {
1078 foreach ($pages as $page) {
1079 if ((int)$page->nextpageid === 0) {
1080 return $page;
1084 return false;
1088 * Returns the id of the first page of this lesson. (prevpageid = 0)
1089 * @return int
1091 protected function get_firstpageid() {
1092 global $DB;
1093 if ($this->firstpageid == null) {
1094 if (!$this->loadedallpages) {
1095 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1096 if (!$firstpageid) {
1097 print_error('cannotfindfirstpage', 'lesson');
1099 $this->firstpageid = $firstpageid;
1100 } else {
1101 $firstpage = $this->get_firstpage();
1102 $this->firstpageid = $firstpage->id;
1105 return $this->firstpageid;
1109 * Returns the id of the last page of this lesson. (nextpageid = 0)
1110 * @return int
1112 public function get_lastpageid() {
1113 global $DB;
1114 if ($this->lastpageid == null) {
1115 if (!$this->loadedallpages) {
1116 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1117 if (!$lastpageid) {
1118 print_error('cannotfindlastpage', 'lesson');
1120 $this->lastpageid = $lastpageid;
1121 } else {
1122 $lastpageid = $this->get_lastpage();
1123 $this->lastpageid = $lastpageid->id;
1127 return $this->lastpageid;
1131 * Gets the next page id to display after the one that is provided.
1132 * @param int $nextpageid
1133 * @return bool
1135 public function get_next_page($nextpageid) {
1136 global $USER, $DB;
1137 $allpages = $this->load_all_pages();
1138 if ($this->properties->nextpagedefault) {
1139 // in Flash Card mode...first get number of retakes
1140 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1141 shuffle($allpages);
1142 $found = false;
1143 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1144 foreach ($allpages as $nextpage) {
1145 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1146 $found = true;
1147 break;
1150 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1151 foreach ($allpages as $nextpage) {
1152 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1153 $found = true;
1154 break;
1158 if ($found) {
1159 if ($this->properties->maxpages) {
1160 // check number of pages viewed (in the lesson)
1161 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1162 return LESSON_EOL;
1165 return $nextpage->id;
1168 // In a normal lesson mode
1169 foreach ($allpages as $nextpage) {
1170 if ((int)$nextpage->id === (int)$nextpageid) {
1171 return $nextpage->id;
1174 return LESSON_EOL;
1178 * Sets a message against the session for this lesson that will displayed next
1179 * time the lesson processes messages
1181 * @param string $message
1182 * @param string $class
1183 * @param string $align
1184 * @return bool
1186 public function add_message($message, $class="notifyproblem", $align='center') {
1187 global $SESSION;
1189 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1190 $SESSION->lesson_messages = array();
1191 $SESSION->lesson_messages[$this->properties->id] = array();
1192 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1193 $SESSION->lesson_messages[$this->properties->id] = array();
1196 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1198 return true;
1202 * Check if the lesson is accessible at the present time
1203 * @return bool True if the lesson is accessible, false otherwise
1205 public function is_accessible() {
1206 $available = $this->properties->available;
1207 $deadline = $this->properties->deadline;
1208 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1212 * Starts the lesson time for the current user
1213 * @return bool Returns true
1215 public function start_timer() {
1216 global $USER, $DB;
1218 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1219 false, MUST_EXIST);
1221 // Trigger lesson started event.
1222 $event = \mod_lesson\event\lesson_started::create(array(
1223 'objectid' => $this->properties()->id,
1224 'context' => context_module::instance($cm->id),
1225 'courseid' => $this->properties()->course
1227 $event->trigger();
1229 $USER->startlesson[$this->properties->id] = true;
1230 $startlesson = new stdClass;
1231 $startlesson->lessonid = $this->properties->id;
1232 $startlesson->userid = $USER->id;
1233 $startlesson->starttime = time();
1234 $startlesson->lessontime = time();
1235 $DB->insert_record('lesson_timer', $startlesson);
1236 if ($this->properties->timed) {
1237 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties->maxtime), 'center');
1239 return true;
1243 * Updates the timer to the current time and returns the new timer object
1244 * @param bool $restart If set to true the timer is restarted
1245 * @param bool $continue If set to true AND $restart=true then the timer
1246 * will continue from a previous attempt
1247 * @return stdClass The new timer
1249 public function update_timer($restart=false, $continue=false) {
1250 global $USER, $DB;
1251 // clock code
1252 // get time information for this user
1253 $params = array("lessonid" => $this->properties->id, "userid" => $USER->id);
1254 if (!$timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1)) {
1255 $this->start_timer();
1256 $timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1);
1258 $timer = current($timer); // This will get the latest start time record.
1260 if ($restart) {
1261 if ($continue) {
1262 // continue a previous test, need to update the clock (think this option is disabled atm)
1263 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1264 } else {
1265 // starting over, so reset the clock
1266 $timer->starttime = time();
1270 $timer->lessontime = time();
1271 $DB->update_record('lesson_timer', $timer);
1272 return $timer;
1276 * Updates the timer to the current time then stops it by unsetting the user var
1277 * @return bool Returns true
1279 public function stop_timer() {
1280 global $USER, $DB;
1281 unset($USER->startlesson[$this->properties->id]);
1283 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1284 false, MUST_EXIST);
1286 // Trigger lesson ended event.
1287 $event = \mod_lesson\event\lesson_ended::create(array(
1288 'objectid' => $this->properties()->id,
1289 'context' => context_module::instance($cm->id),
1290 'courseid' => $this->properties()->course
1292 $event->trigger();
1294 return $this->update_timer(false, false);
1298 * Checks to see if the lesson has pages
1300 public function has_pages() {
1301 global $DB;
1302 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1303 return ($pagecount>0);
1307 * Returns the link for the related activity
1308 * @return array|false
1310 public function link_for_activitylink() {
1311 global $DB;
1312 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1313 if ($module) {
1314 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1315 if ($modname) {
1316 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1317 if ($instancename) {
1318 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1319 get_string('activitylinkname', 'lesson', $instancename),
1320 array('class'=>'centerpadded lessonbutton standardbutton'));
1324 return '';
1328 * Loads the requested page.
1330 * This function will return the requested page id as either a specialised
1331 * lesson_page object OR as a generic lesson_page.
1332 * If the page has been loaded previously it will be returned from the pages
1333 * array, otherwise it will be loaded from the database first
1335 * @param int $pageid
1336 * @return lesson_page A lesson_page object or an object that extends it
1338 public function load_page($pageid) {
1339 if (!array_key_exists($pageid, $this->pages)) {
1340 $manager = lesson_page_type_manager::get($this);
1341 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1343 return $this->pages[$pageid];
1347 * Loads ALL of the pages for this lesson
1349 * @return array An array containing all pages from this lesson
1351 public function load_all_pages() {
1352 if (!$this->loadedallpages) {
1353 $manager = lesson_page_type_manager::get($this);
1354 $this->pages = $manager->load_all_pages($this);
1355 $this->loadedallpages = true;
1357 return $this->pages;
1361 * Determines if a jumpto value is correct or not.
1363 * returns true if jumpto page is (logically) after the pageid page or
1364 * if the jumpto value is a special value. Returns false in all other cases.
1366 * @param int $pageid Id of the page from which you are jumping from.
1367 * @param int $jumpto The jumpto number.
1368 * @return boolean True or false after a series of tests.
1370 public function jumpto_is_correct($pageid, $jumpto) {
1371 global $DB;
1373 // first test the special values
1374 if (!$jumpto) {
1375 // same page
1376 return false;
1377 } elseif ($jumpto == LESSON_NEXTPAGE) {
1378 return true;
1379 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1380 return true;
1381 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1382 return true;
1383 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1384 return true;
1385 } elseif ($jumpto == LESSON_EOL) {
1386 return true;
1389 $pages = $this->load_all_pages();
1390 $apageid = $pages[$pageid]->nextpageid;
1391 while ($apageid != 0) {
1392 if ($jumpto == $apageid) {
1393 return true;
1395 $apageid = $pages[$apageid]->nextpageid;
1397 return false;
1401 * Returns the time a user has remaining on this lesson
1402 * @param int $starttime Starttime timestamp
1403 * @return string
1405 public function time_remaining($starttime) {
1406 $timeleft = $starttime + $this->maxtime * 60 - time();
1407 $hours = floor($timeleft/3600);
1408 $timeleft = $timeleft - ($hours * 3600);
1409 $minutes = floor($timeleft/60);
1410 $secs = $timeleft - ($minutes * 60);
1412 if ($minutes < 10) {
1413 $minutes = "0$minutes";
1415 if ($secs < 10) {
1416 $secs = "0$secs";
1418 $output = array();
1419 $output[] = $hours;
1420 $output[] = $minutes;
1421 $output[] = $secs;
1422 $output = implode(':', $output);
1423 return $output;
1427 * Interprets LESSON_CLUSTERJUMP jumpto value.
1429 * This will select a page randomly
1430 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1431 * and the page selected will be a page that has not been viewed already
1432 * and if any pages are within a branch table or end of branch then only 1 page within
1433 * the branch table or end of branch will be randomly selected (sub clustering).
1435 * @param int $pageid Id of the current page from which we are jumping from.
1436 * @param int $userid Id of the user.
1437 * @return int The id of the next page.
1439 public function cluster_jump($pageid, $userid=null) {
1440 global $DB, $USER;
1442 if ($userid===null) {
1443 $userid = $USER->id;
1445 // get the number of retakes
1446 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1447 $retakes = 0;
1449 // get all the lesson_attempts aka what the user has seen
1450 $seenpages = array();
1451 if ($attempts = $this->get_attempts($retakes)) {
1452 foreach ($attempts as $attempt) {
1453 $seenpages[$attempt->pageid] = $attempt->pageid;
1458 // get the lesson pages
1459 $lessonpages = $this->load_all_pages();
1460 // find the start of the cluster
1461 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1462 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1463 break;
1465 $pageid = $lessonpages[$pageid]->prevpageid;
1468 $clusterpages = array();
1469 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1470 $unseen = array();
1471 foreach ($clusterpages as $key=>$cluster) {
1472 // Remove the page if it is in a branch table or is an endofbranch.
1473 if ($this->is_sub_page_of_type($cluster->id,
1474 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
1475 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1476 unset($clusterpages[$key]);
1477 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
1478 // If branchtable, check to see if any pages inside have been viewed.
1479 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1480 $flag = true;
1481 foreach ($branchpages as $branchpage) {
1482 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
1483 $flag = false;
1486 if ($flag && count($branchpages) > 0) {
1487 // Add branch table.
1488 $unseen[] = $cluster;
1490 } elseif ($cluster->is_unseen($seenpages)) {
1491 $unseen[] = $cluster;
1495 if (count($unseen) > 0) {
1496 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1497 $nextpage = $unseen[rand(0, count($unseen)-1)];
1498 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1499 // if branch table, then pick a random page inside of it
1500 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1501 return $branchpages[rand(0, count($branchpages)-1)]->id;
1502 } else { // otherwise, return the page's id
1503 return $nextpage->id;
1505 } else {
1506 // seen all there is to see, leave the cluster
1507 if (end($clusterpages)->nextpageid == 0) {
1508 return LESSON_EOL;
1509 } else {
1510 $clusterendid = $pageid;
1511 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
1512 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1513 break;
1515 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1517 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1518 if ($exitjump == LESSON_NEXTPAGE) {
1519 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1521 if ($exitjump == 0) {
1522 return LESSON_EOL;
1523 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1524 return $exitjump;
1525 } else {
1526 if (!array_key_exists($exitjump, $lessonpages)) {
1527 $found = false;
1528 foreach ($lessonpages as $page) {
1529 if ($page->id === $clusterendid) {
1530 $found = true;
1531 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1532 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1533 if ($exitjump == LESSON_NEXTPAGE) {
1534 $exitjump = $lessonpages[$page->id]->nextpageid;
1536 break;
1540 if (!array_key_exists($exitjump, $lessonpages)) {
1541 return LESSON_EOL;
1543 return $exitjump;
1550 * Finds all pages that appear to be a subtype of the provided pageid until
1551 * an end point specified within $ends is encountered or no more pages exist
1553 * @param int $pageid
1554 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1555 * the subtype
1556 * @return array An array of specialised lesson_page objects
1558 public function get_sub_pages_of($pageid, array $ends) {
1559 $lessonpages = $this->load_all_pages();
1560 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1561 $pages = array();
1563 while (true) {
1564 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1565 break;
1567 $pages[] = $lessonpages[$pageid];
1568 $pageid = $lessonpages[$pageid]->nextpageid;
1571 return $pages;
1575 * Checks to see if the specified page[id] is a subpage of a type specified in
1576 * the $types array, until either there are no more pages of we find a type
1577 * corresponding to that of a type specified in $ends
1579 * @param int $pageid The id of the page to check
1580 * @param array $types An array of types that would signify this page was a subpage
1581 * @param array $ends An array of types that mean this is not a subpage
1582 * @return bool
1584 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1585 $pages = $this->load_all_pages();
1586 $pageid = $pages[$pageid]->prevpageid; // move up one
1588 array_unshift($ends, 0);
1589 // go up the pages till branch table
1590 while (true) {
1591 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1592 return false;
1593 } else if (in_array($pages[$pageid]->qtype, $types)) {
1594 return true;
1596 $pageid = $pages[$pageid]->prevpageid;
1603 * Abstract class to provide a core functions to the all lesson classes
1605 * This class should be abstracted by ALL classes with the lesson module to ensure
1606 * that all classes within this module can be interacted with in the same way.
1608 * This class provides the user with a basic properties array that can be fetched
1609 * or set via magic methods, or alternatively by defining methods get_blah() or
1610 * set_blah() within the extending object.
1612 * @copyright 2009 Sam Hemelryk
1613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1615 abstract class lesson_base {
1618 * An object containing properties
1619 * @var stdClass
1621 protected $properties;
1624 * The constructor
1625 * @param stdClass $properties
1627 public function __construct($properties) {
1628 $this->properties = (object)$properties;
1632 * Magic property method
1634 * Attempts to call a set_$key method if one exists otherwise falls back
1635 * to simply set the property
1637 * @param string $key
1638 * @param mixed $value
1640 public function __set($key, $value) {
1641 if (method_exists($this, 'set_'.$key)) {
1642 $this->{'set_'.$key}($value);
1644 $this->properties->{$key} = $value;
1648 * Magic get method
1650 * Attempts to call a get_$key method to return the property and ralls over
1651 * to return the raw property
1653 * @param str $key
1654 * @return mixed
1656 public function __get($key) {
1657 if (method_exists($this, 'get_'.$key)) {
1658 return $this->{'get_'.$key}();
1660 return $this->properties->{$key};
1664 * Stupid PHP needs an isset magic method if you use the get magic method and
1665 * still want empty calls to work.... blah ~!
1667 * @param string $key
1668 * @return bool
1670 public function __isset($key) {
1671 if (method_exists($this, 'get_'.$key)) {
1672 $val = $this->{'get_'.$key}();
1673 return !empty($val);
1675 return !empty($this->properties->{$key});
1678 //NOTE: E_STRICT does not allow to change function signature!
1681 * If implemented should create a new instance, save it in the DB and return it
1683 //public static function create() {}
1685 * If implemented should load an instance from the DB and return it
1687 //public static function load() {}
1689 * Fetches all of the properties of the object
1690 * @return stdClass
1692 public function properties() {
1693 return $this->properties;
1699 * Abstract class representation of a page associated with a lesson.
1701 * This class should MUST be extended by all specialised page types defined in
1702 * mod/lesson/pagetypes/.
1703 * There are a handful of abstract methods that need to be defined as well as
1704 * severl methods that can optionally be defined in order to make the page type
1705 * operate in the desired way
1707 * Database properties
1708 * @property int $id The id of this lesson page
1709 * @property int $lessonid The id of the lesson this page belongs to
1710 * @property int $prevpageid The id of the page before this one
1711 * @property int $nextpageid The id of the next page in the page sequence
1712 * @property int $qtype Identifies the page type of this page
1713 * @property int $qoption Used to record page type specific options
1714 * @property int $layout Used to record page specific layout selections
1715 * @property int $display Used to record page specific display selections
1716 * @property int $timecreated Timestamp for when the page was created
1717 * @property int $timemodified Timestamp for when the page was last modified
1718 * @property string $title The title of this page
1719 * @property string $contents The rich content shown to describe the page
1720 * @property int $contentsformat The format of the contents field
1722 * Calculated properties
1723 * @property-read array $answers An array of answers for this page
1724 * @property-read bool $displayinmenublock Toggles display in the left menu block
1725 * @property-read array $jumps An array containing all the jumps this page uses
1726 * @property-read lesson $lesson The lesson this page belongs to
1727 * @property-read int $type The type of the page [question | structure]
1728 * @property-read typeid The unique identifier for the page type
1729 * @property-read typestring The string that describes this page type
1731 * @abstract
1732 * @copyright 2009 Sam Hemelryk
1733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1735 abstract class lesson_page extends lesson_base {
1738 * A reference to the lesson this page belongs to
1739 * @var lesson
1741 protected $lesson = null;
1743 * Contains the answers to this lesson_page once loaded
1744 * @var null|array
1746 protected $answers = null;
1748 * This sets the type of the page, can be one of the constants defined below
1749 * @var int
1751 protected $type = 0;
1754 * Constants used to identify the type of the page
1756 const TYPE_QUESTION = 0;
1757 const TYPE_STRUCTURE = 1;
1760 * This method should return the integer used to identify the page type within
1761 * the database and throughout code. This maps back to the defines used in 1.x
1762 * @abstract
1763 * @return int
1765 abstract protected function get_typeid();
1767 * This method should return the string that describes the pagetype
1768 * @abstract
1769 * @return string
1771 abstract protected function get_typestring();
1774 * This method gets called to display the page to the user taking the lesson
1775 * @abstract
1776 * @param object $renderer
1777 * @param object $attempt
1778 * @return string
1780 abstract public function display($renderer, $attempt);
1783 * Creates a new lesson_page within the database and returns the correct pagetype
1784 * object to use to interact with the new lesson
1786 * @final
1787 * @static
1788 * @param object $properties
1789 * @param lesson $lesson
1790 * @return lesson_page Specialised object that extends lesson_page
1792 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
1793 global $DB;
1794 $newpage = new stdClass;
1795 $newpage->title = $properties->title;
1796 $newpage->contents = $properties->contents_editor['text'];
1797 $newpage->contentsformat = $properties->contents_editor['format'];
1798 $newpage->lessonid = $lesson->id;
1799 $newpage->timecreated = time();
1800 $newpage->qtype = $properties->qtype;
1801 $newpage->qoption = (isset($properties->qoption))?1:0;
1802 $newpage->layout = (isset($properties->layout))?1:0;
1803 $newpage->display = (isset($properties->display))?1:0;
1804 $newpage->prevpageid = 0; // this is a first page
1805 $newpage->nextpageid = 0; // this is the only page
1807 if ($properties->pageid) {
1808 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
1809 if (!$prevpage) {
1810 print_error('cannotfindpages', 'lesson');
1812 $newpage->prevpageid = $prevpage->id;
1813 $newpage->nextpageid = $prevpage->nextpageid;
1814 } else {
1815 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
1816 if ($nextpage) {
1817 // This is the first page, there are existing pages put this at the start
1818 $newpage->nextpageid = $nextpage->id;
1822 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
1824 $editor = new stdClass;
1825 $editor->id = $newpage->id;
1826 $editor->contents_editor = $properties->contents_editor;
1827 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
1828 $DB->update_record("lesson_pages", $editor);
1830 if ($newpage->prevpageid > 0) {
1831 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
1833 if ($newpage->nextpageid > 0) {
1834 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
1837 $page = lesson_page::load($newpage, $lesson);
1838 $page->create_answers($properties);
1840 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
1842 return $page;
1846 * This method loads a page object from the database and returns it as a
1847 * specialised object that extends lesson_page
1849 * @final
1850 * @static
1851 * @param int $id
1852 * @param lesson $lesson
1853 * @return lesson_page Specialised lesson_page object
1855 final public static function load($id, lesson $lesson) {
1856 global $DB;
1858 if (is_object($id) && !empty($id->qtype)) {
1859 $page = $id;
1860 } else {
1861 $page = $DB->get_record("lesson_pages", array("id" => $id));
1862 if (!$page) {
1863 print_error('cannotfindpages', 'lesson');
1866 $manager = lesson_page_type_manager::get($lesson);
1868 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
1869 if (!class_exists($class)) {
1870 $class = 'lesson_page';
1873 return new $class($page, $lesson);
1877 * Deletes a lesson_page from the database as well as any associated records.
1878 * @final
1879 * @return bool
1881 final public function delete() {
1882 global $DB;
1883 // first delete all the associated records...
1884 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
1886 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
1887 // ...now delete the answers...
1888 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
1889 // ..and the page itself
1890 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
1892 // Delete files associated with this page.
1893 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
1894 $context = context_module::instance($cm->id);
1895 $fs = get_file_storage();
1896 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
1898 // repair the hole in the linkage
1899 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
1900 //This is the only page, no repair needed
1901 } elseif (!$this->properties->prevpageid) {
1902 // this is the first page...
1903 $page = $this->lesson->load_page($this->properties->nextpageid);
1904 $page->move(null, 0);
1905 } elseif (!$this->properties->nextpageid) {
1906 // this is the last page...
1907 $page = $this->lesson->load_page($this->properties->prevpageid);
1908 $page->move(0);
1909 } else {
1910 // page is in the middle...
1911 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
1912 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
1914 $prevpage->move($nextpage->id);
1915 $nextpage->move(null, $prevpage->id);
1917 return true;
1921 * Moves a page by updating its nextpageid and prevpageid values within
1922 * the database
1924 * @final
1925 * @param int $nextpageid
1926 * @param int $prevpageid
1928 final public function move($nextpageid=null, $prevpageid=null) {
1929 global $DB;
1930 if ($nextpageid === null) {
1931 $nextpageid = $this->properties->nextpageid;
1933 if ($prevpageid === null) {
1934 $prevpageid = $this->properties->prevpageid;
1936 $obj = new stdClass;
1937 $obj->id = $this->properties->id;
1938 $obj->prevpageid = $prevpageid;
1939 $obj->nextpageid = $nextpageid;
1940 $DB->update_record('lesson_pages', $obj);
1944 * Returns the answers that are associated with this page in the database
1946 * @final
1947 * @return array
1949 final public function get_answers() {
1950 global $DB;
1951 if ($this->answers === null) {
1952 $this->answers = array();
1953 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
1954 if (!$answers) {
1955 // It is possible that a lesson upgraded from Moodle 1.9 still
1956 // contains questions without any answers [MDL-25632].
1957 // debugging(get_string('cannotfindanswer', 'lesson'));
1958 return array();
1960 foreach ($answers as $answer) {
1961 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
1964 return $this->answers;
1968 * Returns the lesson this page is associated with
1969 * @final
1970 * @return lesson
1972 final protected function get_lesson() {
1973 return $this->lesson;
1977 * Returns the type of page this is. Not to be confused with page type
1978 * @final
1979 * @return int
1981 final protected function get_type() {
1982 return $this->type;
1986 * Records an attempt at this page
1988 * @final
1989 * @global moodle_database $DB
1990 * @param stdClass $context
1991 * @return stdClass Returns the result of the attempt
1993 final public function record_attempt($context) {
1994 global $DB, $USER, $OUTPUT;
1997 * This should be overridden by each page type to actually check the response
1998 * against what ever custom criteria they have defined
2000 $result = $this->check_answer();
2002 $result->attemptsremaining = 0;
2003 $result->maxattemptsreached = false;
2005 if ($result->noanswer) {
2006 $result->newpageid = $this->properties->id; // display same page again
2007 $result->feedback = get_string('noanswer', 'lesson');
2008 } else {
2009 if (!has_capability('mod/lesson:manage', $context)) {
2010 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2012 // Get the number of attempts that have been made on this question for this student and retake,
2013 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
2014 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
2016 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
2017 if ($nattempts >= $this->lesson->maxattempts) {
2018 $result->maxattemptsreached = true;
2019 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
2020 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2021 return $result;
2024 // record student's attempt
2025 $attempt = new stdClass;
2026 $attempt->lessonid = $this->lesson->id;
2027 $attempt->pageid = $this->properties->id;
2028 $attempt->userid = $USER->id;
2029 $attempt->answerid = $result->answerid;
2030 $attempt->retry = $nretakes;
2031 $attempt->correct = $result->correctanswer;
2032 if($result->userresponse !== null) {
2033 $attempt->useranswer = $result->userresponse;
2036 $attempt->timeseen = time();
2037 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
2038 $userisreviewing = false;
2039 if (isset($USER->modattempts[$this->lesson->id])) {
2040 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
2041 $userisreviewing = true;
2044 // Only insert a record if we are not reviewing the lesson.
2045 if (!$userisreviewing) {
2046 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
2047 $DB->insert_record("lesson_attempts", $attempt);
2049 // Increase the number of attempts made.
2050 $nattempts++;
2053 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
2054 // displaying of message(s) is at the end of page for more ergonomic display
2055 if (!$result->correctanswer && ($result->newpageid == 0)) {
2056 // retreive the number of attempts left counter for displaying at bottom of feedback page
2057 if ($nattempts >= $this->lesson->maxattempts) {
2058 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2059 $result->maxattemptsreached = true;
2061 $result->newpageid = LESSON_NEXTPAGE;
2062 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2063 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
2067 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
2068 if ($result->newpageid == 0) {
2069 $result->newpageid = $this->properties->id;
2070 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
2071 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2074 // Determine default feedback if necessary
2075 if (empty($result->response)) {
2076 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2077 // These conditions have been met:
2078 // 1. The lesson manager has not supplied feedback to the student
2079 // 2. Not displaying default feedback
2080 // 3. The user did provide an answer
2081 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2083 $result->nodefaultresponse = true; // This will cause a redirect below
2084 } else if ($result->isessayquestion) {
2085 $result->response = get_string('defaultessayresponse', 'lesson');
2086 } else if ($result->correctanswer) {
2087 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2088 } else {
2089 $result->response = get_string('thatsthewronganswer', 'lesson');
2093 if ($result->response) {
2094 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2095 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2096 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2097 if ($qattempts == 1) {
2098 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2099 } else {
2100 $result->feedback = $OUTPUT->BOX(get_string("secondpluswrong", "lesson"), 'feedback');
2102 } else {
2103 $class = 'response';
2104 if ($result->correctanswer) {
2105 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2106 } else if (!$result->isessayquestion) {
2107 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2109 $options = new stdClass;
2110 $options->noclean = true;
2111 $options->para = true;
2112 $options->overflowdiv = true;
2113 $options->context = $context;
2114 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
2115 'mod_lesson', 'page_responses', $result->answerid);
2116 $result->feedback = $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 'generalbox boxaligncenter');
2117 if (isset($result->studentanswerformat)) {
2118 // This is the student's answer so it should be cleaned.
2119 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
2120 array('context' => $context, 'para' => true));
2121 } else {
2122 $studentanswer = format_string($result->studentanswer);
2124 $result->feedback .= '<div class="correctanswer generalbox"><em>'
2125 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
2126 $result->feedback .= $OUTPUT->box($result->response, $class); // Already converted to HTML.
2127 $result->feedback .= '</div>';
2132 return $result;
2136 * Returns the string for a jump name
2138 * @final
2139 * @param int $jumpto Jump code or page ID
2140 * @return string
2142 final protected function get_jump_name($jumpto) {
2143 global $DB;
2144 static $jumpnames = array();
2146 if (!array_key_exists($jumpto, $jumpnames)) {
2147 if ($jumpto == LESSON_THISPAGE) {
2148 $jumptitle = get_string('thispage', 'lesson');
2149 } elseif ($jumpto == LESSON_NEXTPAGE) {
2150 $jumptitle = get_string('nextpage', 'lesson');
2151 } elseif ($jumpto == LESSON_EOL) {
2152 $jumptitle = get_string('endoflesson', 'lesson');
2153 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2154 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2155 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2156 $jumptitle = get_string('previouspage', 'lesson');
2157 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2158 $jumptitle = get_string('randompageinbranch', 'lesson');
2159 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2160 $jumptitle = get_string('randombranch', 'lesson');
2161 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2162 $jumptitle = get_string('clusterjump', 'lesson');
2163 } else {
2164 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2165 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2168 $jumpnames[$jumpto] = format_string($jumptitle,true);
2171 return $jumpnames[$jumpto];
2175 * Constructor method
2176 * @param object $properties
2177 * @param lesson $lesson
2179 public function __construct($properties, lesson $lesson) {
2180 parent::__construct($properties);
2181 $this->lesson = $lesson;
2185 * Returns the score for the attempt
2186 * This may be overridden by page types that require manual grading
2187 * @param array $answers
2188 * @param object $attempt
2189 * @return int
2191 public function earned_score($answers, $attempt) {
2192 return $answers[$attempt->answerid]->score;
2196 * This is a callback method that can be override and gets called when ever a page
2197 * is viewed
2199 * @param bool $canmanage True if the user has the manage cap
2200 * @return mixed
2202 public function callback_on_view($canmanage) {
2203 return true;
2207 * Updates a lesson page and its answers within the database
2209 * @param object $properties
2210 * @return bool
2212 public function update($properties, $context = null, $maxbytes = null) {
2213 global $DB, $PAGE;
2214 $answers = $this->get_answers();
2215 $properties->id = $this->properties->id;
2216 $properties->lessonid = $this->lesson->id;
2217 if (empty($properties->qoption)) {
2218 $properties->qoption = '0';
2220 if (empty($context)) {
2221 $context = $PAGE->context;
2223 if ($maxbytes === null) {
2224 $maxbytes = get_user_max_upload_file_size($context);
2226 $properties->timemodified = time();
2227 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2228 $DB->update_record("lesson_pages", $properties);
2229 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
2230 if (count($answers) > 1) {
2231 $answer = array_shift($answers);
2232 foreach ($answers as $a) {
2233 $DB->delete_record('lesson_answers', array('id' => $a->id));
2235 } else if (count($answers) == 1) {
2236 $answer = array_shift($answers);
2237 } else {
2238 $answer = new stdClass;
2239 $answer->lessonid = $properties->lessonid;
2240 $answer->pageid = $properties->id;
2241 $answer->timecreated = time();
2244 $answer->timemodified = time();
2245 if (isset($properties->jumpto[0])) {
2246 $answer->jumpto = $properties->jumpto[0];
2248 if (isset($properties->score[0])) {
2249 $answer->score = $properties->score[0];
2251 if (!empty($answer->id)) {
2252 $DB->update_record("lesson_answers", $answer->properties());
2253 } else {
2254 $DB->insert_record("lesson_answers", $answer);
2256 } else {
2257 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2258 if (!array_key_exists($i, $this->answers)) {
2259 $this->answers[$i] = new stdClass;
2260 $this->answers[$i]->lessonid = $this->lesson->id;
2261 $this->answers[$i]->pageid = $this->id;
2262 $this->answers[$i]->timecreated = $this->timecreated;
2265 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2266 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2267 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2269 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2270 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2271 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
2274 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
2275 if (isset($properties->jumpto[$i])) {
2276 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2278 if ($this->lesson->custom && isset($properties->score[$i])) {
2279 $this->answers[$i]->score = $properties->score[$i];
2281 if (!isset($this->answers[$i]->id)) {
2282 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2283 } else {
2284 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2287 } else if (isset($this->answers[$i]->id)) {
2288 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
2289 unset($this->answers[$i]);
2293 return true;
2297 * Can be set to true if the page requires a static link to create a new instance
2298 * instead of simply being included in the dropdown
2299 * @param int $previd
2300 * @return bool
2302 public function add_page_link($previd) {
2303 return false;
2307 * Returns true if a page has been viewed before
2309 * @param array|int $param Either an array of pages that have been seen or the
2310 * number of retakes a user has had
2311 * @return bool
2313 public function is_unseen($param) {
2314 global $USER, $DB;
2315 if (is_array($param)) {
2316 $seenpages = $param;
2317 return (!array_key_exists($this->properties->id, $seenpages));
2318 } else {
2319 $nretakes = $param;
2320 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2321 return true;
2324 return false;
2328 * Checks to see if a page has been answered previously
2329 * @param int $nretakes
2330 * @return bool
2332 public function is_unanswered($nretakes) {
2333 global $DB, $USER;
2334 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2335 return true;
2337 return false;
2341 * Creates answers within the database for this lesson_page. Usually only ever
2342 * called when creating a new page instance
2343 * @param object $properties
2344 * @return array
2346 public function create_answers($properties) {
2347 global $DB;
2348 // now add the answers
2349 $newanswer = new stdClass;
2350 $newanswer->lessonid = $this->lesson->id;
2351 $newanswer->pageid = $this->properties->id;
2352 $newanswer->timecreated = $this->properties->timecreated;
2354 $answers = array();
2356 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2357 $answer = clone($newanswer);
2359 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2360 $answer->answer = $properties->answer_editor[$i]['text'];
2361 $answer->answerformat = $properties->answer_editor[$i]['format'];
2363 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2364 $answer->response = $properties->response_editor[$i]['text'];
2365 $answer->responseformat = $properties->response_editor[$i]['format'];
2368 if (isset($answer->answer) && $answer->answer != '') {
2369 if (isset($properties->jumpto[$i])) {
2370 $answer->jumpto = $properties->jumpto[$i];
2372 if ($this->lesson->custom && isset($properties->score[$i])) {
2373 $answer->score = $properties->score[$i];
2375 $answer->id = $DB->insert_record("lesson_answers", $answer);
2376 $answers[$answer->id] = new lesson_page_answer($answer);
2377 } else {
2378 break;
2382 $this->answers = $answers;
2383 return $answers;
2387 * This method MUST be overridden by all question page types, or page types that
2388 * wish to score a page.
2390 * The structure of result should always be the same so it is a good idea when
2391 * overriding this method on a page type to call
2392 * <code>
2393 * $result = parent::check_answer();
2394 * </code>
2395 * before modifying it as required.
2397 * @return stdClass
2399 public function check_answer() {
2400 $result = new stdClass;
2401 $result->answerid = 0;
2402 $result->noanswer = false;
2403 $result->correctanswer = false;
2404 $result->isessayquestion = false; // use this to turn off review button on essay questions
2405 $result->response = '';
2406 $result->newpageid = 0; // stay on the page
2407 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2408 $result->userresponse = null;
2409 $result->feedback = '';
2410 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2411 return $result;
2415 * True if the page uses a custom option
2417 * Should be override and set to true if the page uses a custom option.
2419 * @return bool
2421 public function has_option() {
2422 return false;
2426 * Returns the maximum number of answers for this page given the maximum number
2427 * of answers permitted by the lesson.
2429 * @param int $default
2430 * @return int
2432 public function max_answers($default) {
2433 return $default;
2437 * Returns the properties of this lesson page as an object
2438 * @return stdClass;
2440 public function properties() {
2441 $properties = clone($this->properties);
2442 if ($this->answers === null) {
2443 $this->get_answers();
2445 if (count($this->answers)>0) {
2446 $count = 0;
2447 $qtype = $properties->qtype;
2448 foreach ($this->answers as $answer) {
2449 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
2450 if ($qtype != LESSON_PAGE_MATCHING) {
2451 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
2452 } else {
2453 $properties->{'response_editor['.$count.']'} = $answer->response;
2455 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2456 $properties->{'score['.$count.']'} = $answer->score;
2457 $count++;
2460 return $properties;
2464 * Returns an array of options to display when choosing the jumpto for a page/answer
2465 * @static
2466 * @param int $pageid
2467 * @param lesson $lesson
2468 * @return array
2470 public static function get_jumptooptions($pageid, lesson $lesson) {
2471 global $DB;
2472 $jump = array();
2473 $jump[0] = get_string("thispage", "lesson");
2474 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2475 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2476 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2478 if ($pageid == 0) {
2479 return $jump;
2482 $pages = $lesson->load_all_pages();
2483 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))) {
2484 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
2485 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
2487 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
2488 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
2490 if (!optional_param('firstpage', 0, PARAM_INT)) {
2491 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
2492 while (true) {
2493 if ($apageid) {
2494 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2495 $jump[$apageid] = strip_tags(format_string($title,true));
2496 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2497 } else {
2498 // last page reached
2499 break;
2503 return $jump;
2506 * Returns the contents field for the page properly formatted and with plugin
2507 * file url's converted
2508 * @return string
2510 public function get_contents() {
2511 global $PAGE;
2512 if (!empty($this->properties->contents)) {
2513 if (!isset($this->properties->contentsformat)) {
2514 $this->properties->contentsformat = FORMAT_HTML;
2516 $context = context_module::instance($PAGE->cm->id);
2517 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
2518 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
2519 return format_text($contents, $this->properties->contentsformat,
2520 array('context' => $context, 'noclean' => true,
2521 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
2522 } else {
2523 return '';
2528 * Set to true if this page should display in the menu block
2529 * @return bool
2531 protected function get_displayinmenublock() {
2532 return false;
2536 * Get the string that describes the options of this page type
2537 * @return string
2539 public function option_description_string() {
2540 return '';
2544 * Updates a table with the answers for this page
2545 * @param html_table $table
2546 * @return html_table
2548 public function display_answers(html_table $table) {
2549 $answers = $this->get_answers();
2550 $i = 1;
2551 foreach ($answers as $answer) {
2552 $cells = array();
2553 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2554 $cells[] = $this->get_jump_name($answer->jumpto);
2555 $table->data[] = new html_table_row($cells);
2556 if ($i === 1){
2557 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
2559 $i++;
2561 return $table;
2565 * Determines if this page should be grayed out on the management/report screens
2566 * @return int 0 or 1
2568 protected function get_grayout() {
2569 return 0;
2573 * Adds stats for this page to the &pagestats object. This should be defined
2574 * for all page types that grade
2575 * @param array $pagestats
2576 * @param int $tries
2577 * @return bool
2579 public function stats(array &$pagestats, $tries) {
2580 return true;
2584 * Formats the answers of this page for a report
2586 * @param object $answerpage
2587 * @param object $answerdata
2588 * @param object $useranswer
2589 * @param array $pagestats
2590 * @param int $i Count of first level answers
2591 * @param int $n Count of second level answers
2592 * @return object The answer page for this
2594 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2595 $answers = $this->get_answers();
2596 $formattextdefoptions = new stdClass;
2597 $formattextdefoptions->para = false; //I'll use it widely in this page
2598 foreach ($answers as $answer) {
2599 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
2600 $answerdata->answers[] = array($data, "");
2601 $answerpage->answerdata = $answerdata;
2603 return $answerpage;
2607 * Gets an array of the jumps used by the answers of this page
2609 * @return array
2611 public function get_jumps() {
2612 global $DB;
2613 $jumps = array();
2614 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
2615 if ($answers = $this->get_answers()) {
2616 foreach ($answers as $answer) {
2617 $jumps[] = $this->get_jump_name($answer->jumpto);
2619 } else {
2620 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
2622 return $jumps;
2625 * Informs whether this page type require manual grading or not
2626 * @return bool
2628 public function requires_manual_grading() {
2629 return false;
2633 * A callback method that allows a page to override the next page a user will
2634 * see during when this page is being completed.
2635 * @return false|int
2637 public function override_next_page() {
2638 return false;
2642 * This method is used to determine if this page is a valid page
2644 * @param array $validpages
2645 * @param array $pageviews
2646 * @return int The next page id to check
2648 public function valid_page_and_view(&$validpages, &$pageviews) {
2649 $validpages[$this->properties->id] = 1;
2650 return $this->properties->nextpageid;
2657 * Class used to represent an answer to a page
2659 * @property int $id The ID of this answer in the database
2660 * @property int $lessonid The ID of the lesson this answer belongs to
2661 * @property int $pageid The ID of the page this answer belongs to
2662 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2663 * @property int $grade The grade this answer is worth
2664 * @property int $score The score this answer will give
2665 * @property int $flags Used to store options for the answer
2666 * @property int $timecreated A timestamp of when the answer was created
2667 * @property int $timemodified A timestamp of when the answer was modified
2668 * @property string $answer The answer itself
2669 * @property string $response The response the user sees if selecting this answer
2671 * @copyright 2009 Sam Hemelryk
2672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2674 class lesson_page_answer extends lesson_base {
2677 * Loads an page answer from the DB
2679 * @param int $id
2680 * @return lesson_page_answer
2682 public static function load($id) {
2683 global $DB;
2684 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2685 return new lesson_page_answer($answer);
2689 * Given an object of properties and a page created answer(s) and saves them
2690 * in the database.
2692 * @param stdClass $properties
2693 * @param lesson_page $page
2694 * @return array
2696 public static function create($properties, lesson_page $page) {
2697 return $page->create_answers($properties);
2703 * A management class for page types
2705 * This class is responsible for managing the different pages. A manager object can
2706 * be retrieved by calling the following line of code:
2707 * <code>
2708 * $manager = lesson_page_type_manager::get($lesson);
2709 * </code>
2710 * The first time the page type manager is retrieved the it includes all of the
2711 * different page types located in mod/lesson/pagetypes.
2713 * @copyright 2009 Sam Hemelryk
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2716 class lesson_page_type_manager {
2719 * An array of different page type classes
2720 * @var array
2722 protected $types = array();
2725 * Retrieves the lesson page type manager object
2727 * If the object hasn't yet been created it is created here.
2729 * @staticvar lesson_page_type_manager $pagetypemanager
2730 * @param lesson $lesson
2731 * @return lesson_page_type_manager
2733 public static function get(lesson $lesson) {
2734 static $pagetypemanager;
2735 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
2736 $pagetypemanager = new lesson_page_type_manager();
2737 $pagetypemanager->load_lesson_types($lesson);
2739 return $pagetypemanager;
2743 * Finds and loads all lesson page types in mod/lesson/pagetypes
2745 * @param lesson $lesson
2747 public function load_lesson_types(lesson $lesson) {
2748 global $CFG;
2749 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
2750 $dir = dir($basedir);
2751 while (false !== ($entry = $dir->read())) {
2752 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2753 continue;
2755 require_once($basedir.$entry);
2756 $class = 'lesson_page_type_'.strtok($entry,'.');
2757 if (class_exists($class)) {
2758 $pagetype = new $class(new stdClass, $lesson);
2759 $this->types[$pagetype->typeid] = $pagetype;
2766 * Returns an array of strings to describe the loaded page types
2768 * @param int $type Can be used to return JUST the string for the requested type
2769 * @return array
2771 public function get_page_type_strings($type=null, $special=true) {
2772 $types = array();
2773 foreach ($this->types as $pagetype) {
2774 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
2775 $types[$pagetype->typeid] = $pagetype->typestring;
2778 return $types;
2782 * Returns the basic string used to identify a page type provided with an id
2784 * This string can be used to instantiate or identify the page type class.
2785 * If the page type id is unknown then 'unknown' is returned
2787 * @param int $id
2788 * @return string
2790 public function get_page_type_idstring($id) {
2791 foreach ($this->types as $pagetype) {
2792 if ((int)$pagetype->typeid === (int)$id) {
2793 return $pagetype->idstring;
2796 return 'unknown';
2800 * Loads a page for the provided lesson given it's id
2802 * This function loads a page from the lesson when given both the lesson it belongs
2803 * to as well as the page's id.
2804 * If the page doesn't exist an error is thrown
2806 * @param int $pageid The id of the page to load
2807 * @param lesson $lesson The lesson the page belongs to
2808 * @return lesson_page A class that extends lesson_page
2810 public function load_page($pageid, lesson $lesson) {
2811 global $DB;
2812 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
2813 print_error('cannotfindpages', 'lesson');
2815 $pagetype = get_class($this->types[$page->qtype]);
2816 $page = new $pagetype($page, $lesson);
2817 return $page;
2821 * This function detects errors in the ordering between 2 pages and updates the page records.
2823 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
2824 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
2826 protected function check_page_order($page1, $page2) {
2827 global $DB;
2828 if (empty($page1)) {
2829 if ($page2->prevpageid != 0) {
2830 debugging("***prevpageid of page " . $page2->id . " set to 0***");
2831 $page2->prevpageid = 0;
2832 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
2834 } else if (empty($page2)) {
2835 if ($page1->nextpageid != 0) {
2836 debugging("***nextpageid of page " . $page1->id . " set to 0***");
2837 $page1->nextpageid = 0;
2838 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
2840 } else {
2841 if ($page1->nextpageid != $page2->id) {
2842 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
2843 $page1->nextpageid = $page2->id;
2844 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
2846 if ($page2->prevpageid != $page1->id) {
2847 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
2848 $page2->prevpageid = $page1->id;
2849 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
2855 * This function loads ALL pages that belong to the lesson.
2857 * @param lesson $lesson
2858 * @return array An array of lesson_page_type_*
2860 public function load_all_pages(lesson $lesson) {
2861 global $DB;
2862 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
2863 return array(); // Records returned empty.
2865 foreach ($pages as $key=>$page) {
2866 $pagetype = get_class($this->types[$page->qtype]);
2867 $pages[$key] = new $pagetype($page, $lesson);
2870 $orderedpages = array();
2871 $lastpageid = 0;
2872 $morepages = true;
2873 while ($morepages) {
2874 $morepages = false;
2875 foreach ($pages as $page) {
2876 if ((int)$page->prevpageid === (int)$lastpageid) {
2877 // Check for errors in page ordering and fix them on the fly.
2878 $prevpage = null;
2879 if ($lastpageid !== 0) {
2880 $prevpage = $orderedpages[$lastpageid];
2882 $this->check_page_order($prevpage, $page);
2883 $morepages = true;
2884 $orderedpages[$page->id] = $page;
2885 unset($pages[$page->id]);
2886 $lastpageid = $page->id;
2887 if ((int)$page->nextpageid===0) {
2888 break 2;
2889 } else {
2890 break 1;
2896 // Add remaining pages and fix the nextpageid links for each page.
2897 foreach ($pages as $page) {
2898 // Check for errors in page ordering and fix them on the fly.
2899 $prevpage = null;
2900 if ($lastpageid !== 0) {
2901 $prevpage = $orderedpages[$lastpageid];
2903 $this->check_page_order($prevpage, $page);
2904 $orderedpages[$page->id] = $page;
2905 unset($pages[$page->id]);
2906 $lastpageid = $page->id;
2909 if ($lastpageid !== 0) {
2910 $this->check_page_order($orderedpages[$lastpageid], null);
2913 return $orderedpages;
2917 * Fetches an mform that can be used to create/edit an page
2919 * @param int $type The id for the page type
2920 * @param array $arguments Any arguments to pass to the mform
2921 * @return lesson_add_page_form_base
2923 public function get_page_form($type, $arguments) {
2924 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
2925 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
2926 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
2927 $class = 'lesson_add_page_form_selection';
2928 } else if ($class === 'lesson_add_page_form_unknown') {
2929 $class = 'lesson_add_page_form_selection';
2931 return new $class(null, $arguments);
2935 * Returns an array of links to use as add page links
2936 * @param int $previd The id of the previous page
2937 * @return array
2939 public function get_add_page_type_links($previd) {
2940 global $OUTPUT;
2942 $links = array();
2944 foreach ($this->types as $key=>$type) {
2945 if ($link = $type->add_page_link($previd)) {
2946 $links[$key] = $link;
2950 return $links;