3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Local library file for Lesson. These are non-standard functions that are used
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
28 /** Make sure this isn't being directly accessed */
29 defined('MOODLE_INTERNAL') || die();
31 /** Include the files that are required by this module */
32 require_once($CFG->dirroot.'/course/moodleform_mod.php');
33 require_once($CFG->dirroot . '/mod/lesson/lib.php');
34 require_once($CFG->libdir . '/filelib.php');
37 define('LESSON_THISPAGE', 0);
38 /** Next page -> any page not seen before */
39 define("LESSON_UNSEENPAGE", 1);
40 /** Next page -> any page not answered correctly */
41 define("LESSON_UNANSWEREDPAGE", 2);
42 /** Jump to Next Page */
43 define("LESSON_NEXTPAGE", -1);
45 define("LESSON_EOL", -9);
46 /** Jump to an unseen page within a branch and end of branch or end of lesson */
47 define("LESSON_UNSEENBRANCHPAGE", -50);
48 /** Jump to Previous Page */
49 define("LESSON_PREVIOUSPAGE", -40);
50 /** Jump to a random page within a branch and end of branch or end of lesson */
51 define("LESSON_RANDOMPAGE", -60);
52 /** Jump to a random Branch */
53 define("LESSON_RANDOMBRANCH", -70);
55 define("LESSON_CLUSTERJUMP", -80);
57 define("LESSON_UNDEFINED", -99);
59 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
60 define("LESSON_MAX_EVENT_LENGTH", "432000");
63 //////////////////////////////////////////////////////////////////////////////////////
64 /// Any other lesson functions go here. Each of them must have a name that
65 /// starts with lesson_
68 * Checks to see if a LESSON_CLUSTERJUMP or
69 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
71 * This function is only executed when a teacher is
72 * checking the navigation for a lesson.
74 * @param stdClass $lesson Id of the lesson that is to be checked.
75 * @return boolean True or false.
77 function lesson_display_teacher_warning($lesson) {
80 // get all of the lesson answers
81 $params = array ("lessonid" => $lesson->id);
82 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
83 // no answers, then not using cluster or unseen
86 // just check for the first one that fulfills the requirements
87 foreach ($lessonanswers as $lessonanswer) {
88 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
93 // if no answers use either of the two jumps
98 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
100 * will return the pageid of a random unseen page that is within a branch
102 * @param lesson $lesson
103 * @param int $userid Id of the user.
104 * @param int $pageid Id of the page from which we are jumping.
105 * @return int Id of the next page.
107 function lesson_unseen_question_jump($lesson, $user, $pageid) {
110 // get the number of retakes
111 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
115 // get all the lesson_attempts aka what the user has seen
116 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
117 foreach($viewedpages as $viewed) {
118 $seenpages[] = $viewed->pageid;
121 $seenpages = array();
124 // get the lesson pages
125 $lessonpages = $lesson->load_all_pages();
127 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
128 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
131 // go up the pages till branch table
132 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
133 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
136 $pageid = $lessonpages[$pageid]->prevpageid;
139 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
141 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
143 foreach($pagesinbranch as $page) {
144 if (!in_array($page->id, $seenpages)) {
145 $unseen[] = $page->id;
149 if(count($unseen) == 0) {
150 if(isset($pagesinbranch)) {
151 $temp = end($pagesinbranch);
152 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
154 // there are no pages inside the branch, so return the next page
155 $nextpage = $lessonpages[$pageid]->nextpageid;
157 if ($nextpage == 0) {
163 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
168 * Handles the unseen branch table jump.
170 * @param lesson $lesson
171 * @param int $userid User id.
172 * @return int Will return the page id of a branch table or end of lesson
174 function lesson_unseen_branch_jump($lesson, $userid) {
177 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
181 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
182 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
184 print_error('cannotfindrecords', 'lesson');
187 // get the lesson pages
188 $lessonpages = $lesson->load_all_pages();
190 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
191 // which is the branch table that starts the unseenbranch function
193 foreach ($seenbranches as $seenbranch) {
194 if (!$seenbranch->flag) {
195 $seen[$seenbranch->pageid] = $seenbranch->pageid;
197 $start = $seenbranch->pageid;
201 // this function searches through the lesson pages to find all the branch tables
202 // that follow the flagged branch table
203 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
204 $branchtables = array();
205 while ($pageid != 0) { // grab all of the branch table till eol
206 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
207 $branchtables[] = $lessonpages[$pageid]->id;
209 $pageid = $lessonpages[$pageid]->nextpageid;
212 foreach ($branchtables as $branchtable) {
213 // load all of the unseen branch tables into unseen
214 if (!array_key_exists($branchtable, $seen)) {
215 $unseen[] = $branchtable;
218 if (count($unseen) > 0) {
219 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
221 return LESSON_EOL; // has viewed all of the branch tables
226 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
228 * @param lesson $lesson
229 * @param int $pageid The id of the page that we are jumping from (?)
230 * @return int The pageid of a random page that is within a branch table
232 function lesson_random_question_jump($lesson, $pageid) {
235 // get the lesson pages
236 $params = array ("lessonid" => $lesson->id);
237 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
238 print_error('cannotfindpages', 'lesson');
241 // go up the pages till branch table
242 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
244 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
247 $pageid = $lessonpages[$pageid]->prevpageid;
250 // get the pages within the branch
251 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
253 if(count($pagesinbranch) == 0) {
254 // there are no pages inside the branch, so return the next page
255 return $lessonpages[$pageid]->nextpageid;
257 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
262 * Calculates a user's grade for a lesson.
264 * @param object $lesson The lesson that the user is taking.
265 * @param int $retries The attempt number.
266 * @param int $userid Id of the user (optional, default current user).
267 * @return object { nquestions => number of questions answered
268 attempts => number of question attempts
269 total => max points possible
270 earned => points earned by student
271 grade => calculated percentage grade
272 nmanual => number of manually graded questions
273 manualpoints => point value for manually graded questions }
275 function lesson_grade($lesson, $ntries, $userid = 0) {
278 if (empty($userid)) {
282 // Zero out everything
293 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
294 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
295 userid = :userid AND retry = :retry", $params, "timeseen")) {
296 // group each try with its page
297 $attemptset = array();
298 foreach ($useranswers as $useranswer) {
299 $attemptset[$useranswer->pageid][] = $useranswer;
302 // Drop all attempts that go beyond max attempts for the lesson
303 foreach ($attemptset as $key => $set) {
304 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
307 // get only the pages and their answers that the user answered
308 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
309 array_unshift($parameters, $lesson->id);
310 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
311 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
313 // Number of pages answered
314 $nquestions = count($pages);
316 foreach ($attemptset as $attempts) {
317 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
318 if ($lesson->custom) {
319 $attempt = end($attempts);
320 // If essay question, handle it, otherwise add to score
321 if ($page->requires_manual_grading()) {
322 $useranswerobj = unserialize($attempt->useranswer);
323 if (isset($useranswerobj->score)) {
324 $earned += $useranswerobj->score;
327 $manualpoints += $answers[$attempt->answerid]->score;
328 } else if (!empty($attempt->answerid)) {
329 $earned += $page->earned_score($answers, $attempt);
332 foreach ($attempts as $attempt) {
333 $earned += $attempt->correct;
335 $attempt = end($attempts); // doesn't matter which one
336 // If essay question, increase numbers
337 if ($page->requires_manual_grading()) {
342 // Number of times answered
343 $nviewed += count($attempts);
346 if ($lesson->custom) {
347 $bestscores = array();
348 // Find the highest possible score per page to get our total
349 foreach ($answers as $answer) {
350 if(!isset($bestscores[$answer->pageid])) {
351 $bestscores[$answer->pageid] = $answer->score;
352 } else if ($bestscores[$answer->pageid] < $answer->score) {
353 $bestscores[$answer->pageid] = $answer->score;
356 $total = array_sum($bestscores);
358 // Check to make sure the student has answered the minimum questions
359 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
360 // Nope, increase number viewed by the amount of unanswered questions
361 $total = $nviewed + ($lesson->minquestions - $nquestions);
368 if ($total) { // not zero
369 $thegrade = round(100 * $earned / $total, 5);
372 // Build the grade information object
373 $gradeinfo = new stdClass;
374 $gradeinfo->nquestions = $nquestions;
375 $gradeinfo->attempts = $nviewed;
376 $gradeinfo->total = $total;
377 $gradeinfo->earned = $earned;
378 $gradeinfo->grade = $thegrade;
379 $gradeinfo->nmanual = $nmanual;
380 $gradeinfo->manualpoints = $manualpoints;
386 * Determines if a user can view the left menu. The determining factor
387 * is whether a user has a grade greater than or equal to the lesson setting
390 * @param object $lesson Lesson object of the current lesson
391 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
393 function lesson_displayleftif($lesson) {
394 global $CFG, $USER, $DB;
396 if (!empty($lesson->displayleftif)) {
397 // get the current user's max grade for this lesson
398 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
399 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)) {
400 if ($maxgrade->maxgrade < $lesson->displayleftif) {
401 return 0; // turn off the displayleft
404 return 0; // no grades
408 // if we get to here, keep the original state of displayleft lesson setting
409 return $lesson->displayleft;
417 * @return unknown_type
419 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
420 $bc = lesson_menu_block_contents($cm->id, $lesson);
422 $regions = $page->blocks->get_regions();
423 $firstregion = reset($regions);
424 $page->blocks->add_fake_block($bc, $firstregion);
427 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
429 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
432 if (!empty($timer)) {
433 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
435 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
441 * If there is a media file associated with this
442 * lesson, return a block_contents that displays it.
444 * @param int $cmid Course Module ID for this lesson
445 * @param object $lesson Full lesson record object
446 * @return block_contents
448 function lesson_mediafile_block_contents($cmid, $lesson) {
450 if (empty($lesson->mediafile)) {
455 $options['menubar'] = 0;
456 $options['location'] = 0;
457 $options['left'] = 5;
459 $options['scrollbars'] = 1;
460 $options['resizable'] = 1;
461 $options['width'] = $lesson->mediawidth;
462 $options['height'] = $lesson->mediaheight;
464 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
465 $action = new popup_action('click', $link, 'lessonmediafile', $options);
466 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
468 $bc = new block_contents();
469 $bc->title = get_string('linkedmedia', 'lesson');
470 $bc->attributes['class'] = 'mediafile';
471 $bc->content = $content;
477 * If a timed lesson and not a teacher, then
478 * return a block_contents containing the clock.
480 * @param int $cmid Course Module ID for this lesson
481 * @param object $lesson Full lesson record object
482 * @param object $timer Full timer record object
483 * @return block_contents
485 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
486 // Display for timed lessons and for students only
487 $context = context_module::instance($cmid);
488 if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) {
492 $content = '<div class="jshidewhenenabled">';
493 $content .= $lesson->time_remaining($timer->starttime);
494 $content .= '</div>';
496 $clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
497 $page->requires->data_for_js('clocksettings', $clocksettings);
498 $page->requires->js('/mod/lesson/timer.js');
499 $page->requires->js_function_call('show_clock');
501 $bc = new block_contents();
502 $bc->title = get_string('timeremaining', 'lesson');
503 $bc->attributes['class'] = 'clock block';
504 $bc->content = $content;
510 * If left menu is turned on, then this will
511 * print the menu in a block
513 * @param int $cmid Course Module ID for this lesson
514 * @param lesson $lesson Full lesson record object
517 function lesson_menu_block_contents($cmid, $lesson) {
520 if (!$lesson->displayleft) {
524 $pages = $lesson->load_all_pages();
525 foreach ($pages as $page) {
526 if ((int)$page->prevpageid === 0) {
531 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
533 if (!$pageid || !$pages) {
537 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
539 while ($pageid != 0) {
540 $page = $pages[$pageid];
542 // Only process branch tables with display turned on
543 if ($page->displayinmenublock && $page->display) {
544 if ($page->id == $currentpageid) {
545 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
547 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
551 $pageid = $page->nextpageid;
553 $content .= "</ul>\n</div>\n";
555 $bc = new block_contents();
556 $bc->title = get_string('lessonmenu', 'lesson');
557 $bc->attributes['class'] = 'menu block';
558 $bc->content = $content;
564 * Adds header buttons to the page for the lesson
567 * @param object $context
568 * @param bool $extraeditbuttons
569 * @param int $lessonpageid
571 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
572 global $CFG, $PAGE, $OUTPUT;
573 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
574 if ($lessonpageid === null) {
575 print_error('invalidpageid', 'lesson');
577 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
578 $url = new moodle_url('/mod/lesson/editpage.php', array('id'=>$cm->id, 'pageid'=>$lessonpageid, 'edit'=>1));
579 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
585 * This is a function used to detect media types and generate html code.
587 * @global object $CFG
588 * @global object $PAGE
589 * @param object $lesson
590 * @param object $context
591 * @return string $code the html code of media
593 function lesson_get_media_html($lesson, $context) {
594 global $CFG, $PAGE, $OUTPUT;
595 require_once("$CFG->libdir/resourcelib.php");
597 // get the media file link
598 if (strpos($lesson->mediafile, '://') !== false) {
599 $url = new moodle_url($lesson->mediafile);
601 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
602 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
604 $title = $lesson->mediafile;
606 $clicktoopen = html_writer::link($url, get_string('download'));
608 $mimetype = resourcelib_guess_url_mimetype($url);
610 $extension = resourcelib_get_extension($url->out(false));
612 $mediarenderer = $PAGE->get_renderer('core', 'media');
613 $embedoptions = array(
614 core_media::OPTION_TRUSTED => true,
615 core_media::OPTION_BLOCK => true
618 // find the correct type and print it out
619 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
620 $code = resourcelib_embed_image($url, $title);
622 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
623 // Media (audio/video) file.
624 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
627 // anything else - just try object tag enlarged as much as possible
628 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
636 * Abstract class that page type's MUST inherit from.
638 * This is the abstract class that ALL add page type forms must extend.
639 * You will notice that all but two of the methods this class contains are final.
640 * Essentially the only thing that extending classes can do is extend custom_definition.
641 * OR if it has a special requirement on creation it can extend construction_override
644 * @copyright 2009 Sam Hemelryk
645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 abstract class lesson_add_page_form_base extends moodleform {
650 * This is the classic define that is used to identify this pagetype.
651 * Will be one of LESSON_*
657 * The simple string that describes the page type e.g. truefalse, multichoice
663 * An array of options used in the htmleditor
666 protected $editoroptions = array();
669 * True if this is a standard page of false if it does something special.
670 * Questions are standard pages, branch tables are not
673 protected $standard = true;
676 * Each page type can and should override this to add any custom elements to
677 * the basic form that they want
679 public function custom_definition() {}
682 * Used to determine if this is a standard page or a special page
685 public final function is_standard() {
686 return (bool)$this->standard;
690 * Add the required basic elements to the form.
692 * This method adds the basic elements to the form including title and contents
693 * and then calls custom_definition();
695 public final function definition() {
696 $mform = $this->_form;
697 $editoroptions = $this->_customdata['editoroptions'];
699 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
701 $mform->addElement('hidden', 'id');
702 $mform->setType('id', PARAM_INT);
704 $mform->addElement('hidden', 'pageid');
705 $mform->setType('pageid', PARAM_INT);
707 if ($this->standard === true) {
708 $mform->addElement('hidden', 'qtype');
709 $mform->setType('qtype', PARAM_INT);
711 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
712 $mform->setType('title', PARAM_TEXT);
713 $mform->addRule('title', get_string('required'), 'required', null, 'client');
715 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
716 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
717 $mform->setType('contents_editor', PARAM_RAW);
718 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
721 $this->custom_definition();
723 if ($this->_customdata['edit'] === true) {
724 $mform->addElement('hidden', 'edit', 1);
725 $mform->setType('edit', PARAM_BOOL);
726 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
727 } else if ($this->qtype === 'questiontype') {
728 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
730 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
735 * Convenience function: Adds a jumpto select element
737 * @param string $name
738 * @param string|null $label
739 * @param int $selected The page to select by default
741 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
742 $title = get_string("jump", "lesson");
743 if ($label === null) {
747 $name = "jumpto[$name]";
749 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
750 $this->_form->setDefault($name, $selected);
751 $this->_form->addHelpButton($name, 'jumps', 'lesson');
755 * Convenience function: Adds a score input element
757 * @param string $name
758 * @param string|null $label
759 * @param mixed $value The default value
761 protected final function add_score($name, $label=null, $value=null) {
762 if ($label === null) {
763 $label = get_string("score", "lesson");
767 $name = "score[$name]";
769 $this->_form->addElement('text', $name, $label, array('size'=>5));
770 $this->_form->setType($name, PARAM_INT);
771 if ($value !== null) {
772 $this->_form->setDefault($name, $value);
777 * Convenience function: Adds an answer editor
779 * @param int $count The count of the element to add
780 * @param string $label, null means default
781 * @param bool $required
784 protected final function add_answer($count, $label = null, $required = false) {
785 if ($label === null) {
786 $label = get_string('answer', 'lesson');
788 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
789 $this->_form->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
791 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
795 * Convenience function: Adds an response editor
797 * @param int $count The count of the element to add
798 * @param string $label, null means default
799 * @param bool $required
802 protected final function add_response($count, $label = null, $required = false) {
803 if ($label === null) {
804 $label = get_string('response', 'lesson');
806 $this->_form->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
807 $this->_form->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
809 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
814 * A function that gets called upon init of this object by the calling script.
816 * This can be used to process an immediate action if required. Currently it
817 * is only used in special cases by non-standard page types.
821 public function construction_override($pageid, lesson $lesson) {
829 * Class representation of a lesson
831 * This class is used the interact with, and manage a lesson once instantiated.
832 * If you need to fetch a lesson object you can do so by calling
835 * lesson::load($lessonid);
837 * $lessonrecord = $DB->get_record('lesson', $lessonid);
838 * $lesson = new lesson($lessonrecord);
841 * The class itself extends lesson_base as all classes within the lesson module should
843 * These properties are from the database
844 * @property int $id The id of this lesson
845 * @property int $course The ID of the course this lesson belongs to
846 * @property string $name The name of this lesson
847 * @property int $practice Flag to toggle this as a practice lesson
848 * @property int $modattempts Toggle to allow the user to go back and review answers
849 * @property int $usepassword Toggle the use of a password for entry
850 * @property string $password The password to require users to enter
851 * @property int $dependency ID of another lesson this lesson is dependent on
852 * @property string $conditions Conditions of the lesson dependency
853 * @property int $grade The maximum grade a user can achieve (%)
854 * @property int $custom Toggle custom scoring on or off
855 * @property int $ongoing Toggle display of an ongoing score
856 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
857 * @property int $maxanswers The max number of answers or branches
858 * @property int $maxattempts The maximum number of attempts a user can record
859 * @property int $review Toggle use or wrong answer review button
860 * @property int $nextpagedefault Override the default next page
861 * @property int $feedback Toggles display of default feedback
862 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
863 * @property int $maxpages Maximum number of pages this lesson can contain
864 * @property int $retake Flag to allow users to retake a lesson
865 * @property int $activitylink Relate this lesson to another lesson
866 * @property string $mediafile File to pop up to or webpage to display
867 * @property int $mediaheight Sets the height of the media file popup
868 * @property int $mediawidth Sets the width of the media file popup
869 * @property int $mediaclose Toggle display of a media close button
870 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
871 * @property int $width Width of slideshow
872 * @property int $height Height of slideshow
873 * @property string $bgcolor Background colour of slideshow
874 * @property int $displayleft Display a left menu
875 * @property int $displayleftif Sets the condition on which the left menu is displayed
876 * @property int $progressbar Flag to toggle display of a lesson progress bar
877 * @property int $highscores Flag to toggle collection of high scores
878 * @property int $maxhighscores Number of high scores to limit to
879 * @property int $available Timestamp of when this lesson becomes available
880 * @property int $deadline Timestamp of when this lesson is no longer available
881 * @property int $timemodified Timestamp when lesson was last modified
883 * These properties are calculated
884 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
885 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
887 * @copyright 2009 Sam Hemelryk
888 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
890 class lesson extends lesson_base {
893 * The id of the first page (where prevpageid = 0) gets set and retrieved by
894 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
897 protected $firstpageid = null;
899 * The id of the last page (where nextpageid = 0) gets set and retrieved by
900 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
903 protected $lastpageid = null;
905 * An array used to cache the pages associated with this lesson after the first
906 * time they have been loaded.
907 * A note to developers: If you are going to be working with MORE than one or
908 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
909 * in order to save excess database queries.
910 * @var array An array of lesson_page objects
912 protected $pages = array();
914 * Flag that gets set to true once all of the pages associated with the lesson
918 protected $loadedallpages = false;
921 * Simply generates a lesson object given an array/object of properties
922 * Overrides {@see lesson_base->create()}
924 * @param object|array $properties
927 public static function create($properties) {
928 return new lesson($properties);
932 * Generates a lesson object from the database given its id
934 * @param int $lessonid
937 public static function load($lessonid) {
940 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
941 print_error('invalidcoursemodule');
943 return new lesson($lesson);
947 * Deletes this lesson from the database
949 public function delete() {
951 require_once($CFG->libdir.'/gradelib.php');
952 require_once($CFG->dirroot.'/calendar/lib.php');
954 $DB->delete_records("lesson", array("id"=>$this->properties->id));
955 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
956 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
957 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
958 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
959 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
960 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
961 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
962 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
963 foreach($events as $event) {
964 $event = calendar_event::load($event);
969 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
974 * Fetches messages from the session that may have been set in previous page
978 * // Do not call this method directly instead use
984 protected function get_messages() {
988 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
989 $messages = $SESSION->lesson_messages[$this->properties->id];
990 unset($SESSION->lesson_messages[$this->properties->id]);
997 * Get all of the attempts for the current user.
999 * @param int $retries
1000 * @param bool $correct Optional: only fetch correct attempts
1001 * @param int $pageid Optional: only fetch attempts at the given page
1002 * @param int $userid Optional: defaults to the current user if not set
1003 * @return array|false
1005 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1007 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1009 $params['correct'] = 1;
1011 if ($pageid !== null) {
1012 $params['pageid'] = $pageid;
1014 if ($userid === null) {
1015 $params['userid'] = $USER->id;
1017 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1021 * Returns the first page for the lesson or false if there isn't one.
1023 * This method should be called via the magic method __get();
1025 * $firstpage = $lesson->firstpage;
1028 * @return lesson_page|bool Returns the lesson_page specialised object or false
1030 protected function get_firstpage() {
1031 $pages = $this->load_all_pages();
1032 if (count($pages) > 0) {
1033 foreach ($pages as $page) {
1034 if ((int)$page->prevpageid === 0) {
1043 * Returns the last page for the lesson or false if there isn't one.
1045 * This method should be called via the magic method __get();
1047 * $lastpage = $lesson->lastpage;
1050 * @return lesson_page|bool Returns the lesson_page specialised object or false
1052 protected function get_lastpage() {
1053 $pages = $this->load_all_pages();
1054 if (count($pages) > 0) {
1055 foreach ($pages as $page) {
1056 if ((int)$page->nextpageid === 0) {
1065 * Returns the id of the first page of this lesson. (prevpageid = 0)
1068 protected function get_firstpageid() {
1070 if ($this->firstpageid == null) {
1071 if (!$this->loadedallpages) {
1072 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1073 if (!$firstpageid) {
1074 print_error('cannotfindfirstpage', 'lesson');
1076 $this->firstpageid = $firstpageid;
1078 $firstpage = $this->get_firstpage();
1079 $this->firstpageid = $firstpage->id;
1082 return $this->firstpageid;
1086 * Returns the id of the last page of this lesson. (nextpageid = 0)
1089 public function get_lastpageid() {
1091 if ($this->lastpageid == null) {
1092 if (!$this->loadedallpages) {
1093 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1095 print_error('cannotfindlastpage', 'lesson');
1097 $this->lastpageid = $lastpageid;
1099 $lastpageid = $this->get_lastpage();
1100 $this->lastpageid = $lastpageid->id;
1104 return $this->lastpageid;
1108 * Gets the next page id to display after the one that is provided.
1109 * @param int $nextpageid
1112 public function get_next_page($nextpageid) {
1114 $allpages = $this->load_all_pages();
1115 if ($this->properties->nextpagedefault) {
1116 // in Flash Card mode...first get number of retakes
1117 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1120 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1121 foreach ($allpages as $nextpage) {
1122 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1127 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1128 foreach ($allpages as $nextpage) {
1129 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1136 if ($this->properties->maxpages) {
1137 // check number of pages viewed (in the lesson)
1138 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1142 return $nextpage->id;
1145 // In a normal lesson mode
1146 foreach ($allpages as $nextpage) {
1147 if ((int)$nextpage->id === (int)$nextpageid) {
1148 return $nextpage->id;
1155 * Sets a message against the session for this lesson that will displayed next
1156 * time the lesson processes messages
1158 * @param string $message
1159 * @param string $class
1160 * @param string $align
1163 public function add_message($message, $class="notifyproblem", $align='center') {
1166 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1167 $SESSION->lesson_messages = array();
1168 $SESSION->lesson_messages[$this->properties->id] = array();
1169 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1170 $SESSION->lesson_messages[$this->properties->id] = array();
1173 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1179 * Check if the lesson is accessible at the present time
1180 * @return bool True if the lesson is accessible, false otherwise
1182 public function is_accessible() {
1183 $available = $this->properties->available;
1184 $deadline = $this->properties->deadline;
1185 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1189 * Starts the lesson time for the current user
1190 * @return bool Returns true
1192 public function start_timer() {
1195 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1198 // Trigger lesson started event.
1199 $event = \mod_lesson\event\lesson_started::create(array(
1200 'objectid' => $this->properties()->id,
1201 'context' => context_module::instance($cm->id),
1202 'courseid' => $this->properties()->course
1206 $USER->startlesson[$this->properties->id] = true;
1207 $startlesson = new stdClass;
1208 $startlesson->lessonid = $this->properties->id;
1209 $startlesson->userid = $USER->id;
1210 $startlesson->starttime = time();
1211 $startlesson->lessontime = time();
1212 $DB->insert_record('lesson_timer', $startlesson);
1213 if ($this->properties->timed) {
1214 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties->maxtime), 'center');
1220 * Updates the timer to the current time and returns the new timer object
1221 * @param bool $restart If set to true the timer is restarted
1222 * @param bool $continue If set to true AND $restart=true then the timer
1223 * will continue from a previous attempt
1224 * @return stdClass The new timer
1226 public function update_timer($restart=false, $continue=false) {
1229 // get time information for this user
1230 if (!$timer = $DB->get_records('lesson_timer', array ("lessonid" => $this->properties->id, "userid" => $USER->id), 'starttime DESC', '*', 0, 1)) {
1231 print_error('cannotfindtimer', 'lesson');
1233 $timer = current($timer); // this will get the latest start time record
1238 // continue a previous test, need to update the clock (think this option is disabled atm)
1239 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1241 // starting over, so reset the clock
1242 $timer->starttime = time();
1246 $timer->lessontime = time();
1247 $DB->update_record('lesson_timer', $timer);
1252 * Updates the timer to the current time then stops it by unsetting the user var
1253 * @return bool Returns true
1255 public function stop_timer() {
1257 unset($USER->startlesson[$this->properties->id]);
1259 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1262 // Trigger lesson ended event.
1263 $event = \mod_lesson\event\lesson_ended::create(array(
1264 'objectid' => $this->properties()->id,
1265 'context' => context_module::instance($cm->id),
1266 'courseid' => $this->properties()->course
1270 return $this->update_timer(false, false);
1274 * Checks to see if the lesson has pages
1276 public function has_pages() {
1278 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1279 return ($pagecount>0);
1283 * Returns the link for the related activity
1284 * @return array|false
1286 public function link_for_activitylink() {
1288 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1290 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1292 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1293 if ($instancename) {
1294 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1295 get_string('activitylinkname', 'lesson', $instancename),
1296 array('class'=>'centerpadded lessonbutton standardbutton'));
1304 * Loads the requested page.
1306 * This function will return the requested page id as either a specialised
1307 * lesson_page object OR as a generic lesson_page.
1308 * If the page has been loaded previously it will be returned from the pages
1309 * array, otherwise it will be loaded from the database first
1311 * @param int $pageid
1312 * @return lesson_page A lesson_page object or an object that extends it
1314 public function load_page($pageid) {
1315 if (!array_key_exists($pageid, $this->pages)) {
1316 $manager = lesson_page_type_manager::get($this);
1317 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1319 return $this->pages[$pageid];
1323 * Loads ALL of the pages for this lesson
1325 * @return array An array containing all pages from this lesson
1327 public function load_all_pages() {
1328 if (!$this->loadedallpages) {
1329 $manager = lesson_page_type_manager::get($this);
1330 $this->pages = $manager->load_all_pages($this);
1331 $this->loadedallpages = true;
1333 return $this->pages;
1337 * Determines if a jumpto value is correct or not.
1339 * returns true if jumpto page is (logically) after the pageid page or
1340 * if the jumpto value is a special value. Returns false in all other cases.
1342 * @param int $pageid Id of the page from which you are jumping from.
1343 * @param int $jumpto The jumpto number.
1344 * @return boolean True or false after a series of tests.
1346 public function jumpto_is_correct($pageid, $jumpto) {
1349 // first test the special values
1353 } elseif ($jumpto == LESSON_NEXTPAGE) {
1355 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1357 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1359 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1361 } elseif ($jumpto == LESSON_EOL) {
1365 $pages = $this->load_all_pages();
1366 $apageid = $pages[$pageid]->nextpageid;
1367 while ($apageid != 0) {
1368 if ($jumpto == $apageid) {
1371 $apageid = $pages[$apageid]->nextpageid;
1377 * Returns the time a user has remaining on this lesson
1378 * @param int $starttime Starttime timestamp
1381 public function time_remaining($starttime) {
1382 $timeleft = $starttime + $this->maxtime * 60 - time();
1383 $hours = floor($timeleft/3600);
1384 $timeleft = $timeleft - ($hours * 3600);
1385 $minutes = floor($timeleft/60);
1386 $secs = $timeleft - ($minutes * 60);
1388 if ($minutes < 10) {
1389 $minutes = "0$minutes";
1396 $output[] = $minutes;
1398 $output = implode(':', $output);
1403 * Interprets LESSON_CLUSTERJUMP jumpto value.
1405 * This will select a page randomly
1406 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1407 * and the page selected will be a page that has not been viewed already
1408 * and if any pages are within a branch table or end of branch then only 1 page within
1409 * the branch table or end of branch will be randomly selected (sub clustering).
1411 * @param int $pageid Id of the current page from which we are jumping from.
1412 * @param int $userid Id of the user.
1413 * @return int The id of the next page.
1415 public function cluster_jump($pageid, $userid=null) {
1418 if ($userid===null) {
1419 $userid = $USER->id;
1421 // get the number of retakes
1422 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1425 // get all the lesson_attempts aka what the user has seen
1426 $seenpages = array();
1427 if ($attempts = $this->get_attempts($retakes)) {
1428 foreach ($attempts as $attempt) {
1429 $seenpages[$attempt->pageid] = $attempt->pageid;
1434 // get the lesson pages
1435 $lessonpages = $this->load_all_pages();
1436 // find the start of the cluster
1437 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1438 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1441 $pageid = $lessonpages[$pageid]->prevpageid;
1444 $clusterpages = array();
1445 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1447 foreach ($clusterpages as $key=>$cluster) {
1448 if ($cluster->type !== lesson_page::TYPE_QUESTION) {
1449 unset($clusterpages[$key]);
1450 } elseif ($cluster->is_unseen($seenpages)) {
1451 $unseen[] = $cluster;
1455 if (count($unseen) > 0) {
1456 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1457 $nextpage = $unseen[rand(0, count($unseen)-1)];
1458 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1459 // if branch table, then pick a random page inside of it
1460 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1461 return $branchpages[rand(0, count($branchpages)-1)]->id;
1462 } else { // otherwise, return the page's id
1463 return $nextpage->id;
1466 // seen all there is to see, leave the cluster
1467 if (end($clusterpages)->nextpageid == 0) {
1470 $clusterendid = $pageid;
1471 while ($clusterendid != 0) { // this condition should not be satisfied... should be a cluster page
1472 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_CLUSTER) {
1475 $clusterendid = $lessonpages[$clusterendid]->prevpageid;
1477 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1478 if ($exitjump == LESSON_NEXTPAGE) {
1479 $exitjump = $lessonpages[$pageid]->nextpageid;
1481 if ($exitjump == 0) {
1483 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1486 if (!array_key_exists($exitjump, $lessonpages)) {
1488 foreach ($lessonpages as $page) {
1489 if ($page->id === $clusterendid) {
1491 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1492 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1497 if (!array_key_exists($exitjump, $lessonpages)) {
1507 * Finds all pages that appear to be a subtype of the provided pageid until
1508 * an end point specified within $ends is encountered or no more pages exist
1510 * @param int $pageid
1511 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1513 * @return array An array of specialised lesson_page objects
1515 public function get_sub_pages_of($pageid, array $ends) {
1516 $lessonpages = $this->load_all_pages();
1517 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1521 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1524 $pages[] = $lessonpages[$pageid];
1525 $pageid = $lessonpages[$pageid]->nextpageid;
1532 * Checks to see if the specified page[id] is a subpage of a type specified in
1533 * the $types array, until either there are no more pages of we find a type
1534 * corresponding to that of a type specified in $ends
1536 * @param int $pageid The id of the page to check
1537 * @param array $types An array of types that would signify this page was a subpage
1538 * @param array $ends An array of types that mean this is not a subpage
1541 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1542 $pages = $this->load_all_pages();
1543 $pageid = $pages[$pageid]->prevpageid; // move up one
1545 array_unshift($ends, 0);
1546 // go up the pages till branch table
1548 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1550 } else if (in_array($pages[$pageid]->qtype, $types)) {
1553 $pageid = $pages[$pageid]->prevpageid;
1560 * Abstract class to provide a core functions to the all lesson classes
1562 * This class should be abstracted by ALL classes with the lesson module to ensure
1563 * that all classes within this module can be interacted with in the same way.
1565 * This class provides the user with a basic properties array that can be fetched
1566 * or set via magic methods, or alternatively by defining methods get_blah() or
1567 * set_blah() within the extending object.
1569 * @copyright 2009 Sam Hemelryk
1570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1572 abstract class lesson_base {
1575 * An object containing properties
1578 protected $properties;
1582 * @param stdClass $properties
1584 public function __construct($properties) {
1585 $this->properties = (object)$properties;
1589 * Magic property method
1591 * Attempts to call a set_$key method if one exists otherwise falls back
1592 * to simply set the property
1594 * @param string $key
1595 * @param mixed $value
1597 public function __set($key, $value) {
1598 if (method_exists($this, 'set_'.$key)) {
1599 $this->{'set_'.$key}($value);
1601 $this->properties->{$key} = $value;
1607 * Attempts to call a get_$key method to return the property and ralls over
1608 * to return the raw property
1613 public function __get($key) {
1614 if (method_exists($this, 'get_'.$key)) {
1615 return $this->{'get_'.$key}();
1617 return $this->properties->{$key};
1621 * Stupid PHP needs an isset magic method if you use the get magic method and
1622 * still want empty calls to work.... blah ~!
1624 * @param string $key
1627 public function __isset($key) {
1628 if (method_exists($this, 'get_'.$key)) {
1629 $val = $this->{'get_'.$key}();
1630 return !empty($val);
1632 return !empty($this->properties->{$key});
1635 //NOTE: E_STRICT does not allow to change function signature!
1638 * If implemented should create a new instance, save it in the DB and return it
1640 //public static function create() {}
1642 * If implemented should load an instance from the DB and return it
1644 //public static function load() {}
1646 * Fetches all of the properties of the object
1649 public function properties() {
1650 return $this->properties;
1656 * Abstract class representation of a page associated with a lesson.
1658 * This class should MUST be extended by all specialised page types defined in
1659 * mod/lesson/pagetypes/.
1660 * There are a handful of abstract methods that need to be defined as well as
1661 * severl methods that can optionally be defined in order to make the page type
1662 * operate in the desired way
1664 * Database properties
1665 * @property int $id The id of this lesson page
1666 * @property int $lessonid The id of the lesson this page belongs to
1667 * @property int $prevpageid The id of the page before this one
1668 * @property int $nextpageid The id of the next page in the page sequence
1669 * @property int $qtype Identifies the page type of this page
1670 * @property int $qoption Used to record page type specific options
1671 * @property int $layout Used to record page specific layout selections
1672 * @property int $display Used to record page specific display selections
1673 * @property int $timecreated Timestamp for when the page was created
1674 * @property int $timemodified Timestamp for when the page was last modified
1675 * @property string $title The title of this page
1676 * @property string $contents The rich content shown to describe the page
1677 * @property int $contentsformat The format of the contents field
1679 * Calculated properties
1680 * @property-read array $answers An array of answers for this page
1681 * @property-read bool $displayinmenublock Toggles display in the left menu block
1682 * @property-read array $jumps An array containing all the jumps this page uses
1683 * @property-read lesson $lesson The lesson this page belongs to
1684 * @property-read int $type The type of the page [question | structure]
1685 * @property-read typeid The unique identifier for the page type
1686 * @property-read typestring The string that describes this page type
1689 * @copyright 2009 Sam Hemelryk
1690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1692 abstract class lesson_page extends lesson_base {
1695 * A reference to the lesson this page belongs to
1698 protected $lesson = null;
1700 * Contains the answers to this lesson_page once loaded
1703 protected $answers = null;
1705 * This sets the type of the page, can be one of the constants defined below
1708 protected $type = 0;
1711 * Constants used to identify the type of the page
1713 const TYPE_QUESTION = 0;
1714 const TYPE_STRUCTURE = 1;
1717 * This method should return the integer used to identify the page type within
1718 * the database and throughout code. This maps back to the defines used in 1.x
1722 abstract protected function get_typeid();
1724 * This method should return the string that describes the pagetype
1728 abstract protected function get_typestring();
1731 * This method gets called to display the page to the user taking the lesson
1733 * @param object $renderer
1734 * @param object $attempt
1737 abstract public function display($renderer, $attempt);
1740 * Creates a new lesson_page within the database and returns the correct pagetype
1741 * object to use to interact with the new lesson
1745 * @param object $properties
1746 * @param lesson $lesson
1747 * @return lesson_page Specialised object that extends lesson_page
1749 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
1751 $newpage = new stdClass;
1752 $newpage->title = $properties->title;
1753 $newpage->contents = $properties->contents_editor['text'];
1754 $newpage->contentsformat = $properties->contents_editor['format'];
1755 $newpage->lessonid = $lesson->id;
1756 $newpage->timecreated = time();
1757 $newpage->qtype = $properties->qtype;
1758 $newpage->qoption = (isset($properties->qoption))?1:0;
1759 $newpage->layout = (isset($properties->layout))?1:0;
1760 $newpage->display = (isset($properties->display))?1:0;
1761 $newpage->prevpageid = 0; // this is a first page
1762 $newpage->nextpageid = 0; // this is the only page
1764 if ($properties->pageid) {
1765 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
1767 print_error('cannotfindpages', 'lesson');
1769 $newpage->prevpageid = $prevpage->id;
1770 $newpage->nextpageid = $prevpage->nextpageid;
1772 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
1774 // This is the first page, there are existing pages put this at the start
1775 $newpage->nextpageid = $nextpage->id;
1779 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
1781 $editor = new stdClass;
1782 $editor->id = $newpage->id;
1783 $editor->contents_editor = $properties->contents_editor;
1784 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
1785 $DB->update_record("lesson_pages", $editor);
1787 if ($newpage->prevpageid > 0) {
1788 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
1790 if ($newpage->nextpageid > 0) {
1791 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
1794 $page = lesson_page::load($newpage, $lesson);
1795 $page->create_answers($properties);
1797 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
1803 * This method loads a page object from the database and returns it as a
1804 * specialised object that extends lesson_page
1809 * @param lesson $lesson
1810 * @return lesson_page Specialised lesson_page object
1812 final public static function load($id, lesson $lesson) {
1815 if (is_object($id) && !empty($id->qtype)) {
1818 $page = $DB->get_record("lesson_pages", array("id" => $id));
1820 print_error('cannotfindpages', 'lesson');
1823 $manager = lesson_page_type_manager::get($lesson);
1825 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
1826 if (!class_exists($class)) {
1827 $class = 'lesson_page';
1830 return new $class($page, $lesson);
1834 * Deletes a lesson_page from the database as well as any associated records.
1838 final public function delete() {
1840 // first delete all the associated records...
1841 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
1842 // ...now delete the answers...
1843 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
1844 // ..and the page itself
1845 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
1847 // repair the hole in the linkage
1848 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
1849 //This is the only page, no repair needed
1850 } elseif (!$this->properties->prevpageid) {
1851 // this is the first page...
1852 $page = $this->lesson->load_page($this->properties->nextpageid);
1853 $page->move(null, 0);
1854 } elseif (!$this->properties->nextpageid) {
1855 // this is the last page...
1856 $page = $this->lesson->load_page($this->properties->prevpageid);
1859 // page is in the middle...
1860 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
1861 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
1863 $prevpage->move($nextpage->id);
1864 $nextpage->move(null, $prevpage->id);
1870 * Moves a page by updating its nextpageid and prevpageid values within
1874 * @param int $nextpageid
1875 * @param int $prevpageid
1877 final public function move($nextpageid=null, $prevpageid=null) {
1879 if ($nextpageid === null) {
1880 $nextpageid = $this->properties->nextpageid;
1882 if ($prevpageid === null) {
1883 $prevpageid = $this->properties->prevpageid;
1885 $obj = new stdClass;
1886 $obj->id = $this->properties->id;
1887 $obj->prevpageid = $prevpageid;
1888 $obj->nextpageid = $nextpageid;
1889 $DB->update_record('lesson_pages', $obj);
1893 * Returns the answers that are associated with this page in the database
1898 final public function get_answers() {
1900 if ($this->answers === null) {
1901 $this->answers = array();
1902 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
1904 // It is possible that a lesson upgraded from Moodle 1.9 still
1905 // contains questions without any answers [MDL-25632].
1906 // debugging(get_string('cannotfindanswer', 'lesson'));
1909 foreach ($answers as $answer) {
1910 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
1913 return $this->answers;
1917 * Returns the lesson this page is associated with
1921 final protected function get_lesson() {
1922 return $this->lesson;
1926 * Returns the type of page this is. Not to be confused with page type
1930 final protected function get_type() {
1935 * Records an attempt at this page
1938 * @global moodle_database $DB
1939 * @param stdClass $context
1940 * @return stdClass Returns the result of the attempt
1942 final public function record_attempt($context) {
1943 global $DB, $USER, $OUTPUT;
1946 * This should be overridden by each page type to actually check the response
1947 * against what ever custom criteria they have defined
1949 $result = $this->check_answer();
1951 $result->attemptsremaining = 0;
1952 $result->maxattemptsreached = false;
1954 if ($result->noanswer) {
1955 $result->newpageid = $this->properties->id; // display same page again
1956 $result->feedback = get_string('noanswer', 'lesson');
1958 if (!has_capability('mod/lesson:manage', $context)) {
1959 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
1960 // record student's attempt
1961 $attempt = new stdClass;
1962 $attempt->lessonid = $this->lesson->id;
1963 $attempt->pageid = $this->properties->id;
1964 $attempt->userid = $USER->id;
1965 $attempt->answerid = $result->answerid;
1966 $attempt->retry = $nretakes;
1967 $attempt->correct = $result->correctanswer;
1968 if($result->userresponse !== null) {
1969 $attempt->useranswer = $result->userresponse;
1972 $attempt->timeseen = time();
1973 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
1974 if (isset($USER->modattempts[$this->lesson->id])) {
1975 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
1978 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
1979 $DB->insert_record("lesson_attempts", $attempt);
1981 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
1982 // displaying of message(s) is at the end of page for more ergonomic display
1983 if (!$result->correctanswer && ($result->newpageid == 0)) {
1984 // wrong answer and student is stuck on this page - check how many attempts
1985 // the student has had at this page/question
1986 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry" => $attempt->retry));
1987 // retreive the number of attempts left counter for displaying at bottom of feedback page
1988 if ($nattempts >= $this->lesson->maxattempts) {
1989 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
1990 $result->maxattemptsreached = true;
1992 $result->newpageid = LESSON_NEXTPAGE;
1993 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
1994 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
1998 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
1999 if ($result->newpageid == 0) {
2000 $result->newpageid = $this->properties->id;
2001 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
2002 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2005 // Determine default feedback if necessary
2006 if (empty($result->response)) {
2007 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2008 // These conditions have been met:
2009 // 1. The lesson manager has not supplied feedback to the student
2010 // 2. Not displaying default feedback
2011 // 3. The user did provide an answer
2012 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2014 $result->nodefaultresponse = true; // This will cause a redirect below
2015 } else if ($result->isessayquestion) {
2016 $result->response = get_string('defaultessayresponse', 'lesson');
2017 } else if ($result->correctanswer) {
2018 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2020 $result->response = get_string('thatsthewronganswer', 'lesson');
2024 if ($result->response) {
2025 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2026 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2027 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2028 if ($qattempts == 1) {
2029 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2031 $result->feedback = $OUTPUT->BOX(get_string("secondpluswrong", "lesson"), 'feedback');
2034 $class = 'response';
2035 if ($result->correctanswer) {
2036 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2037 } else if (!$result->isessayquestion) {
2038 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2040 $options = new stdClass;
2041 $options->noclean = true;
2042 $options->para = true;
2043 $options->overflowdiv = true;
2044 $result->feedback = $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 'generalbox boxaligncenter');
2045 $result->feedback .= '<div class="correctanswer generalbox"><em>'.get_string("youranswer", "lesson").'</em> : '.$result->studentanswer; // already in clean html
2046 $result->feedback .= $OUTPUT->box($result->response, $class); // already conerted to HTML
2047 $result->feedback .= '</div>';
2056 * Returns the string for a jump name
2059 * @param int $jumpto Jump code or page ID
2062 final protected function get_jump_name($jumpto) {
2064 static $jumpnames = array();
2066 if (!array_key_exists($jumpto, $jumpnames)) {
2067 if ($jumpto == LESSON_THISPAGE) {
2068 $jumptitle = get_string('thispage', 'lesson');
2069 } elseif ($jumpto == LESSON_NEXTPAGE) {
2070 $jumptitle = get_string('nextpage', 'lesson');
2071 } elseif ($jumpto == LESSON_EOL) {
2072 $jumptitle = get_string('endoflesson', 'lesson');
2073 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2074 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2075 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2076 $jumptitle = get_string('previouspage', 'lesson');
2077 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2078 $jumptitle = get_string('randompageinbranch', 'lesson');
2079 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2080 $jumptitle = get_string('randombranch', 'lesson');
2081 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2082 $jumptitle = get_string('clusterjump', 'lesson');
2084 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2085 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2088 $jumpnames[$jumpto] = format_string($jumptitle,true);
2091 return $jumpnames[$jumpto];
2095 * Constructor method
2096 * @param object $properties
2097 * @param lesson $lesson
2099 public function __construct($properties, lesson $lesson) {
2100 parent::__construct($properties);
2101 $this->lesson = $lesson;
2105 * Returns the score for the attempt
2106 * This may be overridden by page types that require manual grading
2107 * @param array $answers
2108 * @param object $attempt
2111 public function earned_score($answers, $attempt) {
2112 return $answers[$attempt->answerid]->score;
2116 * This is a callback method that can be override and gets called when ever a page
2119 * @param bool $canmanage True if the user has the manage cap
2122 public function callback_on_view($canmanage) {
2127 * Updates a lesson page and its answers within the database
2129 * @param object $properties
2132 public function update($properties, $context = null, $maxbytes = null) {
2134 $answers = $this->get_answers();
2135 $properties->id = $this->properties->id;
2136 $properties->lessonid = $this->lesson->id;
2137 if (empty($properties->qoption)) {
2138 $properties->qoption = '0';
2140 if (empty($context)) {
2141 $context = $PAGE->context;
2143 if ($maxbytes === null) {
2144 $maxbytes = get_user_max_upload_file_size($context);
2146 $properties->timemodified = time();
2147 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2148 $DB->update_record("lesson_pages", $properties);
2150 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2151 if (!array_key_exists($i, $this->answers)) {
2152 $this->answers[$i] = new stdClass;
2153 $this->answers[$i]->lessonid = $this->lesson->id;
2154 $this->answers[$i]->pageid = $this->id;
2155 $this->answers[$i]->timecreated = $this->timecreated;
2158 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2159 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2160 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2162 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2163 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2164 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
2167 // we don't need to check for isset here because properties called it's own isset method.
2168 if ($this->answers[$i]->answer != '') {
2169 if (isset($properties->jumpto[$i])) {
2170 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2172 if ($this->lesson->custom && isset($properties->score[$i])) {
2173 $this->answers[$i]->score = $properties->score[$i];
2175 if (!isset($this->answers[$i]->id)) {
2176 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2178 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2181 } else if (isset($this->answers[$i]->id)) {
2182 $DB->delete_records('lesson_answers', array('id'=>$this->answers[$i]->id));
2183 unset($this->answers[$i]);
2190 * Can be set to true if the page requires a static link to create a new instance
2191 * instead of simply being included in the dropdown
2192 * @param int $previd
2195 public function add_page_link($previd) {
2200 * Returns true if a page has been viewed before
2202 * @param array|int $param Either an array of pages that have been seen or the
2203 * number of retakes a user has had
2206 public function is_unseen($param) {
2208 if (is_array($param)) {
2209 $seenpages = $param;
2210 return (!array_key_exists($this->properties->id, $seenpages));
2213 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2221 * Checks to see if a page has been answered previously
2222 * @param int $nretakes
2225 public function is_unanswered($nretakes) {
2227 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2234 * Creates answers within the database for this lesson_page. Usually only ever
2235 * called when creating a new page instance
2236 * @param object $properties
2239 public function create_answers($properties) {
2241 // now add the answers
2242 $newanswer = new stdClass;
2243 $newanswer->lessonid = $this->lesson->id;
2244 $newanswer->pageid = $this->properties->id;
2245 $newanswer->timecreated = $this->properties->timecreated;
2249 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2250 $answer = clone($newanswer);
2252 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2253 $answer->answer = $properties->answer_editor[$i]['text'];
2254 $answer->answerformat = $properties->answer_editor[$i]['format'];
2256 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2257 $answer->response = $properties->response_editor[$i]['text'];
2258 $answer->responseformat = $properties->response_editor[$i]['format'];
2261 if (isset($answer->answer) && $answer->answer != '') {
2262 if (isset($properties->jumpto[$i])) {
2263 $answer->jumpto = $properties->jumpto[$i];
2265 if ($this->lesson->custom && isset($properties->score[$i])) {
2266 $answer->score = $properties->score[$i];
2268 $answer->id = $DB->insert_record("lesson_answers", $answer);
2269 $answers[$answer->id] = new lesson_page_answer($answer);
2275 $this->answers = $answers;
2280 * This method MUST be overridden by all question page types, or page types that
2281 * wish to score a page.
2283 * The structure of result should always be the same so it is a good idea when
2284 * overriding this method on a page type to call
2286 * $result = parent::check_answer();
2288 * before modifying it as required.
2292 public function check_answer() {
2293 $result = new stdClass;
2294 $result->answerid = 0;
2295 $result->noanswer = false;
2296 $result->correctanswer = false;
2297 $result->isessayquestion = false; // use this to turn off review button on essay questions
2298 $result->response = '';
2299 $result->newpageid = 0; // stay on the page
2300 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2301 $result->userresponse = null;
2302 $result->feedback = '';
2303 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2308 * True if the page uses a custom option
2310 * Should be override and set to true if the page uses a custom option.
2314 public function has_option() {
2319 * Returns the maximum number of answers for this page given the maximum number
2320 * of answers permitted by the lesson.
2322 * @param int $default
2325 public function max_answers($default) {
2330 * Returns the properties of this lesson page as an object
2333 public function properties() {
2334 $properties = clone($this->properties);
2335 if ($this->answers === null) {
2336 $this->get_answers();
2338 if (count($this->answers)>0) {
2340 $qtype = $properties->qtype;
2341 foreach ($this->answers as $answer) {
2342 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
2343 if ($qtype != LESSON_PAGE_MATCHING) {
2344 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
2346 $properties->{'response_editor['.$count.']'} = $answer->response;
2348 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2349 $properties->{'score['.$count.']'} = $answer->score;
2357 * Returns an array of options to display when choosing the jumpto for a page/answer
2359 * @param int $pageid
2360 * @param lesson $lesson
2363 public static function get_jumptooptions($pageid, lesson $lesson) {
2366 $jump[0] = get_string("thispage", "lesson");
2367 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2368 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2369 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2375 $pages = $lesson->load_all_pages();
2376 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))) {
2377 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
2378 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
2380 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
2381 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
2383 if (!optional_param('firstpage', 0, PARAM_INT)) {
2384 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
2387 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2388 $jump[$apageid] = strip_tags(format_string($title,true));
2389 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2391 // last page reached
2399 * Returns the contents field for the page properly formatted and with plugin
2400 * file url's converted
2403 public function get_contents() {
2405 if (!empty($this->properties->contents)) {
2406 if (!isset($this->properties->contentsformat)) {
2407 $this->properties->contentsformat = FORMAT_HTML;
2409 $context = context_module::instance($PAGE->cm->id);
2410 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
2411 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
2412 return format_text($contents, $this->properties->contentsformat,
2413 array('context' => $context, 'noclean' => true,
2414 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
2421 * Set to true if this page should display in the menu block
2424 protected function get_displayinmenublock() {
2429 * Get the string that describes the options of this page type
2432 public function option_description_string() {
2437 * Updates a table with the answers for this page
2438 * @param html_table $table
2439 * @return html_table
2441 public function display_answers(html_table $table) {
2442 $answers = $this->get_answers();
2444 foreach ($answers as $answer) {
2446 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2447 $cells[] = $this->get_jump_name($answer->jumpto);
2448 $table->data[] = new html_table_row($cells);
2450 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
2458 * Determines if this page should be grayed out on the management/report screens
2459 * @return int 0 or 1
2461 protected function get_grayout() {
2466 * Adds stats for this page to the &pagestats object. This should be defined
2467 * for all page types that grade
2468 * @param array $pagestats
2472 public function stats(array &$pagestats, $tries) {
2477 * Formats the answers of this page for a report
2479 * @param object $answerpage
2480 * @param object $answerdata
2481 * @param object $useranswer
2482 * @param array $pagestats
2483 * @param int $i Count of first level answers
2484 * @param int $n Count of second level answers
2485 * @return object The answer page for this
2487 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2488 $answers = $this->get_answers();
2489 $formattextdefoptions = new stdClass;
2490 $formattextdefoptions->para = false; //I'll use it widely in this page
2491 foreach ($answers as $answer) {
2492 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
2493 $answerdata->answers[] = array($data, "");
2494 $answerpage->answerdata = $answerdata;
2500 * Gets an array of the jumps used by the answers of this page
2504 public function get_jumps() {
2507 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
2508 if ($answers = $this->get_answers()) {
2509 foreach ($answers as $answer) {
2510 $jumps[] = $this->get_jump_name($answer->jumpto);
2513 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
2518 * Informs whether this page type require manual grading or not
2521 public function requires_manual_grading() {
2526 * A callback method that allows a page to override the next page a user will
2527 * see during when this page is being completed.
2530 public function override_next_page() {
2535 * This method is used to determine if this page is a valid page
2537 * @param array $validpages
2538 * @param array $pageviews
2539 * @return int The next page id to check
2541 public function valid_page_and_view(&$validpages, &$pageviews) {
2542 $validpages[$this->properties->id] = 1;
2543 return $this->properties->nextpageid;
2550 * Class used to represent an answer to a page
2552 * @property int $id The ID of this answer in the database
2553 * @property int $lessonid The ID of the lesson this answer belongs to
2554 * @property int $pageid The ID of the page this answer belongs to
2555 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2556 * @property int $grade The grade this answer is worth
2557 * @property int $score The score this answer will give
2558 * @property int $flags Used to store options for the answer
2559 * @property int $timecreated A timestamp of when the answer was created
2560 * @property int $timemodified A timestamp of when the answer was modified
2561 * @property string $answer The answer itself
2562 * @property string $response The response the user sees if selecting this answer
2564 * @copyright 2009 Sam Hemelryk
2565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2567 class lesson_page_answer extends lesson_base {
2570 * Loads an page answer from the DB
2573 * @return lesson_page_answer
2575 public static function load($id) {
2577 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2578 return new lesson_page_answer($answer);
2582 * Given an object of properties and a page created answer(s) and saves them
2585 * @param stdClass $properties
2586 * @param lesson_page $page
2589 public static function create($properties, lesson_page $page) {
2590 return $page->create_answers($properties);
2596 * A management class for page types
2598 * This class is responsible for managing the different pages. A manager object can
2599 * be retrieved by calling the following line of code:
2601 * $manager = lesson_page_type_manager::get($lesson);
2603 * The first time the page type manager is retrieved the it includes all of the
2604 * different page types located in mod/lesson/pagetypes.
2606 * @copyright 2009 Sam Hemelryk
2607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2609 class lesson_page_type_manager {
2612 * An array of different page type classes
2615 protected $types = array();
2618 * Retrieves the lesson page type manager object
2620 * If the object hasn't yet been created it is created here.
2622 * @staticvar lesson_page_type_manager $pagetypemanager
2623 * @param lesson $lesson
2624 * @return lesson_page_type_manager
2626 public static function get(lesson $lesson) {
2627 static $pagetypemanager;
2628 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
2629 $pagetypemanager = new lesson_page_type_manager();
2630 $pagetypemanager->load_lesson_types($lesson);
2632 return $pagetypemanager;
2636 * Finds and loads all lesson page types in mod/lesson/pagetypes
2638 * @param lesson $lesson
2640 public function load_lesson_types(lesson $lesson) {
2642 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
2643 $dir = dir($basedir);
2644 while (false !== ($entry = $dir->read())) {
2645 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2648 require_once($basedir.$entry);
2649 $class = 'lesson_page_type_'.strtok($entry,'.');
2650 if (class_exists($class)) {
2651 $pagetype = new $class(new stdClass, $lesson);
2652 $this->types[$pagetype->typeid] = $pagetype;
2659 * Returns an array of strings to describe the loaded page types
2661 * @param int $type Can be used to return JUST the string for the requested type
2664 public function get_page_type_strings($type=null, $special=true) {
2666 foreach ($this->types as $pagetype) {
2667 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
2668 $types[$pagetype->typeid] = $pagetype->typestring;
2675 * Returns the basic string used to identify a page type provided with an id
2677 * This string can be used to instantiate or identify the page type class.
2678 * If the page type id is unknown then 'unknown' is returned
2683 public function get_page_type_idstring($id) {
2684 foreach ($this->types as $pagetype) {
2685 if ((int)$pagetype->typeid === (int)$id) {
2686 return $pagetype->idstring;
2693 * Loads a page for the provided lesson given it's id
2695 * This function loads a page from the lesson when given both the lesson it belongs
2696 * to as well as the page's id.
2697 * If the page doesn't exist an error is thrown
2699 * @param int $pageid The id of the page to load
2700 * @param lesson $lesson The lesson the page belongs to
2701 * @return lesson_page A class that extends lesson_page
2703 public function load_page($pageid, lesson $lesson) {
2705 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
2706 print_error('cannotfindpages', 'lesson');
2708 $pagetype = get_class($this->types[$page->qtype]);
2709 $page = new $pagetype($page, $lesson);
2714 * This function detects errors in the ordering between 2 pages and updates the page records.
2716 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
2717 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
2719 protected function check_page_order($page1, $page2) {
2721 if (empty($page1)) {
2722 if ($page2->prevpageid != 0) {
2723 debugging("***prevpageid of page " . $page2->id . " set to 0***");
2724 $page2->prevpageid = 0;
2725 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
2727 } else if (empty($page2)) {
2728 if ($page1->nextpageid != 0) {
2729 debugging("***nextpageid of page " . $page1->id . " set to 0***");
2730 $page1->nextpageid = 0;
2731 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
2734 if ($page1->nextpageid != $page2->id) {
2735 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
2736 $page1->nextpageid = $page2->id;
2737 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
2739 if ($page2->prevpageid != $page1->id) {
2740 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
2741 $page2->prevpageid = $page1->id;
2742 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
2748 * This function loads ALL pages that belong to the lesson.
2750 * @param lesson $lesson
2751 * @return array An array of lesson_page_type_*
2753 public function load_all_pages(lesson $lesson) {
2755 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
2756 print_error('cannotfindpages', 'lesson');
2758 foreach ($pages as $key=>$page) {
2759 $pagetype = get_class($this->types[$page->qtype]);
2760 $pages[$key] = new $pagetype($page, $lesson);
2763 $orderedpages = array();
2766 while ($morepages) {
2768 foreach ($pages as $page) {
2769 if ((int)$page->prevpageid === (int)$lastpageid) {
2770 // Check for errors in page ordering and fix them on the fly.
2772 if ($lastpageid !== 0) {
2773 $prevpage = $orderedpages[$lastpageid];
2775 $this->check_page_order($prevpage, $page);
2777 $orderedpages[$page->id] = $page;
2778 unset($pages[$page->id]);
2779 $lastpageid = $page->id;
2780 if ((int)$page->nextpageid===0) {
2789 // Add remaining pages and fix the nextpageid links for each page.
2790 foreach ($pages as $page) {
2791 // Check for errors in page ordering and fix them on the fly.
2793 if ($lastpageid !== 0) {
2794 $prevpage = $orderedpages[$lastpageid];
2796 $this->check_page_order($prevpage, $page);
2797 $orderedpages[$page->id] = $page;
2798 unset($pages[$page->id]);
2799 $lastpageid = $page->id;
2802 if ($lastpageid !== 0) {
2803 $this->check_page_order($orderedpages[$lastpageid], null);
2806 return $orderedpages;
2810 * Fetches an mform that can be used to create/edit an page
2812 * @param int $type The id for the page type
2813 * @param array $arguments Any arguments to pass to the mform
2814 * @return lesson_add_page_form_base
2816 public function get_page_form($type, $arguments) {
2817 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
2818 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
2819 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
2820 $class = 'lesson_add_page_form_selection';
2821 } else if ($class === 'lesson_add_page_form_unknown') {
2822 $class = 'lesson_add_page_form_selection';
2824 return new $class(null, $arguments);
2828 * Returns an array of links to use as add page links
2829 * @param int $previd The id of the previous page
2832 public function get_add_page_type_links($previd) {
2837 foreach ($this->types as $key=>$type) {
2838 if ($link = $type->add_page_link($previd)) {
2839 $links[$key] = $link;