MDL-44732 add cli script for execution of scheduled tasks
[moodle.git] / mod / lesson / locallib.php
blob0eb7e06e28724a0ef9e8fa887e682d020a717281
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Local library file for Lesson. These are non-standard functions that are used
20 * only by Lesson.
22 * @package mod_lesson
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
25 **/
27 /** Make sure this isn't being directly accessed */
28 defined('MOODLE_INTERNAL') || die();
30 /** Include the files that are required by this module */
31 require_once($CFG->dirroot.'/course/moodleform_mod.php');
32 require_once($CFG->dirroot . '/mod/lesson/lib.php');
33 require_once($CFG->libdir . '/filelib.php');
35 /** This page */
36 define('LESSON_THISPAGE', 0);
37 /** Next page -> any page not seen before */
38 define("LESSON_UNSEENPAGE", 1);
39 /** Next page -> any page not answered correctly */
40 define("LESSON_UNANSWEREDPAGE", 2);
41 /** Jump to Next Page */
42 define("LESSON_NEXTPAGE", -1);
43 /** End of Lesson */
44 define("LESSON_EOL", -9);
45 /** Jump to an unseen page within a branch and end of branch or end of lesson */
46 define("LESSON_UNSEENBRANCHPAGE", -50);
47 /** Jump to Previous Page */
48 define("LESSON_PREVIOUSPAGE", -40);
49 /** Jump to a random page within a branch and end of branch or end of lesson */
50 define("LESSON_RANDOMPAGE", -60);
51 /** Jump to a random Branch */
52 define("LESSON_RANDOMBRANCH", -70);
53 /** Cluster Jump */
54 define("LESSON_CLUSTERJUMP", -80);
55 /** Undefined */
56 define("LESSON_UNDEFINED", -99);
58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59 define("LESSON_MAX_EVENT_LENGTH", "432000");
62 //////////////////////////////////////////////////////////////////////////////////////
63 /// Any other lesson functions go here. Each of them must have a name that
64 /// starts with lesson_
66 /**
67 * Checks to see if a LESSON_CLUSTERJUMP or
68 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
70 * This function is only executed when a teacher is
71 * checking the navigation for a lesson.
73 * @param stdClass $lesson Id of the lesson that is to be checked.
74 * @return boolean True or false.
75 **/
76 function lesson_display_teacher_warning($lesson) {
77 global $DB;
79 // get all of the lesson answers
80 $params = array ("lessonid" => $lesson->id);
81 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
82 // no answers, then not using cluster or unseen
83 return false;
85 // just check for the first one that fulfills the requirements
86 foreach ($lessonanswers as $lessonanswer) {
87 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
88 return true;
92 // if no answers use either of the two jumps
93 return false;
96 /**
97 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
99 * will return the pageid of a random unseen page that is within a branch
101 * @param lesson $lesson
102 * @param int $userid Id of the user.
103 * @param int $pageid Id of the page from which we are jumping.
104 * @return int Id of the next page.
106 function lesson_unseen_question_jump($lesson, $user, $pageid) {
107 global $DB;
109 // get the number of retakes
110 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
111 $retakes = 0;
114 // get all the lesson_attempts aka what the user has seen
115 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
116 foreach($viewedpages as $viewed) {
117 $seenpages[] = $viewed->pageid;
119 } else {
120 $seenpages = array();
123 // get the lesson pages
124 $lessonpages = $lesson->load_all_pages();
126 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
127 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
130 // go up the pages till branch table
131 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
132 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
133 break;
135 $pageid = $lessonpages[$pageid]->prevpageid;
138 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
140 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
141 $unseen = array();
142 foreach($pagesinbranch as $page) {
143 if (!in_array($page->id, $seenpages)) {
144 $unseen[] = $page->id;
148 if(count($unseen) == 0) {
149 if(isset($pagesinbranch)) {
150 $temp = end($pagesinbranch);
151 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
152 } else {
153 // there are no pages inside the branch, so return the next page
154 $nextpage = $lessonpages[$pageid]->nextpageid;
156 if ($nextpage == 0) {
157 return LESSON_EOL;
158 } else {
159 return $nextpage;
161 } else {
162 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
167 * Handles the unseen branch table jump.
169 * @param lesson $lesson
170 * @param int $userid User id.
171 * @return int Will return the page id of a branch table or end of lesson
173 function lesson_unseen_branch_jump($lesson, $userid) {
174 global $DB;
176 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
177 $retakes = 0;
180 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
181 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
182 "timeseen DESC")) {
183 print_error('cannotfindrecords', 'lesson');
186 // get the lesson pages
187 $lessonpages = $lesson->load_all_pages();
189 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
190 // which is the branch table that starts the unseenbranch function
191 $seen = array();
192 foreach ($seenbranches as $seenbranch) {
193 if (!$seenbranch->flag) {
194 $seen[$seenbranch->pageid] = $seenbranch->pageid;
195 } else {
196 $start = $seenbranch->pageid;
197 break;
200 // this function searches through the lesson pages to find all the branch tables
201 // that follow the flagged branch table
202 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
203 $branchtables = array();
204 while ($pageid != 0) { // grab all of the branch table till eol
205 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
206 $branchtables[] = $lessonpages[$pageid]->id;
208 $pageid = $lessonpages[$pageid]->nextpageid;
210 $unseen = array();
211 foreach ($branchtables as $branchtable) {
212 // load all of the unseen branch tables into unseen
213 if (!array_key_exists($branchtable, $seen)) {
214 $unseen[] = $branchtable;
217 if (count($unseen) > 0) {
218 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
219 } else {
220 return LESSON_EOL; // has viewed all of the branch tables
225 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
227 * @param lesson $lesson
228 * @param int $pageid The id of the page that we are jumping from (?)
229 * @return int The pageid of a random page that is within a branch table
231 function lesson_random_question_jump($lesson, $pageid) {
232 global $DB;
234 // get the lesson pages
235 $params = array ("lessonid" => $lesson->id);
236 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
237 print_error('cannotfindpages', 'lesson');
240 // go up the pages till branch table
241 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
243 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
244 break;
246 $pageid = $lessonpages[$pageid]->prevpageid;
249 // get the pages within the branch
250 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
252 if(count($pagesinbranch) == 0) {
253 // there are no pages inside the branch, so return the next page
254 return $lessonpages[$pageid]->nextpageid;
255 } else {
256 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
261 * Calculates a user's grade for a lesson.
263 * @param object $lesson The lesson that the user is taking.
264 * @param int $retries The attempt number.
265 * @param int $userid Id of the user (optional, default current user).
266 * @return object { nquestions => number of questions answered
267 attempts => number of question attempts
268 total => max points possible
269 earned => points earned by student
270 grade => calculated percentage grade
271 nmanual => number of manually graded questions
272 manualpoints => point value for manually graded questions }
274 function lesson_grade($lesson, $ntries, $userid = 0) {
275 global $USER, $DB;
277 if (empty($userid)) {
278 $userid = $USER->id;
281 // Zero out everything
282 $ncorrect = 0;
283 $nviewed = 0;
284 $score = 0;
285 $nmanual = 0;
286 $manualpoints = 0;
287 $thegrade = 0;
288 $nquestions = 0;
289 $total = 0;
290 $earned = 0;
292 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
293 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
294 userid = :userid AND retry = :retry", $params, "timeseen")) {
295 // group each try with its page
296 $attemptset = array();
297 foreach ($useranswers as $useranswer) {
298 $attemptset[$useranswer->pageid][] = $useranswer;
301 // Drop all attempts that go beyond max attempts for the lesson
302 foreach ($attemptset as $key => $set) {
303 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
306 // get only the pages and their answers that the user answered
307 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
308 array_unshift($parameters, $lesson->id);
309 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
310 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
312 // Number of pages answered
313 $nquestions = count($pages);
315 foreach ($attemptset as $attempts) {
316 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
317 if ($lesson->custom) {
318 $attempt = end($attempts);
319 // If essay question, handle it, otherwise add to score
320 if ($page->requires_manual_grading()) {
321 $useranswerobj = unserialize($attempt->useranswer);
322 if (isset($useranswerobj->score)) {
323 $earned += $useranswerobj->score;
325 $nmanual++;
326 $manualpoints += $answers[$attempt->answerid]->score;
327 } else if (!empty($attempt->answerid)) {
328 $earned += $page->earned_score($answers, $attempt);
330 } else {
331 foreach ($attempts as $attempt) {
332 $earned += $attempt->correct;
334 $attempt = end($attempts); // doesn't matter which one
335 // If essay question, increase numbers
336 if ($page->requires_manual_grading()) {
337 $nmanual++;
338 $manualpoints++;
341 // Number of times answered
342 $nviewed += count($attempts);
345 if ($lesson->custom) {
346 $bestscores = array();
347 // Find the highest possible score per page to get our total
348 foreach ($answers as $answer) {
349 if(!isset($bestscores[$answer->pageid])) {
350 $bestscores[$answer->pageid] = $answer->score;
351 } else if ($bestscores[$answer->pageid] < $answer->score) {
352 $bestscores[$answer->pageid] = $answer->score;
355 $total = array_sum($bestscores);
356 } else {
357 // Check to make sure the student has answered the minimum questions
358 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
359 // Nope, increase number viewed by the amount of unanswered questions
360 $total = $nviewed + ($lesson->minquestions - $nquestions);
361 } else {
362 $total = $nviewed;
367 if ($total) { // not zero
368 $thegrade = round(100 * $earned / $total, 5);
371 // Build the grade information object
372 $gradeinfo = new stdClass;
373 $gradeinfo->nquestions = $nquestions;
374 $gradeinfo->attempts = $nviewed;
375 $gradeinfo->total = $total;
376 $gradeinfo->earned = $earned;
377 $gradeinfo->grade = $thegrade;
378 $gradeinfo->nmanual = $nmanual;
379 $gradeinfo->manualpoints = $manualpoints;
381 return $gradeinfo;
385 * Determines if a user can view the left menu. The determining factor
386 * is whether a user has a grade greater than or equal to the lesson setting
387 * of displayleftif
389 * @param object $lesson Lesson object of the current lesson
390 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
392 function lesson_displayleftif($lesson) {
393 global $CFG, $USER, $DB;
395 if (!empty($lesson->displayleftif)) {
396 // get the current user's max grade for this lesson
397 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
398 if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
399 if ($maxgrade->maxgrade < $lesson->displayleftif) {
400 return 0; // turn off the displayleft
402 } else {
403 return 0; // no grades
407 // if we get to here, keep the original state of displayleft lesson setting
408 return $lesson->displayleft;
413 * @param $cm
414 * @param $lesson
415 * @param $page
416 * @return unknown_type
418 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
419 $bc = lesson_menu_block_contents($cm->id, $lesson);
420 if (!empty($bc)) {
421 $regions = $page->blocks->get_regions();
422 $firstregion = reset($regions);
423 $page->blocks->add_fake_block($bc, $firstregion);
426 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
427 if (!empty($bc)) {
428 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
431 if (!empty($timer)) {
432 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
433 if (!empty($bc)) {
434 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
440 * If there is a media file associated with this
441 * lesson, return a block_contents that displays it.
443 * @param int $cmid Course Module ID for this lesson
444 * @param object $lesson Full lesson record object
445 * @return block_contents
447 function lesson_mediafile_block_contents($cmid, $lesson) {
448 global $OUTPUT;
449 if (empty($lesson->mediafile)) {
450 return null;
453 $options = array();
454 $options['menubar'] = 0;
455 $options['location'] = 0;
456 $options['left'] = 5;
457 $options['top'] = 5;
458 $options['scrollbars'] = 1;
459 $options['resizable'] = 1;
460 $options['width'] = $lesson->mediawidth;
461 $options['height'] = $lesson->mediaheight;
463 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
464 $action = new popup_action('click', $link, 'lessonmediafile', $options);
465 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
467 $bc = new block_contents();
468 $bc->title = get_string('linkedmedia', 'lesson');
469 $bc->attributes['class'] = 'mediafile';
470 $bc->content = $content;
472 return $bc;
476 * If a timed lesson and not a teacher, then
477 * return a block_contents containing the clock.
479 * @param int $cmid Course Module ID for this lesson
480 * @param object $lesson Full lesson record object
481 * @param object $timer Full timer record object
482 * @return block_contents
484 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
485 // Display for timed lessons and for students only
486 $context = context_module::instance($cmid);
487 if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) {
488 return null;
491 $content = '<div class="jshidewhenenabled">';
492 $content .= $lesson->time_remaining($timer->starttime);
493 $content .= '</div>';
495 $clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
496 $page->requires->data_for_js('clocksettings', $clocksettings);
497 $page->requires->js('/mod/lesson/timer.js');
498 $page->requires->js_function_call('show_clock');
500 $bc = new block_contents();
501 $bc->title = get_string('timeremaining', 'lesson');
502 $bc->attributes['class'] = 'clock block';
503 $bc->content = $content;
505 return $bc;
509 * If left menu is turned on, then this will
510 * print the menu in a block
512 * @param int $cmid Course Module ID for this lesson
513 * @param lesson $lesson Full lesson record object
514 * @return void
516 function lesson_menu_block_contents($cmid, $lesson) {
517 global $CFG, $DB;
519 if (!$lesson->displayleft) {
520 return null;
523 $pages = $lesson->load_all_pages();
524 foreach ($pages as $page) {
525 if ((int)$page->prevpageid === 0) {
526 $pageid = $page->id;
527 break;
530 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
532 if (!$pageid || !$pages) {
533 return null;
536 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
538 while ($pageid != 0) {
539 $page = $pages[$pageid];
541 // Only process branch tables with display turned on
542 if ($page->displayinmenublock && $page->display) {
543 if ($page->id == $currentpageid) {
544 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
545 } else {
546 $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";
550 $pageid = $page->nextpageid;
552 $content .= "</ul>\n</div>\n";
554 $bc = new block_contents();
555 $bc->title = get_string('lessonmenu', 'lesson');
556 $bc->attributes['class'] = 'menu block';
557 $bc->content = $content;
559 return $bc;
563 * Adds header buttons to the page for the lesson
565 * @param object $cm
566 * @param object $context
567 * @param bool $extraeditbuttons
568 * @param int $lessonpageid
570 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
571 global $CFG, $PAGE, $OUTPUT;
572 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
573 if ($lessonpageid === null) {
574 print_error('invalidpageid', 'lesson');
576 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
577 $url = new moodle_url('/mod/lesson/editpage.php', array('id'=>$cm->id, 'pageid'=>$lessonpageid, 'edit'=>1));
578 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
584 * This is a function used to detect media types and generate html code.
586 * @global object $CFG
587 * @global object $PAGE
588 * @param object $lesson
589 * @param object $context
590 * @return string $code the html code of media
592 function lesson_get_media_html($lesson, $context) {
593 global $CFG, $PAGE, $OUTPUT;
594 require_once("$CFG->libdir/resourcelib.php");
596 // get the media file link
597 if (strpos($lesson->mediafile, '://') !== false) {
598 $url = new moodle_url($lesson->mediafile);
599 } else {
600 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
601 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
603 $title = $lesson->mediafile;
605 $clicktoopen = html_writer::link($url, get_string('download'));
607 $mimetype = resourcelib_guess_url_mimetype($url);
609 $extension = resourcelib_get_extension($url->out(false));
611 $mediarenderer = $PAGE->get_renderer('core', 'media');
612 $embedoptions = array(
613 core_media::OPTION_TRUSTED => true,
614 core_media::OPTION_BLOCK => true
617 // find the correct type and print it out
618 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
619 $code = resourcelib_embed_image($url, $title);
621 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
622 // Media (audio/video) file.
623 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
625 } else {
626 // anything else - just try object tag enlarged as much as possible
627 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
630 return $code;
635 * Abstract class that page type's MUST inherit from.
637 * This is the abstract class that ALL add page type forms must extend.
638 * You will notice that all but two of the methods this class contains are final.
639 * Essentially the only thing that extending classes can do is extend custom_definition.
640 * OR if it has a special requirement on creation it can extend construction_override
642 * @abstract
643 * @copyright 2009 Sam Hemelryk
644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
646 abstract class lesson_add_page_form_base extends moodleform {
649 * This is the classic define that is used to identify this pagetype.
650 * Will be one of LESSON_*
651 * @var int
653 public $qtype;
656 * The simple string that describes the page type e.g. truefalse, multichoice
657 * @var string
659 public $qtypestring;
662 * An array of options used in the htmleditor
663 * @var array
665 protected $editoroptions = array();
668 * True if this is a standard page of false if it does something special.
669 * Questions are standard pages, branch tables are not
670 * @var bool
672 protected $standard = true;
675 * Each page type can and should override this to add any custom elements to
676 * the basic form that they want
678 public function custom_definition() {}
681 * Used to determine if this is a standard page or a special page
682 * @return bool
684 public final function is_standard() {
685 return (bool)$this->standard;
689 * Add the required basic elements to the form.
691 * This method adds the basic elements to the form including title and contents
692 * and then calls custom_definition();
694 public final function definition() {
695 $mform = $this->_form;
696 $editoroptions = $this->_customdata['editoroptions'];
698 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
700 $mform->addElement('hidden', 'id');
701 $mform->setType('id', PARAM_INT);
703 $mform->addElement('hidden', 'pageid');
704 $mform->setType('pageid', PARAM_INT);
706 if ($this->standard === true) {
707 $mform->addElement('hidden', 'qtype');
708 $mform->setType('qtype', PARAM_INT);
710 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
711 $mform->setType('title', PARAM_TEXT);
712 $mform->addRule('title', get_string('required'), 'required', null, 'client');
714 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
715 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
716 $mform->setType('contents_editor', PARAM_RAW);
717 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
720 $this->custom_definition();
722 if ($this->_customdata['edit'] === true) {
723 $mform->addElement('hidden', 'edit', 1);
724 $mform->setType('edit', PARAM_BOOL);
725 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
726 } else if ($this->qtype === 'questiontype') {
727 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
728 } else {
729 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
734 * Convenience function: Adds a jumpto select element
736 * @param string $name
737 * @param string|null $label
738 * @param int $selected The page to select by default
740 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
741 $title = get_string("jump", "lesson");
742 if ($label === null) {
743 $label = $title;
745 if (is_int($name)) {
746 $name = "jumpto[$name]";
748 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
749 $this->_form->setDefault($name, $selected);
750 $this->_form->addHelpButton($name, 'jumps', 'lesson');
754 * Convenience function: Adds a score input element
756 * @param string $name
757 * @param string|null $label
758 * @param mixed $value The default value
760 protected final function add_score($name, $label=null, $value=null) {
761 if ($label === null) {
762 $label = get_string("score", "lesson");
765 if (is_int($name)) {
766 $name = "score[$name]";
768 $this->_form->addElement('text', $name, $label, array('size'=>5));
769 $this->_form->setType($name, PARAM_INT);
770 if ($value !== null) {
771 $this->_form->setDefault($name, $value);
776 * Convenience function: Adds an answer editor
778 * @param int $count The count of the element to add
779 * @param string $label, null means default
780 * @param bool $required
781 * @return void
783 protected final function add_answer($count, $label = null, $required = false) {
784 if ($label === null) {
785 $label = get_string('answer', 'lesson');
787 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
788 $this->_form->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
789 if ($required) {
790 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
794 * Convenience function: Adds an response editor
796 * @param int $count The count of the element to add
797 * @param string $label, null means default
798 * @param bool $required
799 * @return void
801 protected final function add_response($count, $label = null, $required = false) {
802 if ($label === null) {
803 $label = get_string('response', 'lesson');
805 $this->_form->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
806 $this->_form->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
807 if ($required) {
808 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
813 * A function that gets called upon init of this object by the calling script.
815 * This can be used to process an immediate action if required. Currently it
816 * is only used in special cases by non-standard page types.
818 * @return bool
820 public function construction_override($pageid, lesson $lesson) {
821 return true;
828 * Class representation of a lesson
830 * This class is used the interact with, and manage a lesson once instantiated.
831 * If you need to fetch a lesson object you can do so by calling
833 * <code>
834 * lesson::load($lessonid);
835 * // or
836 * $lessonrecord = $DB->get_record('lesson', $lessonid);
837 * $lesson = new lesson($lessonrecord);
838 * </code>
840 * The class itself extends lesson_base as all classes within the lesson module should
842 * These properties are from the database
843 * @property int $id The id of this lesson
844 * @property int $course The ID of the course this lesson belongs to
845 * @property string $name The name of this lesson
846 * @property int $practice Flag to toggle this as a practice lesson
847 * @property int $modattempts Toggle to allow the user to go back and review answers
848 * @property int $usepassword Toggle the use of a password for entry
849 * @property string $password The password to require users to enter
850 * @property int $dependency ID of another lesson this lesson is dependent on
851 * @property string $conditions Conditions of the lesson dependency
852 * @property int $grade The maximum grade a user can achieve (%)
853 * @property int $custom Toggle custom scoring on or off
854 * @property int $ongoing Toggle display of an ongoing score
855 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
856 * @property int $maxanswers The max number of answers or branches
857 * @property int $maxattempts The maximum number of attempts a user can record
858 * @property int $review Toggle use or wrong answer review button
859 * @property int $nextpagedefault Override the default next page
860 * @property int $feedback Toggles display of default feedback
861 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
862 * @property int $maxpages Maximum number of pages this lesson can contain
863 * @property int $retake Flag to allow users to retake a lesson
864 * @property int $activitylink Relate this lesson to another lesson
865 * @property string $mediafile File to pop up to or webpage to display
866 * @property int $mediaheight Sets the height of the media file popup
867 * @property int $mediawidth Sets the width of the media file popup
868 * @property int $mediaclose Toggle display of a media close button
869 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
870 * @property int $width Width of slideshow
871 * @property int $height Height of slideshow
872 * @property string $bgcolor Background colour of slideshow
873 * @property int $displayleft Display a left menu
874 * @property int $displayleftif Sets the condition on which the left menu is displayed
875 * @property int $progressbar Flag to toggle display of a lesson progress bar
876 * @property int $highscores Flag to toggle collection of high scores
877 * @property int $maxhighscores Number of high scores to limit to
878 * @property int $available Timestamp of when this lesson becomes available
879 * @property int $deadline Timestamp of when this lesson is no longer available
880 * @property int $timemodified Timestamp when lesson was last modified
882 * These properties are calculated
883 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
884 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
886 * @copyright 2009 Sam Hemelryk
887 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
889 class lesson extends lesson_base {
892 * The id of the first page (where prevpageid = 0) gets set and retrieved by
893 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
894 * @var int
896 protected $firstpageid = null;
898 * The id of the last page (where nextpageid = 0) gets set and retrieved by
899 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
900 * @var int
902 protected $lastpageid = null;
904 * An array used to cache the pages associated with this lesson after the first
905 * time they have been loaded.
906 * A note to developers: If you are going to be working with MORE than one or
907 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
908 * in order to save excess database queries.
909 * @var array An array of lesson_page objects
911 protected $pages = array();
913 * Flag that gets set to true once all of the pages associated with the lesson
914 * have been loaded.
915 * @var bool
917 protected $loadedallpages = false;
920 * Simply generates a lesson object given an array/object of properties
921 * Overrides {@see lesson_base->create()}
922 * @static
923 * @param object|array $properties
924 * @return lesson
926 public static function create($properties) {
927 return new lesson($properties);
931 * Generates a lesson object from the database given its id
932 * @static
933 * @param int $lessonid
934 * @return lesson
936 public static function load($lessonid) {
937 global $DB;
939 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
940 print_error('invalidcoursemodule');
942 return new lesson($lesson);
946 * Deletes this lesson from the database
948 public function delete() {
949 global $CFG, $DB;
950 require_once($CFG->libdir.'/gradelib.php');
951 require_once($CFG->dirroot.'/calendar/lib.php');
953 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
954 $context = context_module::instance($cm->id);
956 $DB->delete_records("lesson", array("id"=>$this->properties->id));
957 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
958 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
959 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
960 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
961 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
962 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
963 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
964 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
965 foreach($events as $event) {
966 $event = calendar_event::load($event);
967 $event->delete();
971 // Delete files associated with this module.
972 $fs = get_file_storage();
973 $fs->delete_area_files($context->id);
975 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
976 return true;
980 * Fetches messages from the session that may have been set in previous page
981 * actions.
983 * <code>
984 * // Do not call this method directly instead use
985 * $lesson->messages;
986 * </code>
988 * @return array
990 protected function get_messages() {
991 global $SESSION;
993 $messages = array();
994 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
995 $messages = $SESSION->lesson_messages[$this->properties->id];
996 unset($SESSION->lesson_messages[$this->properties->id]);
999 return $messages;
1003 * Get all of the attempts for the current user.
1005 * @param int $retries
1006 * @param bool $correct Optional: only fetch correct attempts
1007 * @param int $pageid Optional: only fetch attempts at the given page
1008 * @param int $userid Optional: defaults to the current user if not set
1009 * @return array|false
1011 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1012 global $USER, $DB;
1013 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1014 if ($correct) {
1015 $params['correct'] = 1;
1017 if ($pageid !== null) {
1018 $params['pageid'] = $pageid;
1020 if ($userid === null) {
1021 $params['userid'] = $USER->id;
1023 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1027 * Returns the first page for the lesson or false if there isn't one.
1029 * This method should be called via the magic method __get();
1030 * <code>
1031 * $firstpage = $lesson->firstpage;
1032 * </code>
1034 * @return lesson_page|bool Returns the lesson_page specialised object or false
1036 protected function get_firstpage() {
1037 $pages = $this->load_all_pages();
1038 if (count($pages) > 0) {
1039 foreach ($pages as $page) {
1040 if ((int)$page->prevpageid === 0) {
1041 return $page;
1045 return false;
1049 * Returns the last page for the lesson or false if there isn't one.
1051 * This method should be called via the magic method __get();
1052 * <code>
1053 * $lastpage = $lesson->lastpage;
1054 * </code>
1056 * @return lesson_page|bool Returns the lesson_page specialised object or false
1058 protected function get_lastpage() {
1059 $pages = $this->load_all_pages();
1060 if (count($pages) > 0) {
1061 foreach ($pages as $page) {
1062 if ((int)$page->nextpageid === 0) {
1063 return $page;
1067 return false;
1071 * Returns the id of the first page of this lesson. (prevpageid = 0)
1072 * @return int
1074 protected function get_firstpageid() {
1075 global $DB;
1076 if ($this->firstpageid == null) {
1077 if (!$this->loadedallpages) {
1078 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1079 if (!$firstpageid) {
1080 print_error('cannotfindfirstpage', 'lesson');
1082 $this->firstpageid = $firstpageid;
1083 } else {
1084 $firstpage = $this->get_firstpage();
1085 $this->firstpageid = $firstpage->id;
1088 return $this->firstpageid;
1092 * Returns the id of the last page of this lesson. (nextpageid = 0)
1093 * @return int
1095 public function get_lastpageid() {
1096 global $DB;
1097 if ($this->lastpageid == null) {
1098 if (!$this->loadedallpages) {
1099 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1100 if (!$lastpageid) {
1101 print_error('cannotfindlastpage', 'lesson');
1103 $this->lastpageid = $lastpageid;
1104 } else {
1105 $lastpageid = $this->get_lastpage();
1106 $this->lastpageid = $lastpageid->id;
1110 return $this->lastpageid;
1114 * Gets the next page id to display after the one that is provided.
1115 * @param int $nextpageid
1116 * @return bool
1118 public function get_next_page($nextpageid) {
1119 global $USER, $DB;
1120 $allpages = $this->load_all_pages();
1121 if ($this->properties->nextpagedefault) {
1122 // in Flash Card mode...first get number of retakes
1123 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1124 shuffle($allpages);
1125 $found = false;
1126 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1127 foreach ($allpages as $nextpage) {
1128 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1129 $found = true;
1130 break;
1133 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1134 foreach ($allpages as $nextpage) {
1135 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1136 $found = true;
1137 break;
1141 if ($found) {
1142 if ($this->properties->maxpages) {
1143 // check number of pages viewed (in the lesson)
1144 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1145 return LESSON_EOL;
1148 return $nextpage->id;
1151 // In a normal lesson mode
1152 foreach ($allpages as $nextpage) {
1153 if ((int)$nextpage->id === (int)$nextpageid) {
1154 return $nextpage->id;
1157 return LESSON_EOL;
1161 * Sets a message against the session for this lesson that will displayed next
1162 * time the lesson processes messages
1164 * @param string $message
1165 * @param string $class
1166 * @param string $align
1167 * @return bool
1169 public function add_message($message, $class="notifyproblem", $align='center') {
1170 global $SESSION;
1172 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1173 $SESSION->lesson_messages = array();
1174 $SESSION->lesson_messages[$this->properties->id] = array();
1175 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1176 $SESSION->lesson_messages[$this->properties->id] = array();
1179 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1181 return true;
1185 * Check if the lesson is accessible at the present time
1186 * @return bool True if the lesson is accessible, false otherwise
1188 public function is_accessible() {
1189 $available = $this->properties->available;
1190 $deadline = $this->properties->deadline;
1191 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1195 * Starts the lesson time for the current user
1196 * @return bool Returns true
1198 public function start_timer() {
1199 global $USER, $DB;
1201 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1202 false, MUST_EXIST);
1204 // Trigger lesson started event.
1205 $event = \mod_lesson\event\lesson_started::create(array(
1206 'objectid' => $this->properties()->id,
1207 'context' => context_module::instance($cm->id),
1208 'courseid' => $this->properties()->course
1210 $event->trigger();
1212 $USER->startlesson[$this->properties->id] = true;
1213 $startlesson = new stdClass;
1214 $startlesson->lessonid = $this->properties->id;
1215 $startlesson->userid = $USER->id;
1216 $startlesson->starttime = time();
1217 $startlesson->lessontime = time();
1218 $DB->insert_record('lesson_timer', $startlesson);
1219 if ($this->properties->timed) {
1220 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties->maxtime), 'center');
1222 return true;
1226 * Updates the timer to the current time and returns the new timer object
1227 * @param bool $restart If set to true the timer is restarted
1228 * @param bool $continue If set to true AND $restart=true then the timer
1229 * will continue from a previous attempt
1230 * @return stdClass The new timer
1232 public function update_timer($restart=false, $continue=false) {
1233 global $USER, $DB;
1234 // clock code
1235 // get time information for this user
1236 if (!$timer = $DB->get_records('lesson_timer', array ("lessonid" => $this->properties->id, "userid" => $USER->id), 'starttime DESC', '*', 0, 1)) {
1237 print_error('cannotfindtimer', 'lesson');
1238 } else {
1239 $timer = current($timer); // this will get the latest start time record
1242 if ($restart) {
1243 if ($continue) {
1244 // continue a previous test, need to update the clock (think this option is disabled atm)
1245 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1246 } else {
1247 // starting over, so reset the clock
1248 $timer->starttime = time();
1252 $timer->lessontime = time();
1253 $DB->update_record('lesson_timer', $timer);
1254 return $timer;
1258 * Updates the timer to the current time then stops it by unsetting the user var
1259 * @return bool Returns true
1261 public function stop_timer() {
1262 global $USER, $DB;
1263 unset($USER->startlesson[$this->properties->id]);
1265 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1266 false, MUST_EXIST);
1268 // Trigger lesson ended event.
1269 $event = \mod_lesson\event\lesson_ended::create(array(
1270 'objectid' => $this->properties()->id,
1271 'context' => context_module::instance($cm->id),
1272 'courseid' => $this->properties()->course
1274 $event->trigger();
1276 return $this->update_timer(false, false);
1280 * Checks to see if the lesson has pages
1282 public function has_pages() {
1283 global $DB;
1284 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1285 return ($pagecount>0);
1289 * Returns the link for the related activity
1290 * @return array|false
1292 public function link_for_activitylink() {
1293 global $DB;
1294 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1295 if ($module) {
1296 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1297 if ($modname) {
1298 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1299 if ($instancename) {
1300 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1301 get_string('activitylinkname', 'lesson', $instancename),
1302 array('class'=>'centerpadded lessonbutton standardbutton'));
1306 return '';
1310 * Loads the requested page.
1312 * This function will return the requested page id as either a specialised
1313 * lesson_page object OR as a generic lesson_page.
1314 * If the page has been loaded previously it will be returned from the pages
1315 * array, otherwise it will be loaded from the database first
1317 * @param int $pageid
1318 * @return lesson_page A lesson_page object or an object that extends it
1320 public function load_page($pageid) {
1321 if (!array_key_exists($pageid, $this->pages)) {
1322 $manager = lesson_page_type_manager::get($this);
1323 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1325 return $this->pages[$pageid];
1329 * Loads ALL of the pages for this lesson
1331 * @return array An array containing all pages from this lesson
1333 public function load_all_pages() {
1334 if (!$this->loadedallpages) {
1335 $manager = lesson_page_type_manager::get($this);
1336 $this->pages = $manager->load_all_pages($this);
1337 $this->loadedallpages = true;
1339 return $this->pages;
1343 * Determines if a jumpto value is correct or not.
1345 * returns true if jumpto page is (logically) after the pageid page or
1346 * if the jumpto value is a special value. Returns false in all other cases.
1348 * @param int $pageid Id of the page from which you are jumping from.
1349 * @param int $jumpto The jumpto number.
1350 * @return boolean True or false after a series of tests.
1352 public function jumpto_is_correct($pageid, $jumpto) {
1353 global $DB;
1355 // first test the special values
1356 if (!$jumpto) {
1357 // same page
1358 return false;
1359 } elseif ($jumpto == LESSON_NEXTPAGE) {
1360 return true;
1361 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1362 return true;
1363 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1364 return true;
1365 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1366 return true;
1367 } elseif ($jumpto == LESSON_EOL) {
1368 return true;
1371 $pages = $this->load_all_pages();
1372 $apageid = $pages[$pageid]->nextpageid;
1373 while ($apageid != 0) {
1374 if ($jumpto == $apageid) {
1375 return true;
1377 $apageid = $pages[$apageid]->nextpageid;
1379 return false;
1383 * Returns the time a user has remaining on this lesson
1384 * @param int $starttime Starttime timestamp
1385 * @return string
1387 public function time_remaining($starttime) {
1388 $timeleft = $starttime + $this->maxtime * 60 - time();
1389 $hours = floor($timeleft/3600);
1390 $timeleft = $timeleft - ($hours * 3600);
1391 $minutes = floor($timeleft/60);
1392 $secs = $timeleft - ($minutes * 60);
1394 if ($minutes < 10) {
1395 $minutes = "0$minutes";
1397 if ($secs < 10) {
1398 $secs = "0$secs";
1400 $output = array();
1401 $output[] = $hours;
1402 $output[] = $minutes;
1403 $output[] = $secs;
1404 $output = implode(':', $output);
1405 return $output;
1409 * Interprets LESSON_CLUSTERJUMP jumpto value.
1411 * This will select a page randomly
1412 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1413 * and the page selected will be a page that has not been viewed already
1414 * and if any pages are within a branch table or end of branch then only 1 page within
1415 * the branch table or end of branch will be randomly selected (sub clustering).
1417 * @param int $pageid Id of the current page from which we are jumping from.
1418 * @param int $userid Id of the user.
1419 * @return int The id of the next page.
1421 public function cluster_jump($pageid, $userid=null) {
1422 global $DB, $USER;
1424 if ($userid===null) {
1425 $userid = $USER->id;
1427 // get the number of retakes
1428 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1429 $retakes = 0;
1431 // get all the lesson_attempts aka what the user has seen
1432 $seenpages = array();
1433 if ($attempts = $this->get_attempts($retakes)) {
1434 foreach ($attempts as $attempt) {
1435 $seenpages[$attempt->pageid] = $attempt->pageid;
1440 // get the lesson pages
1441 $lessonpages = $this->load_all_pages();
1442 // find the start of the cluster
1443 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1444 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1445 break;
1447 $pageid = $lessonpages[$pageid]->prevpageid;
1450 $clusterpages = array();
1451 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1452 $unseen = array();
1453 foreach ($clusterpages as $key=>$cluster) {
1454 if ($cluster->type !== lesson_page::TYPE_QUESTION) {
1455 unset($clusterpages[$key]);
1456 } elseif ($cluster->is_unseen($seenpages)) {
1457 $unseen[] = $cluster;
1461 if (count($unseen) > 0) {
1462 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1463 $nextpage = $unseen[rand(0, count($unseen)-1)];
1464 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1465 // if branch table, then pick a random page inside of it
1466 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1467 return $branchpages[rand(0, count($branchpages)-1)]->id;
1468 } else { // otherwise, return the page's id
1469 return $nextpage->id;
1471 } else {
1472 // seen all there is to see, leave the cluster
1473 if (end($clusterpages)->nextpageid == 0) {
1474 return LESSON_EOL;
1475 } else {
1476 $clusterendid = $pageid;
1477 while ($clusterendid != 0) { // this condition should not be satisfied... should be a cluster page
1478 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_CLUSTER) {
1479 break;
1481 $clusterendid = $lessonpages[$clusterendid]->prevpageid;
1483 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1484 if ($exitjump == LESSON_NEXTPAGE) {
1485 $exitjump = $lessonpages[$pageid]->nextpageid;
1487 if ($exitjump == 0) {
1488 return LESSON_EOL;
1489 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1490 return $exitjump;
1491 } else {
1492 if (!array_key_exists($exitjump, $lessonpages)) {
1493 $found = false;
1494 foreach ($lessonpages as $page) {
1495 if ($page->id === $clusterendid) {
1496 $found = true;
1497 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1498 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1499 break;
1503 if (!array_key_exists($exitjump, $lessonpages)) {
1504 return LESSON_EOL;
1506 return $exitjump;
1513 * Finds all pages that appear to be a subtype of the provided pageid until
1514 * an end point specified within $ends is encountered or no more pages exist
1516 * @param int $pageid
1517 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1518 * the subtype
1519 * @return array An array of specialised lesson_page objects
1521 public function get_sub_pages_of($pageid, array $ends) {
1522 $lessonpages = $this->load_all_pages();
1523 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1524 $pages = array();
1526 while (true) {
1527 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1528 break;
1530 $pages[] = $lessonpages[$pageid];
1531 $pageid = $lessonpages[$pageid]->nextpageid;
1534 return $pages;
1538 * Checks to see if the specified page[id] is a subpage of a type specified in
1539 * the $types array, until either there are no more pages of we find a type
1540 * corresponding to that of a type specified in $ends
1542 * @param int $pageid The id of the page to check
1543 * @param array $types An array of types that would signify this page was a subpage
1544 * @param array $ends An array of types that mean this is not a subpage
1545 * @return bool
1547 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1548 $pages = $this->load_all_pages();
1549 $pageid = $pages[$pageid]->prevpageid; // move up one
1551 array_unshift($ends, 0);
1552 // go up the pages till branch table
1553 while (true) {
1554 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1555 return false;
1556 } else if (in_array($pages[$pageid]->qtype, $types)) {
1557 return true;
1559 $pageid = $pages[$pageid]->prevpageid;
1566 * Abstract class to provide a core functions to the all lesson classes
1568 * This class should be abstracted by ALL classes with the lesson module to ensure
1569 * that all classes within this module can be interacted with in the same way.
1571 * This class provides the user with a basic properties array that can be fetched
1572 * or set via magic methods, or alternatively by defining methods get_blah() or
1573 * set_blah() within the extending object.
1575 * @copyright 2009 Sam Hemelryk
1576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1578 abstract class lesson_base {
1581 * An object containing properties
1582 * @var stdClass
1584 protected $properties;
1587 * The constructor
1588 * @param stdClass $properties
1590 public function __construct($properties) {
1591 $this->properties = (object)$properties;
1595 * Magic property method
1597 * Attempts to call a set_$key method if one exists otherwise falls back
1598 * to simply set the property
1600 * @param string $key
1601 * @param mixed $value
1603 public function __set($key, $value) {
1604 if (method_exists($this, 'set_'.$key)) {
1605 $this->{'set_'.$key}($value);
1607 $this->properties->{$key} = $value;
1611 * Magic get method
1613 * Attempts to call a get_$key method to return the property and ralls over
1614 * to return the raw property
1616 * @param str $key
1617 * @return mixed
1619 public function __get($key) {
1620 if (method_exists($this, 'get_'.$key)) {
1621 return $this->{'get_'.$key}();
1623 return $this->properties->{$key};
1627 * Stupid PHP needs an isset magic method if you use the get magic method and
1628 * still want empty calls to work.... blah ~!
1630 * @param string $key
1631 * @return bool
1633 public function __isset($key) {
1634 if (method_exists($this, 'get_'.$key)) {
1635 $val = $this->{'get_'.$key}();
1636 return !empty($val);
1638 return !empty($this->properties->{$key});
1641 //NOTE: E_STRICT does not allow to change function signature!
1644 * If implemented should create a new instance, save it in the DB and return it
1646 //public static function create() {}
1648 * If implemented should load an instance from the DB and return it
1650 //public static function load() {}
1652 * Fetches all of the properties of the object
1653 * @return stdClass
1655 public function properties() {
1656 return $this->properties;
1662 * Abstract class representation of a page associated with a lesson.
1664 * This class should MUST be extended by all specialised page types defined in
1665 * mod/lesson/pagetypes/.
1666 * There are a handful of abstract methods that need to be defined as well as
1667 * severl methods that can optionally be defined in order to make the page type
1668 * operate in the desired way
1670 * Database properties
1671 * @property int $id The id of this lesson page
1672 * @property int $lessonid The id of the lesson this page belongs to
1673 * @property int $prevpageid The id of the page before this one
1674 * @property int $nextpageid The id of the next page in the page sequence
1675 * @property int $qtype Identifies the page type of this page
1676 * @property int $qoption Used to record page type specific options
1677 * @property int $layout Used to record page specific layout selections
1678 * @property int $display Used to record page specific display selections
1679 * @property int $timecreated Timestamp for when the page was created
1680 * @property int $timemodified Timestamp for when the page was last modified
1681 * @property string $title The title of this page
1682 * @property string $contents The rich content shown to describe the page
1683 * @property int $contentsformat The format of the contents field
1685 * Calculated properties
1686 * @property-read array $answers An array of answers for this page
1687 * @property-read bool $displayinmenublock Toggles display in the left menu block
1688 * @property-read array $jumps An array containing all the jumps this page uses
1689 * @property-read lesson $lesson The lesson this page belongs to
1690 * @property-read int $type The type of the page [question | structure]
1691 * @property-read typeid The unique identifier for the page type
1692 * @property-read typestring The string that describes this page type
1694 * @abstract
1695 * @copyright 2009 Sam Hemelryk
1696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1698 abstract class lesson_page extends lesson_base {
1701 * A reference to the lesson this page belongs to
1702 * @var lesson
1704 protected $lesson = null;
1706 * Contains the answers to this lesson_page once loaded
1707 * @var null|array
1709 protected $answers = null;
1711 * This sets the type of the page, can be one of the constants defined below
1712 * @var int
1714 protected $type = 0;
1717 * Constants used to identify the type of the page
1719 const TYPE_QUESTION = 0;
1720 const TYPE_STRUCTURE = 1;
1723 * This method should return the integer used to identify the page type within
1724 * the database and throughout code. This maps back to the defines used in 1.x
1725 * @abstract
1726 * @return int
1728 abstract protected function get_typeid();
1730 * This method should return the string that describes the pagetype
1731 * @abstract
1732 * @return string
1734 abstract protected function get_typestring();
1737 * This method gets called to display the page to the user taking the lesson
1738 * @abstract
1739 * @param object $renderer
1740 * @param object $attempt
1741 * @return string
1743 abstract public function display($renderer, $attempt);
1746 * Creates a new lesson_page within the database and returns the correct pagetype
1747 * object to use to interact with the new lesson
1749 * @final
1750 * @static
1751 * @param object $properties
1752 * @param lesson $lesson
1753 * @return lesson_page Specialised object that extends lesson_page
1755 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
1756 global $DB;
1757 $newpage = new stdClass;
1758 $newpage->title = $properties->title;
1759 $newpage->contents = $properties->contents_editor['text'];
1760 $newpage->contentsformat = $properties->contents_editor['format'];
1761 $newpage->lessonid = $lesson->id;
1762 $newpage->timecreated = time();
1763 $newpage->qtype = $properties->qtype;
1764 $newpage->qoption = (isset($properties->qoption))?1:0;
1765 $newpage->layout = (isset($properties->layout))?1:0;
1766 $newpage->display = (isset($properties->display))?1:0;
1767 $newpage->prevpageid = 0; // this is a first page
1768 $newpage->nextpageid = 0; // this is the only page
1770 if ($properties->pageid) {
1771 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
1772 if (!$prevpage) {
1773 print_error('cannotfindpages', 'lesson');
1775 $newpage->prevpageid = $prevpage->id;
1776 $newpage->nextpageid = $prevpage->nextpageid;
1777 } else {
1778 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
1779 if ($nextpage) {
1780 // This is the first page, there are existing pages put this at the start
1781 $newpage->nextpageid = $nextpage->id;
1785 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
1787 $editor = new stdClass;
1788 $editor->id = $newpage->id;
1789 $editor->contents_editor = $properties->contents_editor;
1790 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
1791 $DB->update_record("lesson_pages", $editor);
1793 if ($newpage->prevpageid > 0) {
1794 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
1796 if ($newpage->nextpageid > 0) {
1797 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
1800 $page = lesson_page::load($newpage, $lesson);
1801 $page->create_answers($properties);
1803 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
1805 return $page;
1809 * This method loads a page object from the database and returns it as a
1810 * specialised object that extends lesson_page
1812 * @final
1813 * @static
1814 * @param int $id
1815 * @param lesson $lesson
1816 * @return lesson_page Specialised lesson_page object
1818 final public static function load($id, lesson $lesson) {
1819 global $DB;
1821 if (is_object($id) && !empty($id->qtype)) {
1822 $page = $id;
1823 } else {
1824 $page = $DB->get_record("lesson_pages", array("id" => $id));
1825 if (!$page) {
1826 print_error('cannotfindpages', 'lesson');
1829 $manager = lesson_page_type_manager::get($lesson);
1831 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
1832 if (!class_exists($class)) {
1833 $class = 'lesson_page';
1836 return new $class($page, $lesson);
1840 * Deletes a lesson_page from the database as well as any associated records.
1841 * @final
1842 * @return bool
1844 final public function delete() {
1845 global $DB;
1846 // first delete all the associated records...
1847 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
1848 // ...now delete the answers...
1849 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
1850 // ..and the page itself
1851 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
1853 // Delete files associated with this page.
1854 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
1855 $context = context_module::instance($cm->id);
1856 $fs = get_file_storage();
1857 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
1859 // repair the hole in the linkage
1860 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
1861 //This is the only page, no repair needed
1862 } elseif (!$this->properties->prevpageid) {
1863 // this is the first page...
1864 $page = $this->lesson->load_page($this->properties->nextpageid);
1865 $page->move(null, 0);
1866 } elseif (!$this->properties->nextpageid) {
1867 // this is the last page...
1868 $page = $this->lesson->load_page($this->properties->prevpageid);
1869 $page->move(0);
1870 } else {
1871 // page is in the middle...
1872 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
1873 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
1875 $prevpage->move($nextpage->id);
1876 $nextpage->move(null, $prevpage->id);
1878 return true;
1882 * Moves a page by updating its nextpageid and prevpageid values within
1883 * the database
1885 * @final
1886 * @param int $nextpageid
1887 * @param int $prevpageid
1889 final public function move($nextpageid=null, $prevpageid=null) {
1890 global $DB;
1891 if ($nextpageid === null) {
1892 $nextpageid = $this->properties->nextpageid;
1894 if ($prevpageid === null) {
1895 $prevpageid = $this->properties->prevpageid;
1897 $obj = new stdClass;
1898 $obj->id = $this->properties->id;
1899 $obj->prevpageid = $prevpageid;
1900 $obj->nextpageid = $nextpageid;
1901 $DB->update_record('lesson_pages', $obj);
1905 * Returns the answers that are associated with this page in the database
1907 * @final
1908 * @return array
1910 final public function get_answers() {
1911 global $DB;
1912 if ($this->answers === null) {
1913 $this->answers = array();
1914 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
1915 if (!$answers) {
1916 // It is possible that a lesson upgraded from Moodle 1.9 still
1917 // contains questions without any answers [MDL-25632].
1918 // debugging(get_string('cannotfindanswer', 'lesson'));
1919 return array();
1921 foreach ($answers as $answer) {
1922 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
1925 return $this->answers;
1929 * Returns the lesson this page is associated with
1930 * @final
1931 * @return lesson
1933 final protected function get_lesson() {
1934 return $this->lesson;
1938 * Returns the type of page this is. Not to be confused with page type
1939 * @final
1940 * @return int
1942 final protected function get_type() {
1943 return $this->type;
1947 * Records an attempt at this page
1949 * @final
1950 * @global moodle_database $DB
1951 * @param stdClass $context
1952 * @return stdClass Returns the result of the attempt
1954 final public function record_attempt($context) {
1955 global $DB, $USER, $OUTPUT;
1958 * This should be overridden by each page type to actually check the response
1959 * against what ever custom criteria they have defined
1961 $result = $this->check_answer();
1963 $result->attemptsremaining = 0;
1964 $result->maxattemptsreached = false;
1966 if ($result->noanswer) {
1967 $result->newpageid = $this->properties->id; // display same page again
1968 $result->feedback = get_string('noanswer', 'lesson');
1969 } else {
1970 if (!has_capability('mod/lesson:manage', $context)) {
1971 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
1972 // record student's attempt
1973 $attempt = new stdClass;
1974 $attempt->lessonid = $this->lesson->id;
1975 $attempt->pageid = $this->properties->id;
1976 $attempt->userid = $USER->id;
1977 $attempt->answerid = $result->answerid;
1978 $attempt->retry = $nretakes;
1979 $attempt->correct = $result->correctanswer;
1980 if($result->userresponse !== null) {
1981 $attempt->useranswer = $result->userresponse;
1984 $attempt->timeseen = time();
1985 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
1986 if (isset($USER->modattempts[$this->lesson->id])) {
1987 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
1990 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
1991 $DB->insert_record("lesson_attempts", $attempt);
1993 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
1994 // displaying of message(s) is at the end of page for more ergonomic display
1995 if (!$result->correctanswer && ($result->newpageid == 0)) {
1996 // wrong answer and student is stuck on this page - check how many attempts
1997 // the student has had at this page/question
1998 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry" => $attempt->retry));
1999 // retreive the number of attempts left counter for displaying at bottom of feedback page
2000 if ($nattempts >= $this->lesson->maxattempts) {
2001 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2002 $result->maxattemptsreached = true;
2004 $result->newpageid = LESSON_NEXTPAGE;
2005 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2006 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
2010 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
2011 if ($result->newpageid == 0) {
2012 $result->newpageid = $this->properties->id;
2013 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
2014 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2017 // Determine default feedback if necessary
2018 if (empty($result->response)) {
2019 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2020 // These conditions have been met:
2021 // 1. The lesson manager has not supplied feedback to the student
2022 // 2. Not displaying default feedback
2023 // 3. The user did provide an answer
2024 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2026 $result->nodefaultresponse = true; // This will cause a redirect below
2027 } else if ($result->isessayquestion) {
2028 $result->response = get_string('defaultessayresponse', 'lesson');
2029 } else if ($result->correctanswer) {
2030 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2031 } else {
2032 $result->response = get_string('thatsthewronganswer', 'lesson');
2036 if ($result->response) {
2037 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2038 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2039 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2040 if ($qattempts == 1) {
2041 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2042 } else {
2043 $result->feedback = $OUTPUT->BOX(get_string("secondpluswrong", "lesson"), 'feedback');
2045 } else {
2046 $class = 'response';
2047 if ($result->correctanswer) {
2048 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2049 } else if (!$result->isessayquestion) {
2050 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2052 $options = new stdClass;
2053 $options->noclean = true;
2054 $options->para = true;
2055 $options->overflowdiv = true;
2056 $result->feedback = $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 'generalbox boxaligncenter');
2057 $result->feedback .= '<div class="correctanswer generalbox"><em>'.get_string("youranswer", "lesson").'</em> : '.$result->studentanswer; // already in clean html
2058 $result->feedback .= $OUTPUT->box($result->response, $class); // already conerted to HTML
2059 $result->feedback .= '</div>';
2064 return $result;
2068 * Returns the string for a jump name
2070 * @final
2071 * @param int $jumpto Jump code or page ID
2072 * @return string
2074 final protected function get_jump_name($jumpto) {
2075 global $DB;
2076 static $jumpnames = array();
2078 if (!array_key_exists($jumpto, $jumpnames)) {
2079 if ($jumpto == LESSON_THISPAGE) {
2080 $jumptitle = get_string('thispage', 'lesson');
2081 } elseif ($jumpto == LESSON_NEXTPAGE) {
2082 $jumptitle = get_string('nextpage', 'lesson');
2083 } elseif ($jumpto == LESSON_EOL) {
2084 $jumptitle = get_string('endoflesson', 'lesson');
2085 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2086 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2087 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2088 $jumptitle = get_string('previouspage', 'lesson');
2089 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2090 $jumptitle = get_string('randompageinbranch', 'lesson');
2091 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2092 $jumptitle = get_string('randombranch', 'lesson');
2093 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2094 $jumptitle = get_string('clusterjump', 'lesson');
2095 } else {
2096 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2097 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2100 $jumpnames[$jumpto] = format_string($jumptitle,true);
2103 return $jumpnames[$jumpto];
2107 * Constructor method
2108 * @param object $properties
2109 * @param lesson $lesson
2111 public function __construct($properties, lesson $lesson) {
2112 parent::__construct($properties);
2113 $this->lesson = $lesson;
2117 * Returns the score for the attempt
2118 * This may be overridden by page types that require manual grading
2119 * @param array $answers
2120 * @param object $attempt
2121 * @return int
2123 public function earned_score($answers, $attempt) {
2124 return $answers[$attempt->answerid]->score;
2128 * This is a callback method that can be override and gets called when ever a page
2129 * is viewed
2131 * @param bool $canmanage True if the user has the manage cap
2132 * @return mixed
2134 public function callback_on_view($canmanage) {
2135 return true;
2139 * Updates a lesson page and its answers within the database
2141 * @param object $properties
2142 * @return bool
2144 public function update($properties, $context = null, $maxbytes = null) {
2145 global $DB, $PAGE;
2146 $answers = $this->get_answers();
2147 $properties->id = $this->properties->id;
2148 $properties->lessonid = $this->lesson->id;
2149 if (empty($properties->qoption)) {
2150 $properties->qoption = '0';
2152 if (empty($context)) {
2153 $context = $PAGE->context;
2155 if ($maxbytes === null) {
2156 $maxbytes = get_user_max_upload_file_size($context);
2158 $properties->timemodified = time();
2159 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2160 $DB->update_record("lesson_pages", $properties);
2162 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2163 if (!array_key_exists($i, $this->answers)) {
2164 $this->answers[$i] = new stdClass;
2165 $this->answers[$i]->lessonid = $this->lesson->id;
2166 $this->answers[$i]->pageid = $this->id;
2167 $this->answers[$i]->timecreated = $this->timecreated;
2170 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2171 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2172 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2174 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2175 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2176 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
2179 // we don't need to check for isset here because properties called it's own isset method.
2180 if ($this->answers[$i]->answer != '') {
2181 if (isset($properties->jumpto[$i])) {
2182 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2184 if ($this->lesson->custom && isset($properties->score[$i])) {
2185 $this->answers[$i]->score = $properties->score[$i];
2187 if (!isset($this->answers[$i]->id)) {
2188 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2189 } else {
2190 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2193 } else if (isset($this->answers[$i]->id)) {
2194 $DB->delete_records('lesson_answers', array('id'=>$this->answers[$i]->id));
2195 unset($this->answers[$i]);
2198 return true;
2202 * Can be set to true if the page requires a static link to create a new instance
2203 * instead of simply being included in the dropdown
2204 * @param int $previd
2205 * @return bool
2207 public function add_page_link($previd) {
2208 return false;
2212 * Returns true if a page has been viewed before
2214 * @param array|int $param Either an array of pages that have been seen or the
2215 * number of retakes a user has had
2216 * @return bool
2218 public function is_unseen($param) {
2219 global $USER, $DB;
2220 if (is_array($param)) {
2221 $seenpages = $param;
2222 return (!array_key_exists($this->properties->id, $seenpages));
2223 } else {
2224 $nretakes = $param;
2225 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2226 return true;
2229 return false;
2233 * Checks to see if a page has been answered previously
2234 * @param int $nretakes
2235 * @return bool
2237 public function is_unanswered($nretakes) {
2238 global $DB, $USER;
2239 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2240 return true;
2242 return false;
2246 * Creates answers within the database for this lesson_page. Usually only ever
2247 * called when creating a new page instance
2248 * @param object $properties
2249 * @return array
2251 public function create_answers($properties) {
2252 global $DB;
2253 // now add the answers
2254 $newanswer = new stdClass;
2255 $newanswer->lessonid = $this->lesson->id;
2256 $newanswer->pageid = $this->properties->id;
2257 $newanswer->timecreated = $this->properties->timecreated;
2259 $answers = array();
2261 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2262 $answer = clone($newanswer);
2264 if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
2265 $answer->answer = $properties->answer_editor[$i]['text'];
2266 $answer->answerformat = $properties->answer_editor[$i]['format'];
2268 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2269 $answer->response = $properties->response_editor[$i]['text'];
2270 $answer->responseformat = $properties->response_editor[$i]['format'];
2273 if (isset($answer->answer) && $answer->answer != '') {
2274 if (isset($properties->jumpto[$i])) {
2275 $answer->jumpto = $properties->jumpto[$i];
2277 if ($this->lesson->custom && isset($properties->score[$i])) {
2278 $answer->score = $properties->score[$i];
2280 $answer->id = $DB->insert_record("lesson_answers", $answer);
2281 $answers[$answer->id] = new lesson_page_answer($answer);
2282 } else {
2283 break;
2287 $this->answers = $answers;
2288 return $answers;
2292 * This method MUST be overridden by all question page types, or page types that
2293 * wish to score a page.
2295 * The structure of result should always be the same so it is a good idea when
2296 * overriding this method on a page type to call
2297 * <code>
2298 * $result = parent::check_answer();
2299 * </code>
2300 * before modifying it as required.
2302 * @return stdClass
2304 public function check_answer() {
2305 $result = new stdClass;
2306 $result->answerid = 0;
2307 $result->noanswer = false;
2308 $result->correctanswer = false;
2309 $result->isessayquestion = false; // use this to turn off review button on essay questions
2310 $result->response = '';
2311 $result->newpageid = 0; // stay on the page
2312 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2313 $result->userresponse = null;
2314 $result->feedback = '';
2315 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2316 return $result;
2320 * True if the page uses a custom option
2322 * Should be override and set to true if the page uses a custom option.
2324 * @return bool
2326 public function has_option() {
2327 return false;
2331 * Returns the maximum number of answers for this page given the maximum number
2332 * of answers permitted by the lesson.
2334 * @param int $default
2335 * @return int
2337 public function max_answers($default) {
2338 return $default;
2342 * Returns the properties of this lesson page as an object
2343 * @return stdClass;
2345 public function properties() {
2346 $properties = clone($this->properties);
2347 if ($this->answers === null) {
2348 $this->get_answers();
2350 if (count($this->answers)>0) {
2351 $count = 0;
2352 $qtype = $properties->qtype;
2353 foreach ($this->answers as $answer) {
2354 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
2355 if ($qtype != LESSON_PAGE_MATCHING) {
2356 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
2357 } else {
2358 $properties->{'response_editor['.$count.']'} = $answer->response;
2360 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2361 $properties->{'score['.$count.']'} = $answer->score;
2362 $count++;
2365 return $properties;
2369 * Returns an array of options to display when choosing the jumpto for a page/answer
2370 * @static
2371 * @param int $pageid
2372 * @param lesson $lesson
2373 * @return array
2375 public static function get_jumptooptions($pageid, lesson $lesson) {
2376 global $DB;
2377 $jump = array();
2378 $jump[0] = get_string("thispage", "lesson");
2379 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2380 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2381 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2383 if ($pageid == 0) {
2384 return $jump;
2387 $pages = $lesson->load_all_pages();
2388 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))) {
2389 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
2390 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
2392 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
2393 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
2395 if (!optional_param('firstpage', 0, PARAM_INT)) {
2396 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
2397 while (true) {
2398 if ($apageid) {
2399 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2400 $jump[$apageid] = strip_tags(format_string($title,true));
2401 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2402 } else {
2403 // last page reached
2404 break;
2408 return $jump;
2411 * Returns the contents field for the page properly formatted and with plugin
2412 * file url's converted
2413 * @return string
2415 public function get_contents() {
2416 global $PAGE;
2417 if (!empty($this->properties->contents)) {
2418 if (!isset($this->properties->contentsformat)) {
2419 $this->properties->contentsformat = FORMAT_HTML;
2421 $context = context_module::instance($PAGE->cm->id);
2422 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
2423 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
2424 return format_text($contents, $this->properties->contentsformat,
2425 array('context' => $context, 'noclean' => true,
2426 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
2427 } else {
2428 return '';
2433 * Set to true if this page should display in the menu block
2434 * @return bool
2436 protected function get_displayinmenublock() {
2437 return false;
2441 * Get the string that describes the options of this page type
2442 * @return string
2444 public function option_description_string() {
2445 return '';
2449 * Updates a table with the answers for this page
2450 * @param html_table $table
2451 * @return html_table
2453 public function display_answers(html_table $table) {
2454 $answers = $this->get_answers();
2455 $i = 1;
2456 foreach ($answers as $answer) {
2457 $cells = array();
2458 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2459 $cells[] = $this->get_jump_name($answer->jumpto);
2460 $table->data[] = new html_table_row($cells);
2461 if ($i === 1){
2462 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
2464 $i++;
2466 return $table;
2470 * Determines if this page should be grayed out on the management/report screens
2471 * @return int 0 or 1
2473 protected function get_grayout() {
2474 return 0;
2478 * Adds stats for this page to the &pagestats object. This should be defined
2479 * for all page types that grade
2480 * @param array $pagestats
2481 * @param int $tries
2482 * @return bool
2484 public function stats(array &$pagestats, $tries) {
2485 return true;
2489 * Formats the answers of this page for a report
2491 * @param object $answerpage
2492 * @param object $answerdata
2493 * @param object $useranswer
2494 * @param array $pagestats
2495 * @param int $i Count of first level answers
2496 * @param int $n Count of second level answers
2497 * @return object The answer page for this
2499 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2500 $answers = $this->get_answers();
2501 $formattextdefoptions = new stdClass;
2502 $formattextdefoptions->para = false; //I'll use it widely in this page
2503 foreach ($answers as $answer) {
2504 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
2505 $answerdata->answers[] = array($data, "");
2506 $answerpage->answerdata = $answerdata;
2508 return $answerpage;
2512 * Gets an array of the jumps used by the answers of this page
2514 * @return array
2516 public function get_jumps() {
2517 global $DB;
2518 $jumps = array();
2519 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
2520 if ($answers = $this->get_answers()) {
2521 foreach ($answers as $answer) {
2522 $jumps[] = $this->get_jump_name($answer->jumpto);
2524 } else {
2525 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
2527 return $jumps;
2530 * Informs whether this page type require manual grading or not
2531 * @return bool
2533 public function requires_manual_grading() {
2534 return false;
2538 * A callback method that allows a page to override the next page a user will
2539 * see during when this page is being completed.
2540 * @return false|int
2542 public function override_next_page() {
2543 return false;
2547 * This method is used to determine if this page is a valid page
2549 * @param array $validpages
2550 * @param array $pageviews
2551 * @return int The next page id to check
2553 public function valid_page_and_view(&$validpages, &$pageviews) {
2554 $validpages[$this->properties->id] = 1;
2555 return $this->properties->nextpageid;
2562 * Class used to represent an answer to a page
2564 * @property int $id The ID of this answer in the database
2565 * @property int $lessonid The ID of the lesson this answer belongs to
2566 * @property int $pageid The ID of the page this answer belongs to
2567 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2568 * @property int $grade The grade this answer is worth
2569 * @property int $score The score this answer will give
2570 * @property int $flags Used to store options for the answer
2571 * @property int $timecreated A timestamp of when the answer was created
2572 * @property int $timemodified A timestamp of when the answer was modified
2573 * @property string $answer The answer itself
2574 * @property string $response The response the user sees if selecting this answer
2576 * @copyright 2009 Sam Hemelryk
2577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2579 class lesson_page_answer extends lesson_base {
2582 * Loads an page answer from the DB
2584 * @param int $id
2585 * @return lesson_page_answer
2587 public static function load($id) {
2588 global $DB;
2589 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2590 return new lesson_page_answer($answer);
2594 * Given an object of properties and a page created answer(s) and saves them
2595 * in the database.
2597 * @param stdClass $properties
2598 * @param lesson_page $page
2599 * @return array
2601 public static function create($properties, lesson_page $page) {
2602 return $page->create_answers($properties);
2608 * A management class for page types
2610 * This class is responsible for managing the different pages. A manager object can
2611 * be retrieved by calling the following line of code:
2612 * <code>
2613 * $manager = lesson_page_type_manager::get($lesson);
2614 * </code>
2615 * The first time the page type manager is retrieved the it includes all of the
2616 * different page types located in mod/lesson/pagetypes.
2618 * @copyright 2009 Sam Hemelryk
2619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2621 class lesson_page_type_manager {
2624 * An array of different page type classes
2625 * @var array
2627 protected $types = array();
2630 * Retrieves the lesson page type manager object
2632 * If the object hasn't yet been created it is created here.
2634 * @staticvar lesson_page_type_manager $pagetypemanager
2635 * @param lesson $lesson
2636 * @return lesson_page_type_manager
2638 public static function get(lesson $lesson) {
2639 static $pagetypemanager;
2640 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
2641 $pagetypemanager = new lesson_page_type_manager();
2642 $pagetypemanager->load_lesson_types($lesson);
2644 return $pagetypemanager;
2648 * Finds and loads all lesson page types in mod/lesson/pagetypes
2650 * @param lesson $lesson
2652 public function load_lesson_types(lesson $lesson) {
2653 global $CFG;
2654 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
2655 $dir = dir($basedir);
2656 while (false !== ($entry = $dir->read())) {
2657 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2658 continue;
2660 require_once($basedir.$entry);
2661 $class = 'lesson_page_type_'.strtok($entry,'.');
2662 if (class_exists($class)) {
2663 $pagetype = new $class(new stdClass, $lesson);
2664 $this->types[$pagetype->typeid] = $pagetype;
2671 * Returns an array of strings to describe the loaded page types
2673 * @param int $type Can be used to return JUST the string for the requested type
2674 * @return array
2676 public function get_page_type_strings($type=null, $special=true) {
2677 $types = array();
2678 foreach ($this->types as $pagetype) {
2679 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
2680 $types[$pagetype->typeid] = $pagetype->typestring;
2683 return $types;
2687 * Returns the basic string used to identify a page type provided with an id
2689 * This string can be used to instantiate or identify the page type class.
2690 * If the page type id is unknown then 'unknown' is returned
2692 * @param int $id
2693 * @return string
2695 public function get_page_type_idstring($id) {
2696 foreach ($this->types as $pagetype) {
2697 if ((int)$pagetype->typeid === (int)$id) {
2698 return $pagetype->idstring;
2701 return 'unknown';
2705 * Loads a page for the provided lesson given it's id
2707 * This function loads a page from the lesson when given both the lesson it belongs
2708 * to as well as the page's id.
2709 * If the page doesn't exist an error is thrown
2711 * @param int $pageid The id of the page to load
2712 * @param lesson $lesson The lesson the page belongs to
2713 * @return lesson_page A class that extends lesson_page
2715 public function load_page($pageid, lesson $lesson) {
2716 global $DB;
2717 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
2718 print_error('cannotfindpages', 'lesson');
2720 $pagetype = get_class($this->types[$page->qtype]);
2721 $page = new $pagetype($page, $lesson);
2722 return $page;
2726 * This function detects errors in the ordering between 2 pages and updates the page records.
2728 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
2729 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
2731 protected function check_page_order($page1, $page2) {
2732 global $DB;
2733 if (empty($page1)) {
2734 if ($page2->prevpageid != 0) {
2735 debugging("***prevpageid of page " . $page2->id . " set to 0***");
2736 $page2->prevpageid = 0;
2737 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
2739 } else if (empty($page2)) {
2740 if ($page1->nextpageid != 0) {
2741 debugging("***nextpageid of page " . $page1->id . " set to 0***");
2742 $page1->nextpageid = 0;
2743 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
2745 } else {
2746 if ($page1->nextpageid != $page2->id) {
2747 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
2748 $page1->nextpageid = $page2->id;
2749 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
2751 if ($page2->prevpageid != $page1->id) {
2752 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
2753 $page2->prevpageid = $page1->id;
2754 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
2760 * This function loads ALL pages that belong to the lesson.
2762 * @param lesson $lesson
2763 * @return array An array of lesson_page_type_*
2765 public function load_all_pages(lesson $lesson) {
2766 global $DB;
2767 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
2768 print_error('cannotfindpages', 'lesson');
2770 foreach ($pages as $key=>$page) {
2771 $pagetype = get_class($this->types[$page->qtype]);
2772 $pages[$key] = new $pagetype($page, $lesson);
2775 $orderedpages = array();
2776 $lastpageid = 0;
2777 $morepages = true;
2778 while ($morepages) {
2779 $morepages = false;
2780 foreach ($pages as $page) {
2781 if ((int)$page->prevpageid === (int)$lastpageid) {
2782 // Check for errors in page ordering and fix them on the fly.
2783 $prevpage = null;
2784 if ($lastpageid !== 0) {
2785 $prevpage = $orderedpages[$lastpageid];
2787 $this->check_page_order($prevpage, $page);
2788 $morepages = true;
2789 $orderedpages[$page->id] = $page;
2790 unset($pages[$page->id]);
2791 $lastpageid = $page->id;
2792 if ((int)$page->nextpageid===0) {
2793 break 2;
2794 } else {
2795 break 1;
2801 // Add remaining pages and fix the nextpageid links for each page.
2802 foreach ($pages as $page) {
2803 // Check for errors in page ordering and fix them on the fly.
2804 $prevpage = null;
2805 if ($lastpageid !== 0) {
2806 $prevpage = $orderedpages[$lastpageid];
2808 $this->check_page_order($prevpage, $page);
2809 $orderedpages[$page->id] = $page;
2810 unset($pages[$page->id]);
2811 $lastpageid = $page->id;
2814 if ($lastpageid !== 0) {
2815 $this->check_page_order($orderedpages[$lastpageid], null);
2818 return $orderedpages;
2822 * Fetches an mform that can be used to create/edit an page
2824 * @param int $type The id for the page type
2825 * @param array $arguments Any arguments to pass to the mform
2826 * @return lesson_add_page_form_base
2828 public function get_page_form($type, $arguments) {
2829 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
2830 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
2831 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
2832 $class = 'lesson_add_page_form_selection';
2833 } else if ($class === 'lesson_add_page_form_unknown') {
2834 $class = 'lesson_add_page_form_selection';
2836 return new $class(null, $arguments);
2840 * Returns an array of links to use as add page links
2841 * @param int $previd The id of the previous page
2842 * @return array
2844 public function get_add_page_type_links($previd) {
2845 global $OUTPUT;
2847 $links = array();
2849 foreach ($this->types as $key=>$type) {
2850 if ($link = $type->add_page_link($previd)) {
2851 $links[$key] = $link;
2855 return $links;