MDL-48709 mod_lesson: subclusters are not working
[moodle.git] / mod / lesson / locallib.php
blob9292dbbd0c77c8071142a746b66a3275e3121459
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Local library file for Lesson. These are non-standard functions that are used
20 * only by Lesson.
22 * @package mod_lesson
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
25 **/
27 /** Make sure this isn't being directly accessed */
28 defined('MOODLE_INTERNAL') || die();
30 /** Include the files that are required by this module */
31 require_once($CFG->dirroot.'/course/moodleform_mod.php');
32 require_once($CFG->dirroot . '/mod/lesson/lib.php');
33 require_once($CFG->libdir . '/filelib.php');
35 /** This page */
36 define('LESSON_THISPAGE', 0);
37 /** Next page -> any page not seen before */
38 define("LESSON_UNSEENPAGE", 1);
39 /** Next page -> any page not answered correctly */
40 define("LESSON_UNANSWEREDPAGE", 2);
41 /** Jump to Next Page */
42 define("LESSON_NEXTPAGE", -1);
43 /** End of Lesson */
44 define("LESSON_EOL", -9);
45 /** Jump to an unseen page within a branch and end of branch or end of lesson */
46 define("LESSON_UNSEENBRANCHPAGE", -50);
47 /** Jump to Previous Page */
48 define("LESSON_PREVIOUSPAGE", -40);
49 /** Jump to a random page within a branch and end of branch or end of lesson */
50 define("LESSON_RANDOMPAGE", -60);
51 /** Jump to a random Branch */
52 define("LESSON_RANDOMBRANCH", -70);
53 /** Cluster Jump */
54 define("LESSON_CLUSTERJUMP", -80);
55 /** Undefined */
56 define("LESSON_UNDEFINED", -99);
58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59 define("LESSON_MAX_EVENT_LENGTH", "432000");
61 /** Answer format is HTML */
62 define("LESSON_ANSWER_HTML", "HTML");
64 //////////////////////////////////////////////////////////////////////////////////////
65 /// Any other lesson functions go here. Each of them must have a name that
66 /// starts with lesson_
68 /**
69 * Checks to see if a LESSON_CLUSTERJUMP or
70 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
72 * This function is only executed when a teacher is
73 * checking the navigation for a lesson.
75 * @param stdClass $lesson Id of the lesson that is to be checked.
76 * @return boolean True or false.
77 **/
78 function lesson_display_teacher_warning($lesson) {
79 global $DB;
81 // get all of the lesson answers
82 $params = array ("lessonid" => $lesson->id);
83 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
84 // no answers, then not using cluster or unseen
85 return false;
87 // just check for the first one that fulfills the requirements
88 foreach ($lessonanswers as $lessonanswer) {
89 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
90 return true;
94 // if no answers use either of the two jumps
95 return false;
98 /**
99 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
101 * will return the pageid of a random unseen page that is within a branch
103 * @param lesson $lesson
104 * @param int $userid Id of the user.
105 * @param int $pageid Id of the page from which we are jumping.
106 * @return int Id of the next page.
108 function lesson_unseen_question_jump($lesson, $user, $pageid) {
109 global $DB;
111 // get the number of retakes
112 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
113 $retakes = 0;
116 // get all the lesson_attempts aka what the user has seen
117 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
118 foreach($viewedpages as $viewed) {
119 $seenpages[] = $viewed->pageid;
121 } else {
122 $seenpages = array();
125 // get the lesson pages
126 $lessonpages = $lesson->load_all_pages();
128 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
129 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
132 // go up the pages till branch table
133 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
134 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
135 break;
137 $pageid = $lessonpages[$pageid]->prevpageid;
140 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
142 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
143 $unseen = array();
144 foreach($pagesinbranch as $page) {
145 if (!in_array($page->id, $seenpages)) {
146 $unseen[] = $page->id;
150 if(count($unseen) == 0) {
151 if(isset($pagesinbranch)) {
152 $temp = end($pagesinbranch);
153 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
154 } else {
155 // there are no pages inside the branch, so return the next page
156 $nextpage = $lessonpages[$pageid]->nextpageid;
158 if ($nextpage == 0) {
159 return LESSON_EOL;
160 } else {
161 return $nextpage;
163 } else {
164 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
169 * Handles the unseen branch table jump.
171 * @param lesson $lesson
172 * @param int $userid User id.
173 * @return int Will return the page id of a branch table or end of lesson
175 function lesson_unseen_branch_jump($lesson, $userid) {
176 global $DB;
178 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
179 $retakes = 0;
182 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
183 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
184 "timeseen DESC")) {
185 print_error('cannotfindrecords', 'lesson');
188 // get the lesson pages
189 $lessonpages = $lesson->load_all_pages();
191 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
192 // which is the branch table that starts the unseenbranch function
193 $seen = array();
194 foreach ($seenbranches as $seenbranch) {
195 if (!$seenbranch->flag) {
196 $seen[$seenbranch->pageid] = $seenbranch->pageid;
197 } else {
198 $start = $seenbranch->pageid;
199 break;
202 // this function searches through the lesson pages to find all the branch tables
203 // that follow the flagged branch table
204 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
205 $branchtables = array();
206 while ($pageid != 0) { // grab all of the branch table till eol
207 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
208 $branchtables[] = $lessonpages[$pageid]->id;
210 $pageid = $lessonpages[$pageid]->nextpageid;
212 $unseen = array();
213 foreach ($branchtables as $branchtable) {
214 // load all of the unseen branch tables into unseen
215 if (!array_key_exists($branchtable, $seen)) {
216 $unseen[] = $branchtable;
219 if (count($unseen) > 0) {
220 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
221 } else {
222 return LESSON_EOL; // has viewed all of the branch tables
227 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
229 * @param lesson $lesson
230 * @param int $pageid The id of the page that we are jumping from (?)
231 * @return int The pageid of a random page that is within a branch table
233 function lesson_random_question_jump($lesson, $pageid) {
234 global $DB;
236 // get the lesson pages
237 $params = array ("lessonid" => $lesson->id);
238 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
239 print_error('cannotfindpages', 'lesson');
242 // go up the pages till branch table
243 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
245 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
246 break;
248 $pageid = $lessonpages[$pageid]->prevpageid;
251 // get the pages within the branch
252 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
254 if(count($pagesinbranch) == 0) {
255 // there are no pages inside the branch, so return the next page
256 return $lessonpages[$pageid]->nextpageid;
257 } else {
258 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
263 * Calculates a user's grade for a lesson.
265 * @param object $lesson The lesson that the user is taking.
266 * @param int $retries The attempt number.
267 * @param int $userid Id of the user (optional, default current user).
268 * @return object { nquestions => number of questions answered
269 attempts => number of question attempts
270 total => max points possible
271 earned => points earned by student
272 grade => calculated percentage grade
273 nmanual => number of manually graded questions
274 manualpoints => point value for manually graded questions }
276 function lesson_grade($lesson, $ntries, $userid = 0) {
277 global $USER, $DB;
279 if (empty($userid)) {
280 $userid = $USER->id;
283 // Zero out everything
284 $ncorrect = 0;
285 $nviewed = 0;
286 $score = 0;
287 $nmanual = 0;
288 $manualpoints = 0;
289 $thegrade = 0;
290 $nquestions = 0;
291 $total = 0;
292 $earned = 0;
294 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
295 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
296 userid = :userid AND retry = :retry", $params, "timeseen")) {
297 // group each try with its page
298 $attemptset = array();
299 foreach ($useranswers as $useranswer) {
300 $attemptset[$useranswer->pageid][] = $useranswer;
303 // Drop all attempts that go beyond max attempts for the lesson
304 foreach ($attemptset as $key => $set) {
305 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
308 // get only the pages and their answers that the user answered
309 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
310 array_unshift($parameters, $lesson->id);
311 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
312 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
314 // Number of pages answered
315 $nquestions = count($pages);
317 foreach ($attemptset as $attempts) {
318 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
319 if ($lesson->custom) {
320 $attempt = end($attempts);
321 // If essay question, handle it, otherwise add to score
322 if ($page->requires_manual_grading()) {
323 $useranswerobj = unserialize($attempt->useranswer);
324 if (isset($useranswerobj->score)) {
325 $earned += $useranswerobj->score;
327 $nmanual++;
328 $manualpoints += $answers[$attempt->answerid]->score;
329 } else if (!empty($attempt->answerid)) {
330 $earned += $page->earned_score($answers, $attempt);
332 } else {
333 foreach ($attempts as $attempt) {
334 $earned += $attempt->correct;
336 $attempt = end($attempts); // doesn't matter which one
337 // If essay question, increase numbers
338 if ($page->requires_manual_grading()) {
339 $nmanual++;
340 $manualpoints++;
343 // Number of times answered
344 $nviewed += count($attempts);
347 if ($lesson->custom) {
348 $bestscores = array();
349 // Find the highest possible score per page to get our total
350 foreach ($answers as $answer) {
351 if(!isset($bestscores[$answer->pageid])) {
352 $bestscores[$answer->pageid] = $answer->score;
353 } else if ($bestscores[$answer->pageid] < $answer->score) {
354 $bestscores[$answer->pageid] = $answer->score;
357 $total = array_sum($bestscores);
358 } else {
359 // Check to make sure the student has answered the minimum questions
360 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
361 // Nope, increase number viewed by the amount of unanswered questions
362 $total = $nviewed + ($lesson->minquestions - $nquestions);
363 } else {
364 $total = $nviewed;
369 if ($total) { // not zero
370 $thegrade = round(100 * $earned / $total, 5);
373 // Build the grade information object
374 $gradeinfo = new stdClass;
375 $gradeinfo->nquestions = $nquestions;
376 $gradeinfo->attempts = $nviewed;
377 $gradeinfo->total = $total;
378 $gradeinfo->earned = $earned;
379 $gradeinfo->grade = $thegrade;
380 $gradeinfo->nmanual = $nmanual;
381 $gradeinfo->manualpoints = $manualpoints;
383 return $gradeinfo;
387 * Determines if a user can view the left menu. The determining factor
388 * is whether a user has a grade greater than or equal to the lesson setting
389 * of displayleftif
391 * @param object $lesson Lesson object of the current lesson
392 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
394 function lesson_displayleftif($lesson) {
395 global $CFG, $USER, $DB;
397 if (!empty($lesson->displayleftif)) {
398 // get the current user's max grade for this lesson
399 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
400 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)) {
401 if ($maxgrade->maxgrade < $lesson->displayleftif) {
402 return 0; // turn off the displayleft
404 } else {
405 return 0; // no grades
409 // if we get to here, keep the original state of displayleft lesson setting
410 return $lesson->displayleft;
415 * @param $cm
416 * @param $lesson
417 * @param $page
418 * @return unknown_type
420 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
421 $bc = lesson_menu_block_contents($cm->id, $lesson);
422 if (!empty($bc)) {
423 $regions = $page->blocks->get_regions();
424 $firstregion = reset($regions);
425 $page->blocks->add_fake_block($bc, $firstregion);
428 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
429 if (!empty($bc)) {
430 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
433 if (!empty($timer)) {
434 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
435 if (!empty($bc)) {
436 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
442 * If there is a media file associated with this
443 * lesson, return a block_contents that displays it.
445 * @param int $cmid Course Module ID for this lesson
446 * @param object $lesson Full lesson record object
447 * @return block_contents
449 function lesson_mediafile_block_contents($cmid, $lesson) {
450 global $OUTPUT;
451 if (empty($lesson->mediafile)) {
452 return null;
455 $options = array();
456 $options['menubar'] = 0;
457 $options['location'] = 0;
458 $options['left'] = 5;
459 $options['top'] = 5;
460 $options['scrollbars'] = 1;
461 $options['resizable'] = 1;
462 $options['width'] = $lesson->mediawidth;
463 $options['height'] = $lesson->mediaheight;
465 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
466 $action = new popup_action('click', $link, 'lessonmediafile', $options);
467 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
469 $bc = new block_contents();
470 $bc->title = get_string('linkedmedia', 'lesson');
471 $bc->attributes['class'] = 'mediafile block';
472 $bc->content = $content;
474 return $bc;
478 * If a timed lesson and not a teacher, then
479 * return a block_contents containing the clock.
481 * @param int $cmid Course Module ID for this lesson
482 * @param object $lesson Full lesson record object
483 * @param object $timer Full timer record object
484 * @return block_contents
486 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
487 // Display for timed lessons and for students only
488 $context = context_module::instance($cmid);
489 if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) {
490 return null;
493 $content = '<div id="lesson-timer">';
494 $content .= $lesson->time_remaining($timer->starttime);
495 $content .= '</div>';
497 $clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
498 $page->requires->data_for_js('clocksettings', $clocksettings, true);
499 $page->requires->strings_for_js(array('timeisup'), 'lesson');
500 $page->requires->js('/mod/lesson/timer.js');
501 $page->requires->js_init_call('show_clock');
503 $bc = new block_contents();
504 $bc->title = get_string('timeremaining', 'lesson');
505 $bc->attributes['class'] = 'clock block';
506 $bc->content = $content;
508 return $bc;
512 * If left menu is turned on, then this will
513 * print the menu in a block
515 * @param int $cmid Course Module ID for this lesson
516 * @param lesson $lesson Full lesson record object
517 * @return void
519 function lesson_menu_block_contents($cmid, $lesson) {
520 global $CFG, $DB;
522 if (!$lesson->displayleft) {
523 return null;
526 $pages = $lesson->load_all_pages();
527 foreach ($pages as $page) {
528 if ((int)$page->prevpageid === 0) {
529 $pageid = $page->id;
530 break;
533 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
535 if (!$pageid || !$pages) {
536 return null;
539 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
541 while ($pageid != 0) {
542 $page = $pages[$pageid];
544 // Only process branch tables with display turned on
545 if ($page->displayinmenublock && $page->display) {
546 if ($page->id == $currentpageid) {
547 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
548 } else {
549 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&amp;pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
553 $pageid = $page->nextpageid;
555 $content .= "</ul>\n</div>\n";
557 $bc = new block_contents();
558 $bc->title = get_string('lessonmenu', 'lesson');
559 $bc->attributes['class'] = 'menu block';
560 $bc->content = $content;
562 return $bc;
566 * Adds header buttons to the page for the lesson
568 * @param object $cm
569 * @param object $context
570 * @param bool $extraeditbuttons
571 * @param int $lessonpageid
573 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
574 global $CFG, $PAGE, $OUTPUT;
575 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
576 if ($lessonpageid === null) {
577 print_error('invalidpageid', 'lesson');
579 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
580 $url = new moodle_url('/mod/lesson/editpage.php', array('id'=>$cm->id, 'pageid'=>$lessonpageid, 'edit'=>1));
581 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
587 * This is a function used to detect media types and generate html code.
589 * @global object $CFG
590 * @global object $PAGE
591 * @param object $lesson
592 * @param object $context
593 * @return string $code the html code of media
595 function lesson_get_media_html($lesson, $context) {
596 global $CFG, $PAGE, $OUTPUT;
597 require_once("$CFG->libdir/resourcelib.php");
599 // get the media file link
600 if (strpos($lesson->mediafile, '://') !== false) {
601 $url = new moodle_url($lesson->mediafile);
602 } else {
603 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
604 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
606 $title = $lesson->mediafile;
608 $clicktoopen = html_writer::link($url, get_string('download'));
610 $mimetype = resourcelib_guess_url_mimetype($url);
612 $extension = resourcelib_get_extension($url->out(false));
614 $mediarenderer = $PAGE->get_renderer('core', 'media');
615 $embedoptions = array(
616 core_media::OPTION_TRUSTED => true,
617 core_media::OPTION_BLOCK => true
620 // find the correct type and print it out
621 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
622 $code = resourcelib_embed_image($url, $title);
624 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
625 // Media (audio/video) file.
626 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
628 } else {
629 // anything else - just try object tag enlarged as much as possible
630 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
633 return $code;
638 * Abstract class that page type's MUST inherit from.
640 * This is the abstract class that ALL add page type forms must extend.
641 * You will notice that all but two of the methods this class contains are final.
642 * Essentially the only thing that extending classes can do is extend custom_definition.
643 * OR if it has a special requirement on creation it can extend construction_override
645 * @abstract
646 * @copyright 2009 Sam Hemelryk
647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
649 abstract class lesson_add_page_form_base extends moodleform {
652 * This is the classic define that is used to identify this pagetype.
653 * Will be one of LESSON_*
654 * @var int
656 public $qtype;
659 * The simple string that describes the page type e.g. truefalse, multichoice
660 * @var string
662 public $qtypestring;
665 * An array of options used in the htmleditor
666 * @var array
668 protected $editoroptions = array();
671 * True if this is a standard page of false if it does something special.
672 * Questions are standard pages, branch tables are not
673 * @var bool
675 protected $standard = true;
678 * Each page type can and should override this to add any custom elements to
679 * the basic form that they want
681 public function custom_definition() {}
684 * Used to determine if this is a standard page or a special page
685 * @return bool
687 public final function is_standard() {
688 return (bool)$this->standard;
692 * Add the required basic elements to the form.
694 * This method adds the basic elements to the form including title and contents
695 * and then calls custom_definition();
697 public final function definition() {
698 $mform = $this->_form;
699 $editoroptions = $this->_customdata['editoroptions'];
701 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
703 $mform->addElement('hidden', 'id');
704 $mform->setType('id', PARAM_INT);
706 $mform->addElement('hidden', 'pageid');
707 $mform->setType('pageid', PARAM_INT);
709 if ($this->standard === true) {
710 $mform->addElement('hidden', 'qtype');
711 $mform->setType('qtype', PARAM_INT);
713 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
714 $mform->setType('title', PARAM_TEXT);
715 $mform->addRule('title', get_string('required'), 'required', null, 'client');
717 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
718 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
719 $mform->setType('contents_editor', PARAM_RAW);
720 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
723 $this->custom_definition();
725 if ($this->_customdata['edit'] === true) {
726 $mform->addElement('hidden', 'edit', 1);
727 $mform->setType('edit', PARAM_BOOL);
728 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
729 } else if ($this->qtype === 'questiontype') {
730 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
731 } else {
732 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
737 * Convenience function: Adds a jumpto select element
739 * @param string $name
740 * @param string|null $label
741 * @param int $selected The page to select by default
743 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
744 $title = get_string("jump", "lesson");
745 if ($label === null) {
746 $label = $title;
748 if (is_int($name)) {
749 $name = "jumpto[$name]";
751 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
752 $this->_form->setDefault($name, $selected);
753 $this->_form->addHelpButton($name, 'jumps', 'lesson');
757 * Convenience function: Adds a score input element
759 * @param string $name
760 * @param string|null $label
761 * @param mixed $value The default value
763 protected final function add_score($name, $label=null, $value=null) {
764 if ($label === null) {
765 $label = get_string("score", "lesson");
768 if (is_int($name)) {
769 $name = "score[$name]";
771 $this->_form->addElement('text', $name, $label, array('size'=>5));
772 $this->_form->setType($name, PARAM_INT);
773 if ($value !== null) {
774 $this->_form->setDefault($name, $value);
776 $this->_form->addHelpButton($name, 'score', 'lesson');
778 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
779 if (!$this->_customdata['lesson']->custom) {
780 $this->_form->freeze($name);
785 * Convenience function: Adds an answer editor
787 * @param int $count The count of the element to add
788 * @param string $label, null means default
789 * @param bool $required
790 * @param string $format
791 * @return void
793 protected final function add_answer($count, $label = null, $required = false, $format= '') {
794 if ($label === null) {
795 $label = get_string('answer', 'lesson');
798 if ($format == LESSON_ANSWER_HTML) {
799 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
800 array('rows' => '4', 'columns' => '80'),
801 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
802 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
803 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
804 } else {
805 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
806 array('rows' => '4', 'columns' => '80'), array('noclean' => true));
807 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_MOODLE));
810 if ($required) {
811 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
815 * Convenience function: Adds an response editor
817 * @param int $count The count of the element to add
818 * @param string $label, null means default
819 * @param bool $required
820 * @return void
822 protected final function add_response($count, $label = null, $required = false) {
823 if ($label === null) {
824 $label = get_string('response', 'lesson');
826 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
827 array('rows' => '4', 'columns' => '80'),
828 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
829 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
830 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
832 if ($required) {
833 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
838 * A function that gets called upon init of this object by the calling script.
840 * This can be used to process an immediate action if required. Currently it
841 * is only used in special cases by non-standard page types.
843 * @return bool
845 public function construction_override($pageid, lesson $lesson) {
846 return true;
853 * Class representation of a lesson
855 * This class is used the interact with, and manage a lesson once instantiated.
856 * If you need to fetch a lesson object you can do so by calling
858 * <code>
859 * lesson::load($lessonid);
860 * // or
861 * $lessonrecord = $DB->get_record('lesson', $lessonid);
862 * $lesson = new lesson($lessonrecord);
863 * </code>
865 * The class itself extends lesson_base as all classes within the lesson module should
867 * These properties are from the database
868 * @property int $id The id of this lesson
869 * @property int $course The ID of the course this lesson belongs to
870 * @property string $name The name of this lesson
871 * @property int $practice Flag to toggle this as a practice lesson
872 * @property int $modattempts Toggle to allow the user to go back and review answers
873 * @property int $usepassword Toggle the use of a password for entry
874 * @property string $password The password to require users to enter
875 * @property int $dependency ID of another lesson this lesson is dependent on
876 * @property string $conditions Conditions of the lesson dependency
877 * @property int $grade The maximum grade a user can achieve (%)
878 * @property int $custom Toggle custom scoring on or off
879 * @property int $ongoing Toggle display of an ongoing score
880 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
881 * @property int $maxanswers The max number of answers or branches
882 * @property int $maxattempts The maximum number of attempts a user can record
883 * @property int $review Toggle use or wrong answer review button
884 * @property int $nextpagedefault Override the default next page
885 * @property int $feedback Toggles display of default feedback
886 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
887 * @property int $maxpages Maximum number of pages this lesson can contain
888 * @property int $retake Flag to allow users to retake a lesson
889 * @property int $activitylink Relate this lesson to another lesson
890 * @property string $mediafile File to pop up to or webpage to display
891 * @property int $mediaheight Sets the height of the media file popup
892 * @property int $mediawidth Sets the width of the media file popup
893 * @property int $mediaclose Toggle display of a media close button
894 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
895 * @property int $width Width of slideshow
896 * @property int $height Height of slideshow
897 * @property string $bgcolor Background colour of slideshow
898 * @property int $displayleft Display a left menu
899 * @property int $displayleftif Sets the condition on which the left menu is displayed
900 * @property int $progressbar Flag to toggle display of a lesson progress bar
901 * @property int $highscores Flag to toggle collection of high scores
902 * @property int $maxhighscores Number of high scores to limit to
903 * @property int $available Timestamp of when this lesson becomes available
904 * @property int $deadline Timestamp of when this lesson is no longer available
905 * @property int $timemodified Timestamp when lesson was last modified
907 * These properties are calculated
908 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
909 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
911 * @copyright 2009 Sam Hemelryk
912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
914 class lesson extends lesson_base {
917 * The id of the first page (where prevpageid = 0) gets set and retrieved by
918 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
919 * @var int
921 protected $firstpageid = null;
923 * The id of the last page (where nextpageid = 0) gets set and retrieved by
924 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
925 * @var int
927 protected $lastpageid = null;
929 * An array used to cache the pages associated with this lesson after the first
930 * time they have been loaded.
931 * A note to developers: If you are going to be working with MORE than one or
932 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
933 * in order to save excess database queries.
934 * @var array An array of lesson_page objects
936 protected $pages = array();
938 * Flag that gets set to true once all of the pages associated with the lesson
939 * have been loaded.
940 * @var bool
942 protected $loadedallpages = false;
945 * Simply generates a lesson object given an array/object of properties
946 * Overrides {@see lesson_base->create()}
947 * @static
948 * @param object|array $properties
949 * @return lesson
951 public static function create($properties) {
952 return new lesson($properties);
956 * Generates a lesson object from the database given its id
957 * @static
958 * @param int $lessonid
959 * @return lesson
961 public static function load($lessonid) {
962 global $DB;
964 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
965 print_error('invalidcoursemodule');
967 return new lesson($lesson);
971 * Deletes this lesson from the database
973 public function delete() {
974 global $CFG, $DB;
975 require_once($CFG->libdir.'/gradelib.php');
976 require_once($CFG->dirroot.'/calendar/lib.php');
978 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
979 $context = context_module::instance($cm->id);
981 $DB->delete_records("lesson", array("id"=>$this->properties->id));
982 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
983 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
984 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
985 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
986 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
987 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
988 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
989 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
990 foreach($events as $event) {
991 $event = calendar_event::load($event);
992 $event->delete();
996 // Delete files associated with this module.
997 $fs = get_file_storage();
998 $fs->delete_area_files($context->id);
1000 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1001 return true;
1005 * Fetches messages from the session that may have been set in previous page
1006 * actions.
1008 * <code>
1009 * // Do not call this method directly instead use
1010 * $lesson->messages;
1011 * </code>
1013 * @return array
1015 protected function get_messages() {
1016 global $SESSION;
1018 $messages = array();
1019 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1020 $messages = $SESSION->lesson_messages[$this->properties->id];
1021 unset($SESSION->lesson_messages[$this->properties->id]);
1024 return $messages;
1028 * Get all of the attempts for the current user.
1030 * @param int $retries
1031 * @param bool $correct Optional: only fetch correct attempts
1032 * @param int $pageid Optional: only fetch attempts at the given page
1033 * @param int $userid Optional: defaults to the current user if not set
1034 * @return array|false
1036 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1037 global $USER, $DB;
1038 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1039 if ($correct) {
1040 $params['correct'] = 1;
1042 if ($pageid !== null) {
1043 $params['pageid'] = $pageid;
1045 if ($userid === null) {
1046 $params['userid'] = $USER->id;
1048 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1052 * Returns the first page for the lesson or false if there isn't one.
1054 * This method should be called via the magic method __get();
1055 * <code>
1056 * $firstpage = $lesson->firstpage;
1057 * </code>
1059 * @return lesson_page|bool Returns the lesson_page specialised object or false
1061 protected function get_firstpage() {
1062 $pages = $this->load_all_pages();
1063 if (count($pages) > 0) {
1064 foreach ($pages as $page) {
1065 if ((int)$page->prevpageid === 0) {
1066 return $page;
1070 return false;
1074 * Returns the last page for the lesson or false if there isn't one.
1076 * This method should be called via the magic method __get();
1077 * <code>
1078 * $lastpage = $lesson->lastpage;
1079 * </code>
1081 * @return lesson_page|bool Returns the lesson_page specialised object or false
1083 protected function get_lastpage() {
1084 $pages = $this->load_all_pages();
1085 if (count($pages) > 0) {
1086 foreach ($pages as $page) {
1087 if ((int)$page->nextpageid === 0) {
1088 return $page;
1092 return false;
1096 * Returns the id of the first page of this lesson. (prevpageid = 0)
1097 * @return int
1099 protected function get_firstpageid() {
1100 global $DB;
1101 if ($this->firstpageid == null) {
1102 if (!$this->loadedallpages) {
1103 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1104 if (!$firstpageid) {
1105 print_error('cannotfindfirstpage', 'lesson');
1107 $this->firstpageid = $firstpageid;
1108 } else {
1109 $firstpage = $this->get_firstpage();
1110 $this->firstpageid = $firstpage->id;
1113 return $this->firstpageid;
1117 * Returns the id of the last page of this lesson. (nextpageid = 0)
1118 * @return int
1120 public function get_lastpageid() {
1121 global $DB;
1122 if ($this->lastpageid == null) {
1123 if (!$this->loadedallpages) {
1124 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1125 if (!$lastpageid) {
1126 print_error('cannotfindlastpage', 'lesson');
1128 $this->lastpageid = $lastpageid;
1129 } else {
1130 $lastpageid = $this->get_lastpage();
1131 $this->lastpageid = $lastpageid->id;
1135 return $this->lastpageid;
1139 * Gets the next page id to display after the one that is provided.
1140 * @param int $nextpageid
1141 * @return bool
1143 public function get_next_page($nextpageid) {
1144 global $USER, $DB;
1145 $allpages = $this->load_all_pages();
1146 if ($this->properties->nextpagedefault) {
1147 // in Flash Card mode...first get number of retakes
1148 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1149 shuffle($allpages);
1150 $found = false;
1151 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1152 foreach ($allpages as $nextpage) {
1153 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1154 $found = true;
1155 break;
1158 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1159 foreach ($allpages as $nextpage) {
1160 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1161 $found = true;
1162 break;
1166 if ($found) {
1167 if ($this->properties->maxpages) {
1168 // check number of pages viewed (in the lesson)
1169 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1170 return LESSON_EOL;
1173 return $nextpage->id;
1176 // In a normal lesson mode
1177 foreach ($allpages as $nextpage) {
1178 if ((int)$nextpage->id === (int)$nextpageid) {
1179 return $nextpage->id;
1182 return LESSON_EOL;
1186 * Sets a message against the session for this lesson that will displayed next
1187 * time the lesson processes messages
1189 * @param string $message
1190 * @param string $class
1191 * @param string $align
1192 * @return bool
1194 public function add_message($message, $class="notifyproblem", $align='center') {
1195 global $SESSION;
1197 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1198 $SESSION->lesson_messages = array();
1199 $SESSION->lesson_messages[$this->properties->id] = array();
1200 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1201 $SESSION->lesson_messages[$this->properties->id] = array();
1204 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1206 return true;
1210 * Check if the lesson is accessible at the present time
1211 * @return bool True if the lesson is accessible, false otherwise
1213 public function is_accessible() {
1214 $available = $this->properties->available;
1215 $deadline = $this->properties->deadline;
1216 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1220 * Starts the lesson time for the current user
1221 * @return bool Returns true
1223 public function start_timer() {
1224 global $USER, $DB;
1226 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1227 false, MUST_EXIST);
1229 // Trigger lesson started event.
1230 $event = \mod_lesson\event\lesson_started::create(array(
1231 'objectid' => $this->properties()->id,
1232 'context' => context_module::instance($cm->id),
1233 'courseid' => $this->properties()->course
1235 $event->trigger();
1237 $USER->startlesson[$this->properties->id] = true;
1238 $startlesson = new stdClass;
1239 $startlesson->lessonid = $this->properties->id;
1240 $startlesson->userid = $USER->id;
1241 $startlesson->starttime = time();
1242 $startlesson->lessontime = time();
1243 $DB->insert_record('lesson_timer', $startlesson);
1244 if ($this->properties->timed) {
1245 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties->maxtime), 'center');
1247 return true;
1251 * Updates the timer to the current time and returns the new timer object
1252 * @param bool $restart If set to true the timer is restarted
1253 * @param bool $continue If set to true AND $restart=true then the timer
1254 * will continue from a previous attempt
1255 * @return stdClass The new timer
1257 public function update_timer($restart=false, $continue=false, $endreached =false) {
1258 global $USER, $DB;
1259 // clock code
1260 // get time information for this user
1261 $params = array("lessonid" => $this->properties->id, "userid" => $USER->id);
1262 if (!$timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1)) {
1263 $this->start_timer();
1264 $timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1);
1266 $timer = current($timer); // This will get the latest start time record.
1268 if ($restart) {
1269 if ($continue) {
1270 // continue a previous test, need to update the clock (think this option is disabled atm)
1271 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1272 } else {
1273 // starting over, so reset the clock
1274 $timer->starttime = time();
1278 $timer->lessontime = time();
1279 $timer->completed = $endreached;
1280 $DB->update_record('lesson_timer', $timer);
1281 return $timer;
1285 * Updates the timer to the current time then stops it by unsetting the user var
1286 * @return bool Returns true
1288 public function stop_timer() {
1289 global $USER, $DB;
1290 unset($USER->startlesson[$this->properties->id]);
1292 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1293 false, MUST_EXIST);
1295 // Trigger lesson ended event.
1296 $event = \mod_lesson\event\lesson_ended::create(array(
1297 'objectid' => $this->properties()->id,
1298 'context' => context_module::instance($cm->id),
1299 'courseid' => $this->properties()->course
1301 $event->trigger();
1303 return $this->update_timer(false, false, true);
1307 * Checks to see if the lesson has pages
1309 public function has_pages() {
1310 global $DB;
1311 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1312 return ($pagecount>0);
1316 * Returns the link for the related activity
1317 * @return array|false
1319 public function link_for_activitylink() {
1320 global $DB;
1321 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1322 if ($module) {
1323 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1324 if ($modname) {
1325 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1326 if ($instancename) {
1327 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1328 get_string('activitylinkname', 'lesson', $instancename),
1329 array('class'=>'centerpadded lessonbutton standardbutton'));
1333 return '';
1337 * Loads the requested page.
1339 * This function will return the requested page id as either a specialised
1340 * lesson_page object OR as a generic lesson_page.
1341 * If the page has been loaded previously it will be returned from the pages
1342 * array, otherwise it will be loaded from the database first
1344 * @param int $pageid
1345 * @return lesson_page A lesson_page object or an object that extends it
1347 public function load_page($pageid) {
1348 if (!array_key_exists($pageid, $this->pages)) {
1349 $manager = lesson_page_type_manager::get($this);
1350 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1352 return $this->pages[$pageid];
1356 * Loads ALL of the pages for this lesson
1358 * @return array An array containing all pages from this lesson
1360 public function load_all_pages() {
1361 if (!$this->loadedallpages) {
1362 $manager = lesson_page_type_manager::get($this);
1363 $this->pages = $manager->load_all_pages($this);
1364 $this->loadedallpages = true;
1366 return $this->pages;
1370 * Determines if a jumpto value is correct or not.
1372 * returns true if jumpto page is (logically) after the pageid page or
1373 * if the jumpto value is a special value. Returns false in all other cases.
1375 * @param int $pageid Id of the page from which you are jumping from.
1376 * @param int $jumpto The jumpto number.
1377 * @return boolean True or false after a series of tests.
1379 public function jumpto_is_correct($pageid, $jumpto) {
1380 global $DB;
1382 // first test the special values
1383 if (!$jumpto) {
1384 // same page
1385 return false;
1386 } elseif ($jumpto == LESSON_NEXTPAGE) {
1387 return true;
1388 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1389 return true;
1390 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1391 return true;
1392 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1393 return true;
1394 } elseif ($jumpto == LESSON_EOL) {
1395 return true;
1398 $pages = $this->load_all_pages();
1399 $apageid = $pages[$pageid]->nextpageid;
1400 while ($apageid != 0) {
1401 if ($jumpto == $apageid) {
1402 return true;
1404 $apageid = $pages[$apageid]->nextpageid;
1406 return false;
1410 * Returns the time a user has remaining on this lesson
1411 * @param int $starttime Starttime timestamp
1412 * @return string
1414 public function time_remaining($starttime) {
1415 $timeleft = $starttime + $this->maxtime * 60 - time();
1416 $hours = floor($timeleft/3600);
1417 $timeleft = $timeleft - ($hours * 3600);
1418 $minutes = floor($timeleft/60);
1419 $secs = $timeleft - ($minutes * 60);
1421 if ($minutes < 10) {
1422 $minutes = "0$minutes";
1424 if ($secs < 10) {
1425 $secs = "0$secs";
1427 $output = array();
1428 $output[] = $hours;
1429 $output[] = $minutes;
1430 $output[] = $secs;
1431 $output = implode(':', $output);
1432 return $output;
1436 * Interprets LESSON_CLUSTERJUMP jumpto value.
1438 * This will select a page randomly
1439 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1440 * and the page selected will be a page that has not been viewed already
1441 * and if any pages are within a branch table or end of branch then only 1 page within
1442 * the branch table or end of branch will be randomly selected (sub clustering).
1444 * @param int $pageid Id of the current page from which we are jumping from.
1445 * @param int $userid Id of the user.
1446 * @return int The id of the next page.
1448 public function cluster_jump($pageid, $userid=null) {
1449 global $DB, $USER;
1451 if ($userid===null) {
1452 $userid = $USER->id;
1454 // get the number of retakes
1455 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1456 $retakes = 0;
1458 // get all the lesson_attempts aka what the user has seen
1459 $seenpages = array();
1460 if ($attempts = $this->get_attempts($retakes)) {
1461 foreach ($attempts as $attempt) {
1462 $seenpages[$attempt->pageid] = $attempt->pageid;
1467 // get the lesson pages
1468 $lessonpages = $this->load_all_pages();
1469 // find the start of the cluster
1470 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1471 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1472 break;
1474 $pageid = $lessonpages[$pageid]->prevpageid;
1477 $clusterpages = array();
1478 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1479 $unseen = array();
1480 foreach ($clusterpages as $key=>$cluster) {
1481 // Remove the page if it is in a branch table or is an endofbranch.
1482 if ($this->is_sub_page_of_type($cluster->id,
1483 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
1484 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1485 unset($clusterpages[$key]);
1486 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
1487 // If branchtable, check to see if any pages inside have been viewed.
1488 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1489 $flag = true;
1490 foreach ($branchpages as $branchpage) {
1491 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
1492 $flag = false;
1495 if ($flag && count($branchpages) > 0) {
1496 // Add branch table.
1497 $unseen[] = $cluster;
1499 } elseif ($cluster->is_unseen($seenpages)) {
1500 $unseen[] = $cluster;
1504 if (count($unseen) > 0) {
1505 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1506 $nextpage = $unseen[rand(0, count($unseen)-1)];
1507 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1508 // if branch table, then pick a random page inside of it
1509 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1510 return $branchpages[rand(0, count($branchpages)-1)]->id;
1511 } else { // otherwise, return the page's id
1512 return $nextpage->id;
1514 } else {
1515 // seen all there is to see, leave the cluster
1516 if (end($clusterpages)->nextpageid == 0) {
1517 return LESSON_EOL;
1518 } else {
1519 $clusterendid = $pageid;
1520 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
1521 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1522 break;
1524 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1526 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1527 if ($exitjump == LESSON_NEXTPAGE) {
1528 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1530 if ($exitjump == 0) {
1531 return LESSON_EOL;
1532 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1533 return $exitjump;
1534 } else {
1535 if (!array_key_exists($exitjump, $lessonpages)) {
1536 $found = false;
1537 foreach ($lessonpages as $page) {
1538 if ($page->id === $clusterendid) {
1539 $found = true;
1540 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1541 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1542 if ($exitjump == LESSON_NEXTPAGE) {
1543 $exitjump = $lessonpages[$page->id]->nextpageid;
1545 break;
1549 if (!array_key_exists($exitjump, $lessonpages)) {
1550 return LESSON_EOL;
1552 return $exitjump;
1559 * Finds all pages that appear to be a subtype of the provided pageid until
1560 * an end point specified within $ends is encountered or no more pages exist
1562 * @param int $pageid
1563 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1564 * the subtype
1565 * @return array An array of specialised lesson_page objects
1567 public function get_sub_pages_of($pageid, array $ends) {
1568 $lessonpages = $this->load_all_pages();
1569 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1570 $pages = array();
1572 while (true) {
1573 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1574 break;
1576 $pages[] = $lessonpages[$pageid];
1577 $pageid = $lessonpages[$pageid]->nextpageid;
1580 return $pages;
1584 * Checks to see if the specified page[id] is a subpage of a type specified in
1585 * the $types array, until either there are no more pages of we find a type
1586 * corresponding to that of a type specified in $ends
1588 * @param int $pageid The id of the page to check
1589 * @param array $types An array of types that would signify this page was a subpage
1590 * @param array $ends An array of types that mean this is not a subpage
1591 * @return bool
1593 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1594 $pages = $this->load_all_pages();
1595 $pageid = $pages[$pageid]->prevpageid; // move up one
1597 array_unshift($ends, 0);
1598 // go up the pages till branch table
1599 while (true) {
1600 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1601 return false;
1602 } else if (in_array($pages[$pageid]->qtype, $types)) {
1603 return true;
1605 $pageid = $pages[$pageid]->prevpageid;
1612 * Abstract class to provide a core functions to the all lesson classes
1614 * This class should be abstracted by ALL classes with the lesson module to ensure
1615 * that all classes within this module can be interacted with in the same way.
1617 * This class provides the user with a basic properties array that can be fetched
1618 * or set via magic methods, or alternatively by defining methods get_blah() or
1619 * set_blah() within the extending object.
1621 * @copyright 2009 Sam Hemelryk
1622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1624 abstract class lesson_base {
1627 * An object containing properties
1628 * @var stdClass
1630 protected $properties;
1633 * The constructor
1634 * @param stdClass $properties
1636 public function __construct($properties) {
1637 $this->properties = (object)$properties;
1641 * Magic property method
1643 * Attempts to call a set_$key method if one exists otherwise falls back
1644 * to simply set the property
1646 * @param string $key
1647 * @param mixed $value
1649 public function __set($key, $value) {
1650 if (method_exists($this, 'set_'.$key)) {
1651 $this->{'set_'.$key}($value);
1653 $this->properties->{$key} = $value;
1657 * Magic get method
1659 * Attempts to call a get_$key method to return the property and ralls over
1660 * to return the raw property
1662 * @param str $key
1663 * @return mixed
1665 public function __get($key) {
1666 if (method_exists($this, 'get_'.$key)) {
1667 return $this->{'get_'.$key}();
1669 return $this->properties->{$key};
1673 * Stupid PHP needs an isset magic method if you use the get magic method and
1674 * still want empty calls to work.... blah ~!
1676 * @param string $key
1677 * @return bool
1679 public function __isset($key) {
1680 if (method_exists($this, 'get_'.$key)) {
1681 $val = $this->{'get_'.$key}();
1682 return !empty($val);
1684 return !empty($this->properties->{$key});
1687 //NOTE: E_STRICT does not allow to change function signature!
1690 * If implemented should create a new instance, save it in the DB and return it
1692 //public static function create() {}
1694 * If implemented should load an instance from the DB and return it
1696 //public static function load() {}
1698 * Fetches all of the properties of the object
1699 * @return stdClass
1701 public function properties() {
1702 return $this->properties;
1708 * Abstract class representation of a page associated with a lesson.
1710 * This class should MUST be extended by all specialised page types defined in
1711 * mod/lesson/pagetypes/.
1712 * There are a handful of abstract methods that need to be defined as well as
1713 * severl methods that can optionally be defined in order to make the page type
1714 * operate in the desired way
1716 * Database properties
1717 * @property int $id The id of this lesson page
1718 * @property int $lessonid The id of the lesson this page belongs to
1719 * @property int $prevpageid The id of the page before this one
1720 * @property int $nextpageid The id of the next page in the page sequence
1721 * @property int $qtype Identifies the page type of this page
1722 * @property int $qoption Used to record page type specific options
1723 * @property int $layout Used to record page specific layout selections
1724 * @property int $display Used to record page specific display selections
1725 * @property int $timecreated Timestamp for when the page was created
1726 * @property int $timemodified Timestamp for when the page was last modified
1727 * @property string $title The title of this page
1728 * @property string $contents The rich content shown to describe the page
1729 * @property int $contentsformat The format of the contents field
1731 * Calculated properties
1732 * @property-read array $answers An array of answers for this page
1733 * @property-read bool $displayinmenublock Toggles display in the left menu block
1734 * @property-read array $jumps An array containing all the jumps this page uses
1735 * @property-read lesson $lesson The lesson this page belongs to
1736 * @property-read int $type The type of the page [question | structure]
1737 * @property-read typeid The unique identifier for the page type
1738 * @property-read typestring The string that describes this page type
1740 * @abstract
1741 * @copyright 2009 Sam Hemelryk
1742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1744 abstract class lesson_page extends lesson_base {
1747 * A reference to the lesson this page belongs to
1748 * @var lesson
1750 protected $lesson = null;
1752 * Contains the answers to this lesson_page once loaded
1753 * @var null|array
1755 protected $answers = null;
1757 * This sets the type of the page, can be one of the constants defined below
1758 * @var int
1760 protected $type = 0;
1763 * Constants used to identify the type of the page
1765 const TYPE_QUESTION = 0;
1766 const TYPE_STRUCTURE = 1;
1769 * This method should return the integer used to identify the page type within
1770 * the database and throughout code. This maps back to the defines used in 1.x
1771 * @abstract
1772 * @return int
1774 abstract protected function get_typeid();
1776 * This method should return the string that describes the pagetype
1777 * @abstract
1778 * @return string
1780 abstract protected function get_typestring();
1783 * This method gets called to display the page to the user taking the lesson
1784 * @abstract
1785 * @param object $renderer
1786 * @param object $attempt
1787 * @return string
1789 abstract public function display($renderer, $attempt);
1792 * Creates a new lesson_page within the database and returns the correct pagetype
1793 * object to use to interact with the new lesson
1795 * @final
1796 * @static
1797 * @param object $properties
1798 * @param lesson $lesson
1799 * @return lesson_page Specialised object that extends lesson_page
1801 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
1802 global $DB;
1803 $newpage = new stdClass;
1804 $newpage->title = $properties->title;
1805 $newpage->contents = $properties->contents_editor['text'];
1806 $newpage->contentsformat = $properties->contents_editor['format'];
1807 $newpage->lessonid = $lesson->id;
1808 $newpage->timecreated = time();
1809 $newpage->qtype = $properties->qtype;
1810 $newpage->qoption = (isset($properties->qoption))?1:0;
1811 $newpage->layout = (isset($properties->layout))?1:0;
1812 $newpage->display = (isset($properties->display))?1:0;
1813 $newpage->prevpageid = 0; // this is a first page
1814 $newpage->nextpageid = 0; // this is the only page
1816 if ($properties->pageid) {
1817 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
1818 if (!$prevpage) {
1819 print_error('cannotfindpages', 'lesson');
1821 $newpage->prevpageid = $prevpage->id;
1822 $newpage->nextpageid = $prevpage->nextpageid;
1823 } else {
1824 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
1825 if ($nextpage) {
1826 // This is the first page, there are existing pages put this at the start
1827 $newpage->nextpageid = $nextpage->id;
1831 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
1833 $editor = new stdClass;
1834 $editor->id = $newpage->id;
1835 $editor->contents_editor = $properties->contents_editor;
1836 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
1837 $DB->update_record("lesson_pages", $editor);
1839 if ($newpage->prevpageid > 0) {
1840 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
1842 if ($newpage->nextpageid > 0) {
1843 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
1846 $page = lesson_page::load($newpage, $lesson);
1847 $page->create_answers($properties);
1849 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
1851 return $page;
1855 * This method loads a page object from the database and returns it as a
1856 * specialised object that extends lesson_page
1858 * @final
1859 * @static
1860 * @param int $id
1861 * @param lesson $lesson
1862 * @return lesson_page Specialised lesson_page object
1864 final public static function load($id, lesson $lesson) {
1865 global $DB;
1867 if (is_object($id) && !empty($id->qtype)) {
1868 $page = $id;
1869 } else {
1870 $page = $DB->get_record("lesson_pages", array("id" => $id));
1871 if (!$page) {
1872 print_error('cannotfindpages', 'lesson');
1875 $manager = lesson_page_type_manager::get($lesson);
1877 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
1878 if (!class_exists($class)) {
1879 $class = 'lesson_page';
1882 return new $class($page, $lesson);
1886 * Deletes a lesson_page from the database as well as any associated records.
1887 * @final
1888 * @return bool
1890 final public function delete() {
1891 global $DB;
1893 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
1894 $context = context_module::instance($cm->id);
1896 // Delete files associated with attempts.
1897 $fs = get_file_storage();
1898 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
1899 foreach ($attempts as $attempt) {
1900 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
1904 // Then delete all the associated records...
1905 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
1906 // ...now delete the answers...
1907 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
1908 // ..and the page itself
1909 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
1911 // Delete files associated with this page.
1912 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
1913 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $this->properties->id);
1914 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $this->properties->id);
1916 // repair the hole in the linkage
1917 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
1918 //This is the only page, no repair needed
1919 } elseif (!$this->properties->prevpageid) {
1920 // this is the first page...
1921 $page = $this->lesson->load_page($this->properties->nextpageid);
1922 $page->move(null, 0);
1923 } elseif (!$this->properties->nextpageid) {
1924 // this is the last page...
1925 $page = $this->lesson->load_page($this->properties->prevpageid);
1926 $page->move(0);
1927 } else {
1928 // page is in the middle...
1929 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
1930 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
1932 $prevpage->move($nextpage->id);
1933 $nextpage->move(null, $prevpage->id);
1935 return true;
1939 * Moves a page by updating its nextpageid and prevpageid values within
1940 * the database
1942 * @final
1943 * @param int $nextpageid
1944 * @param int $prevpageid
1946 final public function move($nextpageid=null, $prevpageid=null) {
1947 global $DB;
1948 if ($nextpageid === null) {
1949 $nextpageid = $this->properties->nextpageid;
1951 if ($prevpageid === null) {
1952 $prevpageid = $this->properties->prevpageid;
1954 $obj = new stdClass;
1955 $obj->id = $this->properties->id;
1956 $obj->prevpageid = $prevpageid;
1957 $obj->nextpageid = $nextpageid;
1958 $DB->update_record('lesson_pages', $obj);
1962 * Returns the answers that are associated with this page in the database
1964 * @final
1965 * @return array
1967 final public function get_answers() {
1968 global $DB;
1969 if ($this->answers === null) {
1970 $this->answers = array();
1971 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
1972 if (!$answers) {
1973 // It is possible that a lesson upgraded from Moodle 1.9 still
1974 // contains questions without any answers [MDL-25632].
1975 // debugging(get_string('cannotfindanswer', 'lesson'));
1976 return array();
1978 foreach ($answers as $answer) {
1979 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
1982 return $this->answers;
1986 * Returns the lesson this page is associated with
1987 * @final
1988 * @return lesson
1990 final protected function get_lesson() {
1991 return $this->lesson;
1995 * Returns the type of page this is. Not to be confused with page type
1996 * @final
1997 * @return int
1999 final protected function get_type() {
2000 return $this->type;
2004 * Records an attempt at this page
2006 * @final
2007 * @global moodle_database $DB
2008 * @param stdClass $context
2009 * @return stdClass Returns the result of the attempt
2011 final public function record_attempt($context) {
2012 global $DB, $USER, $OUTPUT;
2015 * This should be overridden by each page type to actually check the response
2016 * against what ever custom criteria they have defined
2018 $result = $this->check_answer();
2020 $result->attemptsremaining = 0;
2021 $result->maxattemptsreached = false;
2023 if ($result->noanswer) {
2024 $result->newpageid = $this->properties->id; // display same page again
2025 $result->feedback = get_string('noanswer', 'lesson');
2026 } else {
2027 if (!has_capability('mod/lesson:manage', $context)) {
2028 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2029 // record student's attempt
2030 $attempt = new stdClass;
2031 $attempt->lessonid = $this->lesson->id;
2032 $attempt->pageid = $this->properties->id;
2033 $attempt->userid = $USER->id;
2034 $attempt->answerid = $result->answerid;
2035 $attempt->retry = $nretakes;
2036 $attempt->correct = $result->correctanswer;
2037 if($result->userresponse !== null) {
2038 $attempt->useranswer = $result->userresponse;
2041 $attempt->timeseen = time();
2042 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
2043 $userisreviewing = false;
2044 if (isset($USER->modattempts[$this->lesson->id])) {
2045 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
2046 $userisreviewing = true;
2049 // Only insert a record if we are not reviewing the lesson.
2050 if (!$userisreviewing) {
2051 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
2052 $DB->insert_record("lesson_attempts", $attempt);
2055 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
2056 // displaying of message(s) is at the end of page for more ergonomic display
2057 if (!$result->correctanswer && ($result->newpageid == 0)) {
2058 // wrong answer and student is stuck on this page - check how many attempts
2059 // the student has had at this page/question
2060 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry" => $attempt->retry));
2061 // retreive the number of attempts left counter for displaying at bottom of feedback page
2062 if ($nattempts >= $this->lesson->maxattempts) {
2063 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2064 $result->maxattemptsreached = true;
2066 $result->newpageid = LESSON_NEXTPAGE;
2067 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2068 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
2072 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
2073 if ($result->newpageid == 0) {
2074 $result->newpageid = $this->properties->id;
2075 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
2076 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2079 // Determine default feedback if necessary
2080 if (empty($result->response)) {
2081 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2082 // These conditions have been met:
2083 // 1. The lesson manager has not supplied feedback to the student
2084 // 2. Not displaying default feedback
2085 // 3. The user did provide an answer
2086 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2088 $result->nodefaultresponse = true; // This will cause a redirect below
2089 } else if ($result->isessayquestion) {
2090 $result->response = get_string('defaultessayresponse', 'lesson');
2091 } else if ($result->correctanswer) {
2092 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2093 } else {
2094 $result->response = get_string('thatsthewronganswer', 'lesson');
2098 if ($result->response) {
2099 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2100 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2101 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2102 if ($qattempts == 1) {
2103 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2104 } else {
2105 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
2107 } else {
2108 $class = 'response';
2109 if ($result->correctanswer) {
2110 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2111 } else if (!$result->isessayquestion) {
2112 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2114 $options = new stdClass;
2115 $options->noclean = true;
2116 $options->para = true;
2117 $options->overflowdiv = true;
2118 $options->context = $context;
2120 $result->feedback = $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 'generalbox boxaligncenter');
2121 if (isset($result->studentanswerformat)) {
2122 // This is the student's answer so it should be cleaned.
2123 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
2124 array('context' => $context, 'para' => true));
2125 } else {
2126 $studentanswer = format_string($result->studentanswer);
2128 $result->feedback .= '<div class="correctanswer generalbox"><em>'
2129 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
2130 if (isset($result->responseformat)) {
2131 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
2132 'mod_lesson', 'page_responses', $result->answerid);
2133 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
2134 , $class);
2135 } else {
2136 $result->feedback .= $OUTPUT->box($result->response, $class);
2138 $result->feedback .= '</div>';
2143 return $result;
2147 * Returns the string for a jump name
2149 * @final
2150 * @param int $jumpto Jump code or page ID
2151 * @return string
2153 final protected function get_jump_name($jumpto) {
2154 global $DB;
2155 static $jumpnames = array();
2157 if (!array_key_exists($jumpto, $jumpnames)) {
2158 if ($jumpto == LESSON_THISPAGE) {
2159 $jumptitle = get_string('thispage', 'lesson');
2160 } elseif ($jumpto == LESSON_NEXTPAGE) {
2161 $jumptitle = get_string('nextpage', 'lesson');
2162 } elseif ($jumpto == LESSON_EOL) {
2163 $jumptitle = get_string('endoflesson', 'lesson');
2164 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2165 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2166 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2167 $jumptitle = get_string('previouspage', 'lesson');
2168 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2169 $jumptitle = get_string('randompageinbranch', 'lesson');
2170 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2171 $jumptitle = get_string('randombranch', 'lesson');
2172 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2173 $jumptitle = get_string('clusterjump', 'lesson');
2174 } else {
2175 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2176 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2179 $jumpnames[$jumpto] = format_string($jumptitle,true);
2182 return $jumpnames[$jumpto];
2186 * Constructor method
2187 * @param object $properties
2188 * @param lesson $lesson
2190 public function __construct($properties, lesson $lesson) {
2191 parent::__construct($properties);
2192 $this->lesson = $lesson;
2196 * Returns the score for the attempt
2197 * This may be overridden by page types that require manual grading
2198 * @param array $answers
2199 * @param object $attempt
2200 * @return int
2202 public function earned_score($answers, $attempt) {
2203 return $answers[$attempt->answerid]->score;
2207 * This is a callback method that can be override and gets called when ever a page
2208 * is viewed
2210 * @param bool $canmanage True if the user has the manage cap
2211 * @return mixed
2213 public function callback_on_view($canmanage) {
2214 return true;
2218 * save editor answers files and update answer record
2220 * @param object $context
2221 * @param int $maxbytes
2222 * @param object $answer
2223 * @param object $answereditor
2224 * @param object $responseeditor
2226 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
2227 global $DB;
2228 if (isset($answereditor['itemid'])) {
2229 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
2230 $context->id, 'mod_lesson', 'page_answers', $answer->id,
2231 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2232 $answer->answer, null);
2233 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
2235 if (isset($responseeditor['itemid'])) {
2236 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
2237 $context->id, 'mod_lesson', 'page_responses', $answer->id,
2238 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2239 $answer->response, null);
2240 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
2245 * Rewrite urls in response and optionality answer of a question answer
2247 * @param object $answer
2248 * @param bool $rewriteanswer must rewrite answer
2249 * @return object answer with rewritten urls
2251 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
2252 global $PAGE;
2254 $context = context_module::instance($PAGE->cm->id);
2255 if ($rewriteanswer) {
2256 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
2257 'mod_lesson', 'page_answers', $answer->id);
2259 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
2260 'mod_lesson', 'page_responses', $answer->id);
2262 return $answer;
2266 * Updates a lesson page and its answers within the database
2268 * @param object $properties
2269 * @return bool
2271 public function update($properties, $context = null, $maxbytes = null) {
2272 global $DB, $PAGE;
2273 $answers = $this->get_answers();
2274 $properties->id = $this->properties->id;
2275 $properties->lessonid = $this->lesson->id;
2276 if (empty($properties->qoption)) {
2277 $properties->qoption = '0';
2279 if (empty($context)) {
2280 $context = $PAGE->context;
2282 if ($maxbytes === null) {
2283 $maxbytes = get_user_max_upload_file_size($context);
2285 $properties->timemodified = time();
2286 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2287 $DB->update_record("lesson_pages", $properties);
2288 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
2289 if (count($answers) > 1) {
2290 $answer = array_shift($answers);
2291 foreach ($answers as $a) {
2292 $DB->delete_record('lesson_answers', array('id' => $a->id));
2294 } else if (count($answers) == 1) {
2295 $answer = array_shift($answers);
2296 } else {
2297 $answer = new stdClass;
2298 $answer->lessonid = $properties->lessonid;
2299 $answer->pageid = $properties->id;
2300 $answer->timecreated = time();
2303 $answer->timemodified = time();
2304 if (isset($properties->jumpto[0])) {
2305 $answer->jumpto = $properties->jumpto[0];
2307 if (isset($properties->score[0])) {
2308 $answer->score = $properties->score[0];
2310 if (!empty($answer->id)) {
2311 $DB->update_record("lesson_answers", $answer->properties());
2312 } else {
2313 $DB->insert_record("lesson_answers", $answer);
2315 } else {
2316 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2317 if (!array_key_exists($i, $this->answers)) {
2318 $this->answers[$i] = new stdClass;
2319 $this->answers[$i]->lessonid = $this->lesson->id;
2320 $this->answers[$i]->pageid = $this->id;
2321 $this->answers[$i]->timecreated = $this->timecreated;
2324 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2325 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2326 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2328 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2329 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2330 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
2333 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
2334 if (isset($properties->jumpto[$i])) {
2335 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2337 if ($this->lesson->custom && isset($properties->score[$i])) {
2338 $this->answers[$i]->score = $properties->score[$i];
2340 if (!isset($this->answers[$i]->id)) {
2341 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2342 } else {
2343 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2346 // Save files in answers and responses.
2347 if (isset($properties->response_editor[$i])) {
2348 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
2349 $properties->answer_editor[$i], $properties->response_editor[$i]);
2350 } else {
2351 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
2352 $properties->answer_editor[$i]);
2355 } else if (isset($this->answers[$i]->id)) {
2356 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
2357 unset($this->answers[$i]);
2361 return true;
2365 * Can be set to true if the page requires a static link to create a new instance
2366 * instead of simply being included in the dropdown
2367 * @param int $previd
2368 * @return bool
2370 public function add_page_link($previd) {
2371 return false;
2375 * Returns true if a page has been viewed before
2377 * @param array|int $param Either an array of pages that have been seen or the
2378 * number of retakes a user has had
2379 * @return bool
2381 public function is_unseen($param) {
2382 global $USER, $DB;
2383 if (is_array($param)) {
2384 $seenpages = $param;
2385 return (!array_key_exists($this->properties->id, $seenpages));
2386 } else {
2387 $nretakes = $param;
2388 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2389 return true;
2392 return false;
2396 * Checks to see if a page has been answered previously
2397 * @param int $nretakes
2398 * @return bool
2400 public function is_unanswered($nretakes) {
2401 global $DB, $USER;
2402 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2403 return true;
2405 return false;
2409 * Creates answers within the database for this lesson_page. Usually only ever
2410 * called when creating a new page instance
2411 * @param object $properties
2412 * @return array
2414 public function create_answers($properties) {
2415 global $DB, $PAGE;
2416 // now add the answers
2417 $newanswer = new stdClass;
2418 $newanswer->lessonid = $this->lesson->id;
2419 $newanswer->pageid = $this->properties->id;
2420 $newanswer->timecreated = $this->properties->timecreated;
2422 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
2423 $context = context_module::instance($cm->id);
2425 $answers = array();
2427 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2428 $answer = clone($newanswer);
2430 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2431 $answer->answer = $properties->answer_editor[$i]['text'];
2432 $answer->answerformat = $properties->answer_editor[$i]['format'];
2434 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2435 $answer->response = $properties->response_editor[$i]['text'];
2436 $answer->responseformat = $properties->response_editor[$i]['format'];
2439 if (isset($answer->answer) && $answer->answer != '') {
2440 if (isset($properties->jumpto[$i])) {
2441 $answer->jumpto = $properties->jumpto[$i];
2443 if ($this->lesson->custom && isset($properties->score[$i])) {
2444 $answer->score = $properties->score[$i];
2446 $answer->id = $DB->insert_record("lesson_answers", $answer);
2447 if (isset($properties->response_editor[$i])) {
2448 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
2449 $properties->answer_editor[$i], $properties->response_editor[$i]);
2450 } else {
2451 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
2452 $properties->answer_editor[$i]);
2454 $answers[$answer->id] = new lesson_page_answer($answer);
2455 } else {
2456 break;
2460 $this->answers = $answers;
2461 return $answers;
2465 * This method MUST be overridden by all question page types, or page types that
2466 * wish to score a page.
2468 * The structure of result should always be the same so it is a good idea when
2469 * overriding this method on a page type to call
2470 * <code>
2471 * $result = parent::check_answer();
2472 * </code>
2473 * before modifying it as required.
2475 * @return stdClass
2477 public function check_answer() {
2478 $result = new stdClass;
2479 $result->answerid = 0;
2480 $result->noanswer = false;
2481 $result->correctanswer = false;
2482 $result->isessayquestion = false; // use this to turn off review button on essay questions
2483 $result->response = '';
2484 $result->newpageid = 0; // stay on the page
2485 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2486 $result->userresponse = null;
2487 $result->feedback = '';
2488 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2489 return $result;
2493 * True if the page uses a custom option
2495 * Should be override and set to true if the page uses a custom option.
2497 * @return bool
2499 public function has_option() {
2500 return false;
2504 * Returns the maximum number of answers for this page given the maximum number
2505 * of answers permitted by the lesson.
2507 * @param int $default
2508 * @return int
2510 public function max_answers($default) {
2511 return $default;
2515 * Returns the properties of this lesson page as an object
2516 * @return stdClass;
2518 public function properties() {
2519 $properties = clone($this->properties);
2520 if ($this->answers === null) {
2521 $this->get_answers();
2523 if (count($this->answers)>0) {
2524 $count = 0;
2525 $qtype = $properties->qtype;
2526 foreach ($this->answers as $answer) {
2527 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
2528 if ($qtype != LESSON_PAGE_MATCHING) {
2529 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
2530 } else {
2531 $properties->{'response_editor['.$count.']'} = $answer->response;
2533 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2534 $properties->{'score['.$count.']'} = $answer->score;
2535 $count++;
2538 return $properties;
2542 * Returns an array of options to display when choosing the jumpto for a page/answer
2543 * @static
2544 * @param int $pageid
2545 * @param lesson $lesson
2546 * @return array
2548 public static function get_jumptooptions($pageid, lesson $lesson) {
2549 global $DB;
2550 $jump = array();
2551 $jump[0] = get_string("thispage", "lesson");
2552 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2553 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2554 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2556 if ($pageid == 0) {
2557 return $jump;
2560 $pages = $lesson->load_all_pages();
2561 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))) {
2562 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
2563 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
2565 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
2566 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
2568 if (!optional_param('firstpage', 0, PARAM_INT)) {
2569 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
2570 while (true) {
2571 if ($apageid) {
2572 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2573 $jump[$apageid] = strip_tags(format_string($title,true));
2574 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2575 } else {
2576 // last page reached
2577 break;
2581 return $jump;
2584 * Returns the contents field for the page properly formatted and with plugin
2585 * file url's converted
2586 * @return string
2588 public function get_contents() {
2589 global $PAGE;
2590 if (!empty($this->properties->contents)) {
2591 if (!isset($this->properties->contentsformat)) {
2592 $this->properties->contentsformat = FORMAT_HTML;
2594 $context = context_module::instance($PAGE->cm->id);
2595 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
2596 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
2597 return format_text($contents, $this->properties->contentsformat,
2598 array('context' => $context, 'noclean' => true,
2599 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
2600 } else {
2601 return '';
2606 * Set to true if this page should display in the menu block
2607 * @return bool
2609 protected function get_displayinmenublock() {
2610 return false;
2614 * Get the string that describes the options of this page type
2615 * @return string
2617 public function option_description_string() {
2618 return '';
2622 * Updates a table with the answers for this page
2623 * @param html_table $table
2624 * @return html_table
2626 public function display_answers(html_table $table) {
2627 $answers = $this->get_answers();
2628 $i = 1;
2629 foreach ($answers as $answer) {
2630 $cells = array();
2631 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2632 $cells[] = $this->get_jump_name($answer->jumpto);
2633 $table->data[] = new html_table_row($cells);
2634 if ($i === 1){
2635 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
2637 $i++;
2639 return $table;
2643 * Determines if this page should be grayed out on the management/report screens
2644 * @return int 0 or 1
2646 protected function get_grayout() {
2647 return 0;
2651 * Adds stats for this page to the &pagestats object. This should be defined
2652 * for all page types that grade
2653 * @param array $pagestats
2654 * @param int $tries
2655 * @return bool
2657 public function stats(array &$pagestats, $tries) {
2658 return true;
2662 * Formats the answers of this page for a report
2664 * @param object $answerpage
2665 * @param object $answerdata
2666 * @param object $useranswer
2667 * @param array $pagestats
2668 * @param int $i Count of first level answers
2669 * @param int $n Count of second level answers
2670 * @return object The answer page for this
2672 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2673 $answers = $this->get_answers();
2674 $formattextdefoptions = new stdClass;
2675 $formattextdefoptions->para = false; //I'll use it widely in this page
2676 foreach ($answers as $answer) {
2677 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
2678 $answerdata->answers[] = array($data, "");
2679 $answerpage->answerdata = $answerdata;
2681 return $answerpage;
2685 * Gets an array of the jumps used by the answers of this page
2687 * @return array
2689 public function get_jumps() {
2690 global $DB;
2691 $jumps = array();
2692 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
2693 if ($answers = $this->get_answers()) {
2694 foreach ($answers as $answer) {
2695 $jumps[] = $this->get_jump_name($answer->jumpto);
2697 } else {
2698 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
2700 return $jumps;
2703 * Informs whether this page type require manual grading or not
2704 * @return bool
2706 public function requires_manual_grading() {
2707 return false;
2711 * A callback method that allows a page to override the next page a user will
2712 * see during when this page is being completed.
2713 * @return false|int
2715 public function override_next_page() {
2716 return false;
2720 * This method is used to determine if this page is a valid page
2722 * @param array $validpages
2723 * @param array $pageviews
2724 * @return int The next page id to check
2726 public function valid_page_and_view(&$validpages, &$pageviews) {
2727 $validpages[$this->properties->id] = 1;
2728 return $this->properties->nextpageid;
2735 * Class used to represent an answer to a page
2737 * @property int $id The ID of this answer in the database
2738 * @property int $lessonid The ID of the lesson this answer belongs to
2739 * @property int $pageid The ID of the page this answer belongs to
2740 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2741 * @property int $grade The grade this answer is worth
2742 * @property int $score The score this answer will give
2743 * @property int $flags Used to store options for the answer
2744 * @property int $timecreated A timestamp of when the answer was created
2745 * @property int $timemodified A timestamp of when the answer was modified
2746 * @property string $answer The answer itself
2747 * @property string $response The response the user sees if selecting this answer
2749 * @copyright 2009 Sam Hemelryk
2750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2752 class lesson_page_answer extends lesson_base {
2755 * Loads an page answer from the DB
2757 * @param int $id
2758 * @return lesson_page_answer
2760 public static function load($id) {
2761 global $DB;
2762 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2763 return new lesson_page_answer($answer);
2767 * Given an object of properties and a page created answer(s) and saves them
2768 * in the database.
2770 * @param stdClass $properties
2771 * @param lesson_page $page
2772 * @return array
2774 public static function create($properties, lesson_page $page) {
2775 return $page->create_answers($properties);
2781 * A management class for page types
2783 * This class is responsible for managing the different pages. A manager object can
2784 * be retrieved by calling the following line of code:
2785 * <code>
2786 * $manager = lesson_page_type_manager::get($lesson);
2787 * </code>
2788 * The first time the page type manager is retrieved the it includes all of the
2789 * different page types located in mod/lesson/pagetypes.
2791 * @copyright 2009 Sam Hemelryk
2792 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2794 class lesson_page_type_manager {
2797 * An array of different page type classes
2798 * @var array
2800 protected $types = array();
2803 * Retrieves the lesson page type manager object
2805 * If the object hasn't yet been created it is created here.
2807 * @staticvar lesson_page_type_manager $pagetypemanager
2808 * @param lesson $lesson
2809 * @return lesson_page_type_manager
2811 public static function get(lesson $lesson) {
2812 static $pagetypemanager;
2813 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
2814 $pagetypemanager = new lesson_page_type_manager();
2815 $pagetypemanager->load_lesson_types($lesson);
2817 return $pagetypemanager;
2821 * Finds and loads all lesson page types in mod/lesson/pagetypes
2823 * @param lesson $lesson
2825 public function load_lesson_types(lesson $lesson) {
2826 global $CFG;
2827 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
2828 $dir = dir($basedir);
2829 while (false !== ($entry = $dir->read())) {
2830 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2831 continue;
2833 require_once($basedir.$entry);
2834 $class = 'lesson_page_type_'.strtok($entry,'.');
2835 if (class_exists($class)) {
2836 $pagetype = new $class(new stdClass, $lesson);
2837 $this->types[$pagetype->typeid] = $pagetype;
2844 * Returns an array of strings to describe the loaded page types
2846 * @param int $type Can be used to return JUST the string for the requested type
2847 * @return array
2849 public function get_page_type_strings($type=null, $special=true) {
2850 $types = array();
2851 foreach ($this->types as $pagetype) {
2852 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
2853 $types[$pagetype->typeid] = $pagetype->typestring;
2856 return $types;
2860 * Returns the basic string used to identify a page type provided with an id
2862 * This string can be used to instantiate or identify the page type class.
2863 * If the page type id is unknown then 'unknown' is returned
2865 * @param int $id
2866 * @return string
2868 public function get_page_type_idstring($id) {
2869 foreach ($this->types as $pagetype) {
2870 if ((int)$pagetype->typeid === (int)$id) {
2871 return $pagetype->idstring;
2874 return 'unknown';
2878 * Loads a page for the provided lesson given it's id
2880 * This function loads a page from the lesson when given both the lesson it belongs
2881 * to as well as the page's id.
2882 * If the page doesn't exist an error is thrown
2884 * @param int $pageid The id of the page to load
2885 * @param lesson $lesson The lesson the page belongs to
2886 * @return lesson_page A class that extends lesson_page
2888 public function load_page($pageid, lesson $lesson) {
2889 global $DB;
2890 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
2891 print_error('cannotfindpages', 'lesson');
2893 $pagetype = get_class($this->types[$page->qtype]);
2894 $page = new $pagetype($page, $lesson);
2895 return $page;
2899 * This function detects errors in the ordering between 2 pages and updates the page records.
2901 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
2902 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
2904 protected function check_page_order($page1, $page2) {
2905 global $DB;
2906 if (empty($page1)) {
2907 if ($page2->prevpageid != 0) {
2908 debugging("***prevpageid of page " . $page2->id . " set to 0***");
2909 $page2->prevpageid = 0;
2910 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
2912 } else if (empty($page2)) {
2913 if ($page1->nextpageid != 0) {
2914 debugging("***nextpageid of page " . $page1->id . " set to 0***");
2915 $page1->nextpageid = 0;
2916 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
2918 } else {
2919 if ($page1->nextpageid != $page2->id) {
2920 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
2921 $page1->nextpageid = $page2->id;
2922 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
2924 if ($page2->prevpageid != $page1->id) {
2925 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
2926 $page2->prevpageid = $page1->id;
2927 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
2933 * This function loads ALL pages that belong to the lesson.
2935 * @param lesson $lesson
2936 * @return array An array of lesson_page_type_*
2938 public function load_all_pages(lesson $lesson) {
2939 global $DB;
2940 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
2941 return array(); // Records returned empty.
2943 foreach ($pages as $key=>$page) {
2944 $pagetype = get_class($this->types[$page->qtype]);
2945 $pages[$key] = new $pagetype($page, $lesson);
2948 $orderedpages = array();
2949 $lastpageid = 0;
2950 $morepages = true;
2951 while ($morepages) {
2952 $morepages = false;
2953 foreach ($pages as $page) {
2954 if ((int)$page->prevpageid === (int)$lastpageid) {
2955 // Check for errors in page ordering and fix them on the fly.
2956 $prevpage = null;
2957 if ($lastpageid !== 0) {
2958 $prevpage = $orderedpages[$lastpageid];
2960 $this->check_page_order($prevpage, $page);
2961 $morepages = true;
2962 $orderedpages[$page->id] = $page;
2963 unset($pages[$page->id]);
2964 $lastpageid = $page->id;
2965 if ((int)$page->nextpageid===0) {
2966 break 2;
2967 } else {
2968 break 1;
2974 // Add remaining pages and fix the nextpageid links for each page.
2975 foreach ($pages as $page) {
2976 // Check for errors in page ordering and fix them on the fly.
2977 $prevpage = null;
2978 if ($lastpageid !== 0) {
2979 $prevpage = $orderedpages[$lastpageid];
2981 $this->check_page_order($prevpage, $page);
2982 $orderedpages[$page->id] = $page;
2983 unset($pages[$page->id]);
2984 $lastpageid = $page->id;
2987 if ($lastpageid !== 0) {
2988 $this->check_page_order($orderedpages[$lastpageid], null);
2991 return $orderedpages;
2995 * Fetches an mform that can be used to create/edit an page
2997 * @param int $type The id for the page type
2998 * @param array $arguments Any arguments to pass to the mform
2999 * @return lesson_add_page_form_base
3001 public function get_page_form($type, $arguments) {
3002 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
3003 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
3004 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
3005 $class = 'lesson_add_page_form_selection';
3006 } else if ($class === 'lesson_add_page_form_unknown') {
3007 $class = 'lesson_add_page_form_selection';
3009 return new $class(null, $arguments);
3013 * Returns an array of links to use as add page links
3014 * @param int $previd The id of the previous page
3015 * @return array
3017 public function get_add_page_type_links($previd) {
3018 global $OUTPUT;
3020 $links = array();
3022 foreach ($this->types as $key=>$type) {
3023 if ($link = $type->add_page_link($previd)) {
3024 $links[$key] = $link;
3028 return $links;