3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Local library file for Lesson. These are non-standard functions that are used
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
28 /** Make sure this isn't being directly accessed */
29 defined('MOODLE_INTERNAL') ||
die();
31 /** Include the files that are required by this module */
32 require_once($CFG->dirroot
.'/course/moodleform_mod.php');
33 require_once($CFG->dirroot
. '/mod/lesson/lib.php');
34 require_once($CFG->libdir
. '/filelib.php');
37 define('LESSON_THISPAGE', 0);
38 /** Next page -> any page not seen before */
39 define("LESSON_UNSEENPAGE", 1);
40 /** Next page -> any page not answered correctly */
41 define("LESSON_UNANSWEREDPAGE", 2);
42 /** Jump to Next Page */
43 define("LESSON_NEXTPAGE", -1);
45 define("LESSON_EOL", -9);
46 /** Jump to an unseen page within a branch and end of branch or end of lesson */
47 define("LESSON_UNSEENBRANCHPAGE", -50);
48 /** Jump to Previous Page */
49 define("LESSON_PREVIOUSPAGE", -40);
50 /** Jump to a random page within a branch and end of branch or end of lesson */
51 define("LESSON_RANDOMPAGE", -60);
52 /** Jump to a random Branch */
53 define("LESSON_RANDOMBRANCH", -70);
55 define("LESSON_CLUSTERJUMP", -80);
57 define("LESSON_UNDEFINED", -99);
59 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
60 define("LESSON_MAX_EVENT_LENGTH", "432000");
63 //////////////////////////////////////////////////////////////////////////////////////
64 /// Any other lesson functions go here. Each of them must have a name that
65 /// starts with lesson_
68 * Checks to see if a LESSON_CLUSTERJUMP or
69 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
71 * This function is only executed when a teacher is
72 * checking the navigation for a lesson.
74 * @param stdClass $lesson Id of the lesson that is to be checked.
75 * @return boolean True or false.
77 function lesson_display_teacher_warning($lesson) {
80 // get all of the lesson answers
81 $params = array ("lessonid" => $lesson->id
);
82 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
83 // no answers, then not using cluster or unseen
86 // just check for the first one that fulfills the requirements
87 foreach ($lessonanswers as $lessonanswer) {
88 if ($lessonanswer->jumpto
== LESSON_CLUSTERJUMP ||
$lessonanswer->jumpto
== LESSON_UNSEENBRANCHPAGE
) {
93 // if no answers use either of the two jumps
98 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
100 * will return the pageid of a random unseen page that is within a branch
102 * @param lesson $lesson
103 * @param int $userid Id of the user.
104 * @param int $pageid Id of the page from which we are jumping.
105 * @return int Id of the next page.
107 function lesson_unseen_question_jump($lesson, $user, $pageid) {
110 // get the number of retakes
111 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id
, "userid"=>$user))) {
115 // get all the lesson_attempts aka what the user has seen
116 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id
, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
117 foreach($viewedpages as $viewed) {
118 $seenpages[] = $viewed->pageid
;
121 $seenpages = array();
124 // get the lesson pages
125 $lessonpages = $lesson->load_all_pages();
127 if ($pageid == LESSON_UNSEENBRANCHPAGE
) { // this only happens when a student leaves in the middle of an unseen question within a branch series
128 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
131 // go up the pages till branch table
132 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
133 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_BRANCHTABLE
) {
136 $pageid = $lessonpages[$pageid]->prevpageid
;
139 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
141 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
143 foreach($pagesinbranch as $page) {
144 if (!in_array($page->id
, $seenpages)) {
145 $unseen[] = $page->id
;
149 if(count($unseen) == 0) {
150 if(isset($pagesinbranch)) {
151 $temp = end($pagesinbranch);
152 $nextpage = $temp->nextpageid
; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
154 // there are no pages inside the branch, so return the next page
155 $nextpage = $lessonpages[$pageid]->nextpageid
;
157 if ($nextpage == 0) {
163 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
168 * Handles the unseen branch table jump.
170 * @param lesson $lesson
171 * @param int $userid User id.
172 * @return int Will return the page id of a branch table or end of lesson
174 function lesson_unseen_branch_jump($lesson, $userid) {
177 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id
, "userid"=>$userid))) {
181 $params = array ("lessonid" => $lesson->id
, "userid" => $userid, "retry" => $retakes);
182 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
184 print_error('cannotfindrecords', 'lesson');
187 // get the lesson pages
188 $lessonpages = $lesson->load_all_pages();
190 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
191 // which is the branch table that starts the unseenbranch function
193 foreach ($seenbranches as $seenbranch) {
194 if (!$seenbranch->flag
) {
195 $seen[$seenbranch->pageid
] = $seenbranch->pageid
;
197 $start = $seenbranch->pageid
;
201 // this function searches through the lesson pages to find all the branch tables
202 // that follow the flagged branch table
203 $pageid = $lessonpages[$start]->nextpageid
; // move down from the flagged branch table
204 $branchtables = array();
205 while ($pageid != 0) { // grab all of the branch table till eol
206 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_BRANCHTABLE
) {
207 $branchtables[] = $lessonpages[$pageid]->id
;
209 $pageid = $lessonpages[$pageid]->nextpageid
;
212 foreach ($branchtables as $branchtable) {
213 // load all of the unseen branch tables into unseen
214 if (!array_key_exists($branchtable, $seen)) {
215 $unseen[] = $branchtable;
218 if (count($unseen) > 0) {
219 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
221 return LESSON_EOL
; // has viewed all of the branch tables
226 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
228 * @param lesson $lesson
229 * @param int $pageid The id of the page that we are jumping from (?)
230 * @return int The pageid of a random page that is within a branch table
232 function lesson_random_question_jump($lesson, $pageid) {
235 // get the lesson pages
236 $params = array ("lessonid" => $lesson->id
);
237 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
238 print_error('cannotfindpages', 'lesson');
241 // go up the pages till branch table
242 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
244 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_BRANCHTABLE
) {
247 $pageid = $lessonpages[$pageid]->prevpageid
;
250 // get the pages within the branch
251 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
253 if(count($pagesinbranch) == 0) {
254 // there are no pages inside the branch, so return the next page
255 return $lessonpages[$pageid]->nextpageid
;
257 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id
; // returns a random page id for the next page
262 * Calculates a user's grade for a lesson.
264 * @param object $lesson The lesson that the user is taking.
265 * @param int $retries The attempt number.
266 * @param int $userid Id of the user (optional, default current user).
267 * @return object { nquestions => number of questions answered
268 attempts => number of question attempts
269 total => max points possible
270 earned => points earned by student
271 grade => calculated percentage grade
272 nmanual => number of manually graded questions
273 manualpoints => point value for manually graded questions }
275 function lesson_grade($lesson, $ntries, $userid = 0) {
278 if (empty($userid)) {
282 // Zero out everything
293 $params = array ("lessonid" => $lesson->id
, "userid" => $userid, "retry" => $ntries);
294 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
295 userid = :userid AND retry = :retry", $params, "timeseen")) {
296 // group each try with its page
297 $attemptset = array();
298 foreach ($useranswers as $useranswer) {
299 $attemptset[$useranswer->pageid
][] = $useranswer;
302 // Drop all attempts that go beyond max attempts for the lesson
303 foreach ($attemptset as $key => $set) {
304 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts
);
307 // get only the pages and their answers that the user answered
308 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
309 array_unshift($parameters, $lesson->id
);
310 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
311 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
313 // Number of pages answered
314 $nquestions = count($pages);
316 foreach ($attemptset as $attempts) {
317 $page = lesson_page
::load($pages[end($attempts)->pageid
], $lesson);
318 if ($lesson->custom
) {
319 $attempt = end($attempts);
320 // If essay question, handle it, otherwise add to score
321 if ($page->requires_manual_grading()) {
322 $useranswerobj = unserialize($attempt->useranswer
);
323 if (isset($useranswerobj->score
)) {
324 $earned +
= $useranswerobj->score
;
327 $manualpoints +
= $answers[$attempt->answerid
]->score
;
328 } else if (!empty($attempt->answerid
)) {
329 $earned +
= $page->earned_score($answers, $attempt);
332 foreach ($attempts as $attempt) {
333 $earned +
= $attempt->correct
;
335 $attempt = end($attempts); // doesn't matter which one
336 // If essay question, increase numbers
337 if ($page->requires_manual_grading()) {
342 // Number of times answered
343 $nviewed +
= count($attempts);
346 if ($lesson->custom
) {
347 $bestscores = array();
348 // Find the highest possible score per page to get our total
349 foreach ($answers as $answer) {
350 if(!isset($bestscores[$answer->pageid
])) {
351 $bestscores[$answer->pageid
] = $answer->score
;
352 } else if ($bestscores[$answer->pageid
] < $answer->score
) {
353 $bestscores[$answer->pageid
] = $answer->score
;
356 $total = array_sum($bestscores);
358 // Check to make sure the student has answered the minimum questions
359 if ($lesson->minquestions
and $nquestions < $lesson->minquestions
) {
360 // Nope, increase number viewed by the amount of unanswered questions
361 $total = $nviewed +
($lesson->minquestions
- $nquestions);
368 if ($total) { // not zero
369 $thegrade = round(100 * $earned / $total, 5);
372 // Build the grade information object
373 $gradeinfo = new stdClass
;
374 $gradeinfo->nquestions
= $nquestions;
375 $gradeinfo->attempts
= $nviewed;
376 $gradeinfo->total
= $total;
377 $gradeinfo->earned
= $earned;
378 $gradeinfo->grade
= $thegrade;
379 $gradeinfo->nmanual
= $nmanual;
380 $gradeinfo->manualpoints
= $manualpoints;
386 * Determines if a user can view the left menu. The determining factor
387 * is whether a user has a grade greater than or equal to the lesson setting
390 * @param object $lesson Lesson object of the current lesson
391 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
393 function lesson_displayleftif($lesson) {
394 global $CFG, $USER, $DB;
396 if (!empty($lesson->displayleftif
)) {
397 // get the current user's max grade for this lesson
398 $params = array ("userid" => $USER->id
, "lessonid" => $lesson->id
);
399 if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
400 if ($maxgrade->maxgrade
< $lesson->displayleftif
) {
401 return 0; // turn off the displayleft
404 return 0; // no grades
408 // if we get to here, keep the original state of displayleft lesson setting
409 return $lesson->displayleft
;
417 * @return unknown_type
419 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
420 $bc = lesson_menu_block_contents($cm->id
, $lesson);
422 $regions = $page->blocks
->get_regions();
423 $firstregion = reset($regions);
424 $page->blocks
->add_fake_block($bc, $firstregion);
427 $bc = lesson_mediafile_block_contents($cm->id
, $lesson);
429 $page->blocks
->add_fake_block($bc, $page->blocks
->get_default_region());
432 if (!empty($timer)) {
433 $bc = lesson_clock_block_contents($cm->id
, $lesson, $timer, $page);
435 $page->blocks
->add_fake_block($bc, $page->blocks
->get_default_region());
441 * If there is a media file associated with this
442 * lesson, return a block_contents that displays it.
444 * @param int $cmid Course Module ID for this lesson
445 * @param object $lesson Full lesson record object
446 * @return block_contents
448 function lesson_mediafile_block_contents($cmid, $lesson) {
450 if (empty($lesson->mediafile
)) {
455 $options['menubar'] = 0;
456 $options['location'] = 0;
457 $options['left'] = 5;
459 $options['scrollbars'] = 1;
460 $options['resizable'] = 1;
461 $options['width'] = $lesson->mediawidth
;
462 $options['height'] = $lesson->mediaheight
;
464 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
465 $action = new popup_action('click', $link, 'lessonmediafile', $options);
466 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
468 $bc = new block_contents();
469 $bc->title
= get_string('linkedmedia', 'lesson');
470 $bc->attributes
['class'] = 'mediafile';
471 $bc->content
= $content;
477 * If a timed lesson and not a teacher, then
478 * return a block_contents containing the clock.
480 * @param int $cmid Course Module ID for this lesson
481 * @param object $lesson Full lesson record object
482 * @param object $timer Full timer record object
483 * @return block_contents
485 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
486 // Display for timed lessons and for students only
487 $context = context_module
::instance($cmid);
488 if(!$lesson->timed ||
has_capability('mod/lesson:manage', $context)) {
492 $content = '<div class="jshidewhenenabled">';
493 $content .= $lesson->time_remaining($timer->starttime
);
494 $content .= '</div>';
496 $clocksettings = array('starttime'=>$timer->starttime
, 'servertime'=>time(),'testlength'=>($lesson->maxtime
* 60));
497 $page->requires
->data_for_js('clocksettings', $clocksettings);
498 $page->requires
->js('/mod/lesson/timer.js');
499 $page->requires
->js_function_call('show_clock');
501 $bc = new block_contents();
502 $bc->title
= get_string('timeremaining', 'lesson');
503 $bc->attributes
['class'] = 'clock block';
504 $bc->content
= $content;
510 * If left menu is turned on, then this will
511 * print the menu in a block
513 * @param int $cmid Course Module ID for this lesson
514 * @param lesson $lesson Full lesson record object
517 function lesson_menu_block_contents($cmid, $lesson) {
520 if (!$lesson->displayleft
) {
524 $pages = $lesson->load_all_pages();
525 foreach ($pages as $page) {
526 if ((int)$page->prevpageid
=== 0) {
531 $currentpageid = optional_param('pageid', $pageid, PARAM_INT
);
533 if (!$pageid ||
!$pages) {
537 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
539 while ($pageid != 0) {
540 $page = $pages[$pageid];
542 // Only process branch tables with display turned on
543 if ($page->displayinmenublock
&& $page->display
) {
544 if ($page->id
== $currentpageid) {
545 $content .= '<li class="selected">'.format_string($page->title
,true)."</li>\n";
547 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title
,true)."</a></li>\n";
551 $pageid = $page->nextpageid
;
553 $content .= "</ul>\n</div>\n";
555 $bc = new block_contents();
556 $bc->title
= get_string('lessonmenu', 'lesson');
557 $bc->attributes
['class'] = 'menu block';
558 $bc->content
= $content;
564 * Adds header buttons to the page for the lesson
567 * @param object $context
568 * @param bool $extraeditbuttons
569 * @param int $lessonpageid
571 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
572 global $CFG, $PAGE, $OUTPUT;
573 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
574 if ($lessonpageid === null) {
575 print_error('invalidpageid', 'lesson');
577 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL
) {
578 $url = new moodle_url('/mod/lesson/editpage.php', array('id'=>$cm->id
, 'pageid'=>$lessonpageid, 'edit'=>1));
579 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
585 * This is a function used to detect media types and generate html code.
587 * @global object $CFG
588 * @global object $PAGE
589 * @param object $lesson
590 * @param object $context
591 * @return string $code the html code of media
593 function lesson_get_media_html($lesson, $context) {
594 global $CFG, $PAGE, $OUTPUT;
595 require_once("$CFG->libdir/resourcelib.php");
597 // get the media file link
598 if (strpos($lesson->mediafile
, '://') !== false) {
599 $url = new moodle_url($lesson->mediafile
);
601 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
602 $url = moodle_url
::make_pluginfile_url($context->id
, 'mod_lesson', 'mediafile', $lesson->timemodified
, '/', ltrim($lesson->mediafile
, '/'));
604 $title = $lesson->mediafile
;
606 $clicktoopen = html_writer
::link($url, get_string('download'));
608 $mimetype = resourcelib_guess_url_mimetype($url);
610 $extension = resourcelib_get_extension($url->out(false));
612 $mediarenderer = $PAGE->get_renderer('core', 'media');
613 $embedoptions = array(
614 core_media
::OPTION_TRUSTED
=> true,
615 core_media
::OPTION_BLOCK
=> true
618 // find the correct type and print it out
619 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
620 $code = resourcelib_embed_image($url, $title);
622 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
623 // Media (audio/video) file.
624 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
627 // anything else - just try object tag enlarged as much as possible
628 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
636 * Abstract class that page type's MUST inherit from.
638 * This is the abstract class that ALL add page type forms must extend.
639 * You will notice that all but two of the methods this class contains are final.
640 * Essentially the only thing that extending classes can do is extend custom_definition.
641 * OR if it has a special requirement on creation it can extend construction_override
644 * @copyright 2009 Sam Hemelryk
645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 abstract class lesson_add_page_form_base
extends moodleform
{
650 * This is the classic define that is used to identify this pagetype.
651 * Will be one of LESSON_*
657 * The simple string that describes the page type e.g. truefalse, multichoice
663 * An array of options used in the htmleditor
666 protected $editoroptions = array();
669 * True if this is a standard page of false if it does something special.
670 * Questions are standard pages, branch tables are not
673 protected $standard = true;
676 * Each page type can and should override this to add any custom elements to
677 * the basic form that they want
679 public function custom_definition() {}
682 * Used to determine if this is a standard page or a special page
685 public final function is_standard() {
686 return (bool)$this->standard
;
690 * Add the required basic elements to the form.
692 * This method adds the basic elements to the form including title and contents
693 * and then calls custom_definition();
695 public final function definition() {
696 $mform = $this->_form
;
697 $editoroptions = $this->_customdata
['editoroptions'];
699 $mform->addElement('header', 'qtypeheading', get_string('addaquestionpage', 'lesson', get_string($this->qtypestring
, 'lesson')));
701 $mform->addElement('hidden', 'id');
702 $mform->setType('id', PARAM_INT
);
704 $mform->addElement('hidden', 'pageid');
705 $mform->setType('pageid', PARAM_INT
);
707 if ($this->standard
=== true) {
708 $mform->addElement('hidden', 'qtype');
709 $mform->setType('qtype', PARAM_INT
);
711 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
712 $mform->setType('title', PARAM_TEXT
);
713 $mform->addRule('title', get_string('required'), 'required', null, 'client');
715 $this->editoroptions
= array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$this->_customdata
['maxbytes']);
716 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions
);
717 $mform->setType('contents_editor', PARAM_RAW
);
718 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
721 $this->custom_definition();
723 if ($this->_customdata
['edit'] === true) {
724 $mform->addElement('hidden', 'edit', 1);
725 $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'));
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) {
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 $name = "score[$name]";
767 $this->_form
->addElement('text', $name, $label, array('size'=>5));
768 if ($value !== null) {
769 $this->_form
->setDefault($name, $value);
774 * Convenience function: Adds an answer editor
776 * @param int $count The count of the element to add
777 * @param string $label, NULL means default
778 * @param bool $required
781 protected final function add_answer($count, $label = NULL, $required = false) {
782 if ($label === NULL) {
783 $label = get_string('answer', 'lesson');
785 $this->_form
->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
786 $this->_form
->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE
));
788 $this->_form
->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
792 * Convenience function: Adds an response editor
794 * @param int $count The count of the element to add
795 * @param string $label, NULL means default
796 * @param bool $required
799 protected final function add_response($count, $label = NULL, $required = false) {
800 if ($label === NULL) {
801 $label = get_string('response', 'lesson');
803 $this->_form
->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
804 $this->_form
->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE
));
806 $this->_form
->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
811 * A function that gets called upon init of this object by the calling script.
813 * This can be used to process an immediate action if required. Currently it
814 * is only used in special cases by non-standard page types.
818 public function construction_override($pageid, lesson
$lesson) {
826 * Class representation of a lesson
828 * This class is used the interact with, and manage a lesson once instantiated.
829 * If you need to fetch a lesson object you can do so by calling
832 * lesson::load($lessonid);
834 * $lessonrecord = $DB->get_record('lesson', $lessonid);
835 * $lesson = new lesson($lessonrecord);
838 * The class itself extends lesson_base as all classes within the lesson module should
840 * These properties are from the database
841 * @property int $id The id of this lesson
842 * @property int $course The ID of the course this lesson belongs to
843 * @property string $name The name of this lesson
844 * @property int $practice Flag to toggle this as a practice lesson
845 * @property int $modattempts Toggle to allow the user to go back and review answers
846 * @property int $usepassword Toggle the use of a password for entry
847 * @property string $password The password to require users to enter
848 * @property int $dependency ID of another lesson this lesson is dependent on
849 * @property string $conditions Conditions of the lesson dependency
850 * @property int $grade The maximum grade a user can achieve (%)
851 * @property int $custom Toggle custom scoring on or off
852 * @property int $ongoing Toggle display of an ongoing score
853 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
854 * @property int $maxanswers The max number of answers or branches
855 * @property int $maxattempts The maximum number of attempts a user can record
856 * @property int $review Toggle use or wrong answer review button
857 * @property int $nextpagedefault Override the default next page
858 * @property int $feedback Toggles display of default feedback
859 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
860 * @property int $maxpages Maximum number of pages this lesson can contain
861 * @property int $retake Flag to allow users to retake a lesson
862 * @property int $activitylink Relate this lesson to another lesson
863 * @property string $mediafile File to pop up to or webpage to display
864 * @property int $mediaheight Sets the height of the media file popup
865 * @property int $mediawidth Sets the width of the media file popup
866 * @property int $mediaclose Toggle display of a media close button
867 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
868 * @property int $width Width of slideshow
869 * @property int $height Height of slideshow
870 * @property string $bgcolor Background colour of slideshow
871 * @property int $displayleft Display a left menu
872 * @property int $displayleftif Sets the condition on which the left menu is displayed
873 * @property int $progressbar Flag to toggle display of a lesson progress bar
874 * @property int $highscores Flag to toggle collection of high scores
875 * @property int $maxhighscores Number of high scores to limit to
876 * @property int $available Timestamp of when this lesson becomes available
877 * @property int $deadline Timestamp of when this lesson is no longer available
878 * @property int $timemodified Timestamp when lesson was last modified
880 * These properties are calculated
881 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
882 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
884 * @copyright 2009 Sam Hemelryk
885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
887 class lesson
extends lesson_base
{
890 * The id of the first page (where prevpageid = 0) gets set and retrieved by
891 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
894 protected $firstpageid = null;
896 * The id of the last page (where nextpageid = 0) gets set and retrieved by
897 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
900 protected $lastpageid = null;
902 * An array used to cache the pages associated with this lesson after the first
903 * time they have been loaded.
904 * A note to developers: If you are going to be working with MORE than one or
905 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
906 * in order to save excess database queries.
907 * @var array An array of lesson_page objects
909 protected $pages = array();
911 * Flag that gets set to true once all of the pages associated with the lesson
915 protected $loadedallpages = false;
918 * Simply generates a lesson object given an array/object of properties
919 * Overrides {@see lesson_base->create()}
921 * @param object|array $properties
924 public static function create($properties) {
925 return new lesson($properties);
929 * Generates a lesson object from the database given its id
931 * @param int $lessonid
934 public static function load($lessonid) {
937 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
938 print_error('invalidcoursemodule');
940 return new lesson($lesson);
944 * Deletes this lesson from the database
946 public function delete() {
948 require_once($CFG->libdir
.'/gradelib.php');
949 require_once($CFG->dirroot
.'/calendar/lib.php');
951 $DB->delete_records("lesson", array("id"=>$this->properties
->id
));;
952 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties
->id
));
953 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties
->id
));
954 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties
->id
));
955 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties
->id
));
956 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties
->id
));
957 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties
->id
));
958 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties
->id
));
959 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties
->id
))) {
960 foreach($events as $event) {
961 $event = calendar_event
::load($event);
966 grade_update('mod/lesson', $this->properties
->course
, 'mod', 'lesson', $this->properties
->id
, 0, NULL, array('deleted'=>1));
971 * Fetches messages from the session that may have been set in previous page
975 * // Do not call this method directly instead use
981 protected function get_messages() {
985 if (!empty($SESSION->lesson_messages
) && is_array($SESSION->lesson_messages
) && array_key_exists($this->properties
->id
, $SESSION->lesson_messages
)) {
986 $messages = $SESSION->lesson_messages
[$this->properties
->id
];
987 unset($SESSION->lesson_messages
[$this->properties
->id
]);
994 * Get all of the attempts for the current user.
996 * @param int $retries
997 * @param bool $correct Optional: only fetch correct attempts
998 * @param int $pageid Optional: only fetch attempts at the given page
999 * @param int $userid Optional: defaults to the current user if not set
1000 * @return array|false
1002 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1004 $params = array("lessonid"=>$this->properties
->id
, "userid"=>$userid, "retry"=>$retries);
1006 $params['correct'] = 1;
1008 if ($pageid !== null) {
1009 $params['pageid'] = $pageid;
1011 if ($userid === null) {
1012 $params['userid'] = $USER->id
;
1014 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1018 * Returns the first page for the lesson or false if there isn't one.
1020 * This method should be called via the magic method __get();
1022 * $firstpage = $lesson->firstpage;
1025 * @return lesson_page|bool Returns the lesson_page specialised object or false
1027 protected function get_firstpage() {
1028 $pages = $this->load_all_pages();
1029 if (count($pages) > 0) {
1030 foreach ($pages as $page) {
1031 if ((int)$page->prevpageid
=== 0) {
1040 * Returns the last page for the lesson or false if there isn't one.
1042 * This method should be called via the magic method __get();
1044 * $lastpage = $lesson->lastpage;
1047 * @return lesson_page|bool Returns the lesson_page specialised object or false
1049 protected function get_lastpage() {
1050 $pages = $this->load_all_pages();
1051 if (count($pages) > 0) {
1052 foreach ($pages as $page) {
1053 if ((int)$page->nextpageid
=== 0) {
1062 * Returns the id of the first page of this lesson. (prevpageid = 0)
1065 protected function get_firstpageid() {
1067 if ($this->firstpageid
== null) {
1068 if (!$this->loadedallpages
) {
1069 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties
->id
, 'prevpageid'=>0));
1070 if (!$firstpageid) {
1071 print_error('cannotfindfirstpage', 'lesson');
1073 $this->firstpageid
= $firstpageid;
1075 $firstpage = $this->get_firstpage();
1076 $this->firstpageid
= $firstpage->id
;
1079 return $this->firstpageid
;
1083 * Returns the id of the last page of this lesson. (nextpageid = 0)
1086 public function get_lastpageid() {
1088 if ($this->lastpageid
== null) {
1089 if (!$this->loadedallpages
) {
1090 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties
->id
, 'nextpageid'=>0));
1092 print_error('cannotfindlastpage', 'lesson');
1094 $this->lastpageid
= $lastpageid;
1096 $lastpageid = $this->get_lastpage();
1097 $this->lastpageid
= $lastpageid->id
;
1101 return $this->lastpageid
;
1105 * Gets the next page id to display after the one that is provided.
1106 * @param int $nextpageid
1109 public function get_next_page($nextpageid) {
1111 $allpages = $this->load_all_pages();
1112 if ($this->properties
->nextpagedefault
) {
1113 // in Flash Card mode...first get number of retakes
1114 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
));
1117 if ($this->properties
->nextpagedefault
== LESSON_UNSEENPAGE
) {
1118 foreach ($allpages as $nextpage) {
1119 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id
, "userid" => $USER->id
, "retry" => $nretakes))) {
1124 } elseif ($this->properties
->nextpagedefault
== LESSON_UNANSWEREDPAGE
) {
1125 foreach ($allpages as $nextpage) {
1126 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id
, 'userid' => $USER->id
, 'correct' => 1, 'retry' => $nretakes))) {
1133 if ($this->properties
->maxpages
) {
1134 // check number of pages viewed (in the lesson)
1135 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties
->id
, "userid" => $USER->id
, "retry" => $nretakes)) >= $this->properties
->maxpages
) {
1139 return $nextpage->id
;
1142 // In a normal lesson mode
1143 foreach ($allpages as $nextpage) {
1144 if ((int)$nextpage->id
=== (int)$nextpageid) {
1145 return $nextpage->id
;
1152 * Sets a message against the session for this lesson that will displayed next
1153 * time the lesson processes messages
1155 * @param string $message
1156 * @param string $class
1157 * @param string $align
1160 public function add_message($message, $class="notifyproblem", $align='center') {
1163 if (empty($SESSION->lesson_messages
) ||
!is_array($SESSION->lesson_messages
)) {
1164 $SESSION->lesson_messages
= array();
1165 $SESSION->lesson_messages
[$this->properties
->id
] = array();
1166 } else if (!array_key_exists($this->properties
->id
, $SESSION->lesson_messages
)) {
1167 $SESSION->lesson_messages
[$this->properties
->id
] = array();
1170 $SESSION->lesson_messages
[$this->properties
->id
][] = array($message, $class, $align);
1176 * Check if the lesson is accessible at the present time
1177 * @return bool True if the lesson is accessible, false otherwise
1179 public function is_accessible() {
1180 $available = $this->properties
->available
;
1181 $deadline = $this->properties
->deadline
;
1182 return (($available == 0 ||
time() >= $available) && ($deadline == 0 ||
time() < $deadline));
1186 * Starts the lesson time for the current user
1187 * @return bool Returns true
1189 public function start_timer() {
1191 $USER->startlesson
[$this->properties
->id
] = true;
1192 $startlesson = new stdClass
;
1193 $startlesson->lessonid
= $this->properties
->id
;
1194 $startlesson->userid
= $USER->id
;
1195 $startlesson->starttime
= time();
1196 $startlesson->lessontime
= time();
1197 $DB->insert_record('lesson_timer', $startlesson);
1198 if ($this->properties
->timed
) {
1199 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties
->maxtime
), 'center');
1205 * Updates the timer to the current time and returns the new timer object
1206 * @param bool $restart If set to true the timer is restarted
1207 * @param bool $continue If set to true AND $restart=true then the timer
1208 * will continue from a previous attempt
1209 * @return stdClass The new timer
1211 public function update_timer($restart=false, $continue=false) {
1214 // get time information for this user
1215 if (!$timer = $DB->get_records('lesson_timer', array ("lessonid" => $this->properties
->id
, "userid" => $USER->id
), 'starttime DESC', '*', 0, 1)) {
1216 print_error('cannotfindtimer', 'lesson');
1218 $timer = current($timer); // this will get the latest start time record
1223 // continue a previous test, need to update the clock (think this option is disabled atm)
1224 $timer->starttime
= time() - ($timer->lessontime
- $timer->starttime
);
1226 // starting over, so reset the clock
1227 $timer->starttime
= time();
1231 $timer->lessontime
= time();
1232 $DB->update_record('lesson_timer', $timer);
1237 * Updates the timer to the current time then stops it by unsetting the user var
1238 * @return bool Returns true
1240 public function stop_timer() {
1242 unset($USER->startlesson
[$this->properties
->id
]);
1243 return $this->update_timer(false, false);
1247 * Checks to see if the lesson has pages
1249 public function has_pages() {
1251 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties
->id
));
1252 return ($pagecount>0);
1256 * Returns the link for the related activity
1257 * @return array|false
1259 public function link_for_activitylink() {
1261 $module = $DB->get_record('course_modules', array('id' => $this->properties
->activitylink
));
1263 $modname = $DB->get_field('modules', 'name', array('id' => $module->module
));
1265 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance
));
1266 if ($instancename) {
1267 return html_writer
::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties
->activitylink
)),
1268 get_string('activitylinkname', 'lesson', $instancename),
1269 array('class'=>'centerpadded lessonbutton standardbutton'));
1277 * Loads the requested page.
1279 * This function will return the requested page id as either a specialised
1280 * lesson_page object OR as a generic lesson_page.
1281 * If the page has been loaded previously it will be returned from the pages
1282 * array, otherwise it will be loaded from the database first
1284 * @param int $pageid
1285 * @return lesson_page A lesson_page object or an object that extends it
1287 public function load_page($pageid) {
1288 if (!array_key_exists($pageid, $this->pages
)) {
1289 $manager = lesson_page_type_manager
::get($this);
1290 $this->pages
[$pageid] = $manager->load_page($pageid, $this);
1292 return $this->pages
[$pageid];
1296 * Loads ALL of the pages for this lesson
1298 * @return array An array containing all pages from this lesson
1300 public function load_all_pages() {
1301 if (!$this->loadedallpages
) {
1302 $manager = lesson_page_type_manager
::get($this);
1303 $this->pages
= $manager->load_all_pages($this);
1304 $this->loadedallpages
= true;
1306 return $this->pages
;
1310 * Determines if a jumpto value is correct or not.
1312 * returns true if jumpto page is (logically) after the pageid page or
1313 * if the jumpto value is a special value. Returns false in all other cases.
1315 * @param int $pageid Id of the page from which you are jumping from.
1316 * @param int $jumpto The jumpto number.
1317 * @return boolean True or false after a series of tests.
1319 public function jumpto_is_correct($pageid, $jumpto) {
1322 // first test the special values
1326 } elseif ($jumpto == LESSON_NEXTPAGE
) {
1328 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE
) {
1330 } elseif ($jumpto == LESSON_RANDOMPAGE
) {
1332 } elseif ($jumpto == LESSON_CLUSTERJUMP
) {
1334 } elseif ($jumpto == LESSON_EOL
) {
1338 $pages = $this->load_all_pages();
1339 $apageid = $pages[$pageid]->nextpageid
;
1340 while ($apageid != 0) {
1341 if ($jumpto == $apageid) {
1344 $apageid = $pages[$apageid]->nextpageid
;
1350 * Returns the time a user has remaining on this lesson
1351 * @param int $starttime Starttime timestamp
1354 public function time_remaining($starttime) {
1355 $timeleft = $starttime +
$this->maxtime
* 60 - time();
1356 $hours = floor($timeleft/3600);
1357 $timeleft = $timeleft - ($hours * 3600);
1358 $minutes = floor($timeleft/60);
1359 $secs = $timeleft - ($minutes * 60);
1361 if ($minutes < 10) {
1362 $minutes = "0$minutes";
1369 $output[] = $minutes;
1371 $output = implode(':', $output);
1376 * Interprets LESSON_CLUSTERJUMP jumpto value.
1378 * This will select a page randomly
1379 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1380 * and the page selected will be a page that has not been viewed already
1381 * and if any pages are within a branch table or end of branch then only 1 page within
1382 * the branch table or end of branch will be randomly selected (sub clustering).
1384 * @param int $pageid Id of the current page from which we are jumping from.
1385 * @param int $userid Id of the user.
1386 * @return int The id of the next page.
1388 public function cluster_jump($pageid, $userid=null) {
1391 if ($userid===null) {
1392 $userid = $USER->id
;
1394 // get the number of retakes
1395 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties
->id
, "userid"=>$userid))) {
1398 // get all the lesson_attempts aka what the user has seen
1399 $seenpages = array();
1400 if ($attempts = $this->get_attempts($retakes)) {
1401 foreach ($attempts as $attempt) {
1402 $seenpages[$attempt->pageid
] = $attempt->pageid
;
1407 // get the lesson pages
1408 $lessonpages = $this->load_all_pages();
1409 // find the start of the cluster
1410 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1411 if ($lessonpages[$pageid]->qtype
== LESSON_PAGE_CLUSTER
) {
1414 $pageid = $lessonpages[$pageid]->prevpageid
;
1417 $clusterpages = array();
1418 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER
));
1420 foreach ($clusterpages as $key=>$cluster) {
1421 if ($cluster->type
!== lesson_page
::TYPE_QUESTION
) {
1422 unset($clusterpages[$key]);
1423 } elseif ($cluster->is_unseen($seenpages)) {
1424 $unseen[] = $cluster;
1428 if (count($unseen) > 0) {
1429 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1430 $nextpage = $unseen[rand(0, count($unseen)-1)];
1431 if ($nextpage->qtype
== LESSON_PAGE_BRANCHTABLE
) {
1432 // if branch table, then pick a random page inside of it
1433 $branchpages = $this->get_sub_pages_of($nextpage->id
, array(LESSON_PAGE_BRANCHTABLE
, LESSON_PAGE_ENDOFBRANCH
));
1434 return $branchpages[rand(0, count($branchpages)-1)]->id
;
1435 } else { // otherwise, return the page's id
1436 return $nextpage->id
;
1439 // seen all there is to see, leave the cluster
1440 if (end($clusterpages)->nextpageid
== 0) {
1443 $clusterendid = $pageid;
1444 while ($clusterendid != 0) { // this condition should not be satisfied... should be a cluster page
1445 if ($lessonpages[$clusterendid]->qtype
== LESSON_PAGE_CLUSTER
) {
1448 $clusterendid = $lessonpages[$clusterendid]->prevpageid
;
1450 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties
->id
));
1451 if ($exitjump == LESSON_NEXTPAGE
) {
1452 $exitjump = $lessonpages[$pageid]->nextpageid
;
1454 if ($exitjump == 0) {
1456 } else if (in_array($exitjump, array(LESSON_EOL
, LESSON_PREVIOUSPAGE
))) {
1459 if (!array_key_exists($exitjump, $lessonpages)) {
1461 foreach ($lessonpages as $page) {
1462 if ($page->id
=== $clusterendid) {
1464 } else if ($page->qtype
== LESSON_PAGE_ENDOFCLUSTER
) {
1465 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id
, "lessonid" => $this->properties
->id
));
1470 if (!array_key_exists($exitjump, $lessonpages)) {
1480 * Finds all pages that appear to be a subtype of the provided pageid until
1481 * an end point specified within $ends is encountered or no more pages exist
1483 * @param int $pageid
1484 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1486 * @return array An array of specialised lesson_page objects
1488 public function get_sub_pages_of($pageid, array $ends) {
1489 $lessonpages = $this->load_all_pages();
1490 $pageid = $lessonpages[$pageid]->nextpageid
; // move to the first page after the branch table
1494 if ($pageid == 0 ||
in_array($lessonpages[$pageid]->qtype
, $ends)) {
1497 $pages[] = $lessonpages[$pageid];
1498 $pageid = $lessonpages[$pageid]->nextpageid
;
1505 * Checks to see if the specified page[id] is a subpage of a type specified in
1506 * the $types array, until either there are no more pages of we find a type
1507 * corresponding to that of a type specified in $ends
1509 * @param int $pageid The id of the page to check
1510 * @param array $types An array of types that would signify this page was a subpage
1511 * @param array $ends An array of types that mean this is not a subpage
1514 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1515 $pages = $this->load_all_pages();
1516 $pageid = $pages[$pageid]->prevpageid
; // move up one
1518 array_unshift($ends, 0);
1519 // go up the pages till branch table
1521 if ($pageid==0 ||
in_array($pages[$pageid]->qtype
, $ends)) {
1523 } else if (in_array($pages[$pageid]->qtype
, $types)) {
1526 $pageid = $pages[$pageid]->prevpageid
;
1533 * Abstract class to provide a core functions to the all lesson classes
1535 * This class should be abstracted by ALL classes with the lesson module to ensure
1536 * that all classes within this module can be interacted with in the same way.
1538 * This class provides the user with a basic properties array that can be fetched
1539 * or set via magic methods, or alternatively by defining methods get_blah() or
1540 * set_blah() within the extending object.
1542 * @copyright 2009 Sam Hemelryk
1543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1545 abstract class lesson_base
{
1548 * An object containing properties
1551 protected $properties;
1555 * @param stdClass $properties
1557 public function __construct($properties) {
1558 $this->properties
= (object)$properties;
1562 * Magic property method
1564 * Attempts to call a set_$key method if one exists otherwise falls back
1565 * to simply set the property
1567 * @param string $key
1568 * @param mixed $value
1570 public function __set($key, $value) {
1571 if (method_exists($this, 'set_'.$key)) {
1572 $this->{'set_'.$key}($value);
1574 $this->properties
->{$key} = $value;
1580 * Attempts to call a get_$key method to return the property and ralls over
1581 * to return the raw property
1586 public function __get($key) {
1587 if (method_exists($this, 'get_'.$key)) {
1588 return $this->{'get_'.$key}();
1590 return $this->properties
->{$key};
1594 * Stupid PHP needs an isset magic method if you use the get magic method and
1595 * still want empty calls to work.... blah ~!
1597 * @param string $key
1600 public function __isset($key) {
1601 if (method_exists($this, 'get_'.$key)) {
1602 $val = $this->{'get_'.$key}();
1603 return !empty($val);
1605 return !empty($this->properties
->{$key});
1608 //NOTE: E_STRICT does not allow to change function signature!
1611 * If implemented should create a new instance, save it in the DB and return it
1613 //public static function create() {}
1615 * If implemented should load an instance from the DB and return it
1617 //public static function load() {}
1619 * Fetches all of the properties of the object
1622 public function properties() {
1623 return $this->properties
;
1629 * Abstract class representation of a page associated with a lesson.
1631 * This class should MUST be extended by all specialised page types defined in
1632 * mod/lesson/pagetypes/.
1633 * There are a handful of abstract methods that need to be defined as well as
1634 * severl methods that can optionally be defined in order to make the page type
1635 * operate in the desired way
1637 * Database properties
1638 * @property int $id The id of this lesson page
1639 * @property int $lessonid The id of the lesson this page belongs to
1640 * @property int $prevpageid The id of the page before this one
1641 * @property int $nextpageid The id of the next page in the page sequence
1642 * @property int $qtype Identifies the page type of this page
1643 * @property int $qoption Used to record page type specific options
1644 * @property int $layout Used to record page specific layout selections
1645 * @property int $display Used to record page specific display selections
1646 * @property int $timecreated Timestamp for when the page was created
1647 * @property int $timemodified Timestamp for when the page was last modified
1648 * @property string $title The title of this page
1649 * @property string $contents The rich content shown to describe the page
1650 * @property int $contentsformat The format of the contents field
1652 * Calculated properties
1653 * @property-read array $answers An array of answers for this page
1654 * @property-read bool $displayinmenublock Toggles display in the left menu block
1655 * @property-read array $jumps An array containing all the jumps this page uses
1656 * @property-read lesson $lesson The lesson this page belongs to
1657 * @property-read int $type The type of the page [question | structure]
1658 * @property-read typeid The unique identifier for the page type
1659 * @property-read typestring The string that describes this page type
1662 * @copyright 2009 Sam Hemelryk
1663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1665 abstract class lesson_page
extends lesson_base
{
1668 * A reference to the lesson this page belongs to
1671 protected $lesson = null;
1673 * Contains the answers to this lesson_page once loaded
1676 protected $answers = null;
1678 * This sets the type of the page, can be one of the constants defined below
1681 protected $type = 0;
1684 * Constants used to identify the type of the page
1686 const TYPE_QUESTION
= 0;
1687 const TYPE_STRUCTURE
= 1;
1690 * This method should return the integer used to identify the page type within
1691 * the database and throughout code. This maps back to the defines used in 1.x
1695 abstract protected function get_typeid();
1697 * This method should return the string that describes the pagetype
1701 abstract protected function get_typestring();
1704 * This method gets called to display the page to the user taking the lesson
1706 * @param object $renderer
1707 * @param object $attempt
1710 abstract public function display($renderer, $attempt);
1713 * Creates a new lesson_page within the database and returns the correct pagetype
1714 * object to use to interact with the new lesson
1718 * @param object $properties
1719 * @param lesson $lesson
1720 * @return lesson_page Specialised object that extends lesson_page
1722 final public static function create($properties, lesson
$lesson, $context, $maxbytes) {
1724 $newpage = new stdClass
;
1725 $newpage->title
= $properties->title
;
1726 $newpage->contents
= $properties->contents_editor
['text'];
1727 $newpage->contentsformat
= $properties->contents_editor
['format'];
1728 $newpage->lessonid
= $lesson->id
;
1729 $newpage->timecreated
= time();
1730 $newpage->qtype
= $properties->qtype
;
1731 $newpage->qoption
= (isset($properties->qoption
))?
1:0;
1732 $newpage->layout
= (isset($properties->layout
))?
1:0;
1733 $newpage->display
= (isset($properties->display
))?
1:0;
1734 $newpage->prevpageid
= 0; // this is a first page
1735 $newpage->nextpageid
= 0; // this is the only page
1737 if ($properties->pageid
) {
1738 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid
), 'id, nextpageid');
1740 print_error('cannotfindpages', 'lesson');
1742 $newpage->prevpageid
= $prevpage->id
;
1743 $newpage->nextpageid
= $prevpage->nextpageid
;
1745 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id
, 'prevpageid'=>0), 'id');
1747 // This is the first page, there are existing pages put this at the start
1748 $newpage->nextpageid
= $nextpage->id
;
1752 $newpage->id
= $DB->insert_record("lesson_pages", $newpage);
1754 $editor = new stdClass
;
1755 $editor->id
= $newpage->id
;
1756 $editor->contents_editor
= $properties->contents_editor
;
1757 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id
);
1758 $DB->update_record("lesson_pages", $editor);
1760 if ($newpage->prevpageid
> 0) {
1761 $DB->set_field("lesson_pages", "nextpageid", $newpage->id
, array("id" => $newpage->prevpageid
));
1763 if ($newpage->nextpageid
> 0) {
1764 $DB->set_field("lesson_pages", "prevpageid", $newpage->id
, array("id" => $newpage->nextpageid
));
1767 $page = lesson_page
::load($newpage, $lesson);
1768 $page->create_answers($properties);
1770 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title
, true), 'notifysuccess');
1776 * This method loads a page object from the database and returns it as a
1777 * specialised object that extends lesson_page
1782 * @param lesson $lesson
1783 * @return lesson_page Specialised lesson_page object
1785 final public static function load($id, lesson
$lesson) {
1788 if (is_object($id) && !empty($id->qtype
)) {
1791 $page = $DB->get_record("lesson_pages", array("id" => $id));
1793 print_error('cannotfindpages', 'lesson');
1796 $manager = lesson_page_type_manager
::get($lesson);
1798 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype
);
1799 if (!class_exists($class)) {
1800 $class = 'lesson_page';
1803 return new $class($page, $lesson);
1807 * Deletes a lesson_page from the database as well as any associated records.
1811 final public function delete() {
1813 // first delete all the associated records...
1814 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties
->id
));
1815 // ...now delete the answers...
1816 $DB->delete_records("lesson_answers", array("pageid" => $this->properties
->id
));
1817 // ..and the page itself
1818 $DB->delete_records("lesson_pages", array("id" => $this->properties
->id
));
1820 // repair the hole in the linkage
1821 if (!$this->properties
->prevpageid
&& !$this->properties
->nextpageid
) {
1822 //This is the only page, no repair needed
1823 } elseif (!$this->properties
->prevpageid
) {
1824 // this is the first page...
1825 $page = $this->lesson
->load_page($this->properties
->nextpageid
);
1826 $page->move(null, 0);
1827 } elseif (!$this->properties
->nextpageid
) {
1828 // this is the last page...
1829 $page = $this->lesson
->load_page($this->properties
->prevpageid
);
1832 // page is in the middle...
1833 $prevpage = $this->lesson
->load_page($this->properties
->prevpageid
);
1834 $nextpage = $this->lesson
->load_page($this->properties
->nextpageid
);
1836 $prevpage->move($nextpage->id
);
1837 $nextpage->move(null, $prevpage->id
);
1843 * Moves a page by updating its nextpageid and prevpageid values within
1847 * @param int $nextpageid
1848 * @param int $prevpageid
1850 final public function move($nextpageid=null, $prevpageid=null) {
1852 if ($nextpageid === null) {
1853 $nextpageid = $this->properties
->nextpageid
;
1855 if ($prevpageid === null) {
1856 $prevpageid = $this->properties
->prevpageid
;
1858 $obj = new stdClass
;
1859 $obj->id
= $this->properties
->id
;
1860 $obj->prevpageid
= $prevpageid;
1861 $obj->nextpageid
= $nextpageid;
1862 $DB->update_record('lesson_pages', $obj);
1866 * Returns the answers that are associated with this page in the database
1871 final public function get_answers() {
1873 if ($this->answers
=== null) {
1874 $this->answers
= array();
1875 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties
->id
, 'lessonid'=>$this->lesson
->id
), 'id');
1877 // It is possible that a lesson upgraded from Moodle 1.9 still
1878 // contains questions without any answers [MDL-25632].
1879 // debugging(get_string('cannotfindanswer', 'lesson'));
1882 foreach ($answers as $answer) {
1883 $this->answers
[count($this->answers
)] = new lesson_page_answer($answer);
1886 return $this->answers
;
1890 * Returns the lesson this page is associated with
1894 final protected function get_lesson() {
1895 return $this->lesson
;
1899 * Returns the type of page this is. Not to be confused with page type
1903 final protected function get_type() {
1908 * Records an attempt at this page
1911 * @global moodle_database $DB
1912 * @param stdClass $context
1913 * @return stdClass Returns the result of the attempt
1915 final public function record_attempt($context) {
1916 global $DB, $USER, $OUTPUT;
1919 * This should be overridden by each page type to actually check the response
1920 * against what ever custom criteria they have defined
1922 $result = $this->check_answer();
1924 $result->attemptsremaining
= 0;
1925 $result->maxattemptsreached
= false;
1927 if ($result->noanswer
) {
1928 $result->newpageid
= $this->properties
->id
; // display same page again
1929 $result->feedback
= get_string('noanswer', 'lesson');
1931 if (!has_capability('mod/lesson:manage', $context)) {
1932 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson
->id
, "userid"=>$USER->id
));
1933 // record student's attempt
1934 $attempt = new stdClass
;
1935 $attempt->lessonid
= $this->lesson
->id
;
1936 $attempt->pageid
= $this->properties
->id
;
1937 $attempt->userid
= $USER->id
;
1938 $attempt->answerid
= $result->answerid
;
1939 $attempt->retry
= $nretakes;
1940 $attempt->correct
= $result->correctanswer
;
1941 if($result->userresponse
!== null) {
1942 $attempt->useranswer
= $result->userresponse
;
1945 $attempt->timeseen
= time();
1946 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
1947 if (isset($USER->modattempts
[$this->lesson
->id
])) {
1948 $attempt->retry
= $nretakes - 1; // they are going through on review, $nretakes will be too high
1951 if ($this->lesson
->retake ||
(!$this->lesson
->retake
&& $nretakes == 0)) {
1952 $DB->insert_record("lesson_attempts", $attempt);
1954 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
1955 // displaying of message(s) is at the end of page for more ergonomic display
1956 if (!$result->correctanswer
&& ($result->newpageid
== 0)) {
1957 // wrong answer and student is stuck on this page - check how many attempts
1958 // the student has had at this page/question
1959 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties
->id
, "userid"=>$USER->id
, "retry" => $attempt->retry
));
1960 // retreive the number of attempts left counter for displaying at bottom of feedback page
1961 if ($nattempts >= $this->lesson
->maxattempts
) {
1962 if ($this->lesson
->maxattempts
> 1) { // don't bother with message if only one attempt
1963 $result->maxattemptsreached
= true;
1965 $result->newpageid
= LESSON_NEXTPAGE
;
1966 } else if ($this->lesson
->maxattempts
> 1) { // don't bother with message if only one attempt
1967 $result->attemptsremaining
= $this->lesson
->maxattempts
- $nattempts;
1971 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
1972 if ($result->newpageid
== 0) {
1973 $result->newpageid
= $this->properties
->id
;
1974 } elseif ($result->newpageid
== LESSON_NEXTPAGE
) {
1975 $result->newpageid
= $this->lesson
->get_next_page($this->properties
->nextpageid
);
1978 // Determine default feedback if necessary
1979 if (empty($result->response
)) {
1980 if (!$this->lesson
->feedback
&& !$result->noanswer
&& !($this->lesson
->review
& !$result->correctanswer
&& !$result->isessayquestion
)) {
1981 // These conditions have been met:
1982 // 1. The lesson manager has not supplied feedback to the student
1983 // 2. Not displaying default feedback
1984 // 3. The user did provide an answer
1985 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
1987 $result->nodefaultresponse
= true; // This will cause a redirect below
1988 } else if ($result->isessayquestion
) {
1989 $result->response
= get_string('defaultessayresponse', 'lesson');
1990 } else if ($result->correctanswer
) {
1991 $result->response
= get_string('thatsthecorrectanswer', 'lesson');
1993 $result->response
= get_string('thatsthewronganswer', 'lesson');
1997 if ($result->response
) {
1998 if ($this->lesson
->review
&& !$result->correctanswer
&& !$result->isessayquestion
) {
1999 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson
->id
, "userid"=>$USER->id
));
2000 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id
, "retry"=>$nretakes, "pageid"=>$this->properties
->id
));
2001 if ($qattempts == 1) {
2002 $result->feedback
= $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2004 $result->feedback
= $OUTPUT->BOX(get_string("secondpluswrong", "lesson"), 'feedback');
2007 $class = 'response';
2008 if ($result->correctanswer
) {
2009 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2010 } else if (!$result->isessayquestion
) {
2011 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2013 $options = new stdClass
;
2014 $options->noclean
= true;
2015 $options->para
= true;
2016 $options->overflowdiv
= true;
2017 $result->feedback
= $OUTPUT->box(format_text($this->get_contents(), $this->properties
->contentsformat
, $options), 'generalbox boxaligncenter');
2018 $result->feedback
.= '<div class="correctanswer generalbox"><em>'.get_string("youranswer", "lesson").'</em> : '.$result->studentanswer
; // already in clean html
2019 $result->feedback
.= $OUTPUT->box($result->response
, $class); // already conerted to HTML
2020 $result->feedback
.= '</div>';
2029 * Returns the string for a jump name
2032 * @param int $jumpto Jump code or page ID
2035 final protected function get_jump_name($jumpto) {
2037 static $jumpnames = array();
2039 if (!array_key_exists($jumpto, $jumpnames)) {
2040 if ($jumpto == LESSON_THISPAGE
) {
2041 $jumptitle = get_string('thispage', 'lesson');
2042 } elseif ($jumpto == LESSON_NEXTPAGE
) {
2043 $jumptitle = get_string('nextpage', 'lesson');
2044 } elseif ($jumpto == LESSON_EOL
) {
2045 $jumptitle = get_string('endoflesson', 'lesson');
2046 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE
) {
2047 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2048 } elseif ($jumpto == LESSON_PREVIOUSPAGE
) {
2049 $jumptitle = get_string('previouspage', 'lesson');
2050 } elseif ($jumpto == LESSON_RANDOMPAGE
) {
2051 $jumptitle = get_string('randompageinbranch', 'lesson');
2052 } elseif ($jumpto == LESSON_RANDOMBRANCH
) {
2053 $jumptitle = get_string('randombranch', 'lesson');
2054 } elseif ($jumpto == LESSON_CLUSTERJUMP
) {
2055 $jumptitle = get_string('clusterjump', 'lesson');
2057 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2058 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2061 $jumpnames[$jumpto] = format_string($jumptitle,true);
2064 return $jumpnames[$jumpto];
2068 * Constructor method
2069 * @param object $properties
2070 * @param lesson $lesson
2072 public function __construct($properties, lesson
$lesson) {
2073 parent
::__construct($properties);
2074 $this->lesson
= $lesson;
2078 * Returns the score for the attempt
2079 * This may be overridden by page types that require manual grading
2080 * @param array $answers
2081 * @param object $attempt
2084 public function earned_score($answers, $attempt) {
2085 return $answers[$attempt->answerid
]->score
;
2089 * This is a callback method that can be override and gets called when ever a page
2092 * @param bool $canmanage True if the user has the manage cap
2095 public function callback_on_view($canmanage) {
2100 * Updates a lesson page and its answers within the database
2102 * @param object $properties
2105 public function update($properties, $context = null, $maxbytes = null) {
2107 $answers = $this->get_answers();
2108 $properties->id
= $this->properties
->id
;
2109 $properties->lessonid
= $this->lesson
->id
;
2110 if (empty($properties->qoption
)) {
2111 $properties->qoption
= '0';
2113 if (empty($context)) {
2114 $context = $PAGE->context
;
2116 if ($maxbytes === null) {
2117 $maxbytes = get_user_max_upload_file_size($context);
2119 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES
, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id
);
2120 $DB->update_record("lesson_pages", $properties);
2122 for ($i = 0; $i < $this->lesson
->maxanswers
; $i++
) {
2123 if (!array_key_exists($i, $this->answers
)) {
2124 $this->answers
[$i] = new stdClass
;
2125 $this->answers
[$i]->lessonid
= $this->lesson
->id
;
2126 $this->answers
[$i]->pageid
= $this->id
;
2127 $this->answers
[$i]->timecreated
= $this->timecreated
;
2130 if (!empty($properties->answer_editor
[$i]) && is_array($properties->answer_editor
[$i])) {
2131 $this->answers
[$i]->answer
= $properties->answer_editor
[$i]['text'];
2132 $this->answers
[$i]->answerformat
= $properties->answer_editor
[$i]['format'];
2134 if (!empty($properties->response_editor
[$i]) && is_array($properties->response_editor
[$i])) {
2135 $this->answers
[$i]->response
= $properties->response_editor
[$i]['text'];
2136 $this->answers
[$i]->responseformat
= $properties->response_editor
[$i]['format'];
2139 // we don't need to check for isset here because properties called it's own isset method.
2140 if ($this->answers
[$i]->answer
!= '') {
2141 if (isset($properties->jumpto
[$i])) {
2142 $this->answers
[$i]->jumpto
= $properties->jumpto
[$i];
2144 if ($this->lesson
->custom
&& isset($properties->score
[$i])) {
2145 $this->answers
[$i]->score
= $properties->score
[$i];
2147 if (!isset($this->answers
[$i]->id
)) {
2148 $this->answers
[$i]->id
= $DB->insert_record("lesson_answers", $this->answers
[$i]);
2150 $DB->update_record("lesson_answers", $this->answers
[$i]->properties());
2153 } else if (isset($this->answers
[$i]->id
)) {
2154 $DB->delete_records('lesson_answers', array('id'=>$this->answers
[$i]->id
));
2155 unset($this->answers
[$i]);
2162 * Can be set to true if the page requires a static link to create a new instance
2163 * instead of simply being included in the dropdown
2164 * @param int $previd
2167 public function add_page_link($previd) {
2172 * Returns true if a page has been viewed before
2174 * @param array|int $param Either an array of pages that have been seen or the
2175 * number of retakes a user has had
2178 public function is_unseen($param) {
2180 if (is_array($param)) {
2181 $seenpages = $param;
2182 return (!array_key_exists($this->properties
->id
, $seenpages));
2185 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties
->id
, "userid"=>$USER->id
, "retry"=>$nretakes))) {
2193 * Checks to see if a page has been answered previously
2194 * @param int $nretakes
2197 public function is_unanswered($nretakes) {
2199 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties
->id
, 'userid'=>$USER->id
, 'correct'=>1, 'retry'=>$nretakes))) {
2206 * Creates answers within the database for this lesson_page. Usually only ever
2207 * called when creating a new page instance
2208 * @param object $properties
2211 public function create_answers($properties) {
2213 // now add the answers
2214 $newanswer = new stdClass
;
2215 $newanswer->lessonid
= $this->lesson
->id
;
2216 $newanswer->pageid
= $this->properties
->id
;
2217 $newanswer->timecreated
= $this->properties
->timecreated
;
2221 for ($i = 0; $i < $this->lesson
->maxanswers
; $i++
) {
2222 $answer = clone($newanswer);
2224 if (!empty($properties->answer_editor
[$i]) && is_array($properties->answer_editor
[$i])) {
2225 $answer->answer
= $properties->answer_editor
[$i]['text'];
2226 $answer->answerformat
= $properties->answer_editor
[$i]['format'];
2228 if (!empty($properties->response_editor
[$i]) && is_array($properties->response_editor
[$i])) {
2229 $answer->response
= $properties->response_editor
[$i]['text'];
2230 $answer->responseformat
= $properties->response_editor
[$i]['format'];
2233 if (isset($answer->answer
) && $answer->answer
!= '') {
2234 if (isset($properties->jumpto
[$i])) {
2235 $answer->jumpto
= $properties->jumpto
[$i];
2237 if ($this->lesson
->custom
&& isset($properties->score
[$i])) {
2238 $answer->score
= $properties->score
[$i];
2240 $answer->id
= $DB->insert_record("lesson_answers", $answer);
2241 $answers[$answer->id
] = new lesson_page_answer($answer);
2247 $this->answers
= $answers;
2252 * This method MUST be overridden by all question page types, or page types that
2253 * wish to score a page.
2255 * The structure of result should always be the same so it is a good idea when
2256 * overriding this method on a page type to call
2258 * $result = parent::check_answer();
2260 * before modifying it as required.
2264 public function check_answer() {
2265 $result = new stdClass
;
2266 $result->answerid
= 0;
2267 $result->noanswer
= false;
2268 $result->correctanswer
= false;
2269 $result->isessayquestion
= false; // use this to turn off review button on essay questions
2270 $result->response
= '';
2271 $result->newpageid
= 0; // stay on the page
2272 $result->studentanswer
= ''; // use this to store student's answer(s) in order to display it on feedback page
2273 $result->userresponse
= null;
2274 $result->feedback
= '';
2275 $result->nodefaultresponse
= false; // Flag for redirecting when default feedback is turned off
2280 * True if the page uses a custom option
2282 * Should be override and set to true if the page uses a custom option.
2286 public function has_option() {
2291 * Returns the maximum number of answers for this page given the maximum number
2292 * of answers permitted by the lesson.
2294 * @param int $default
2297 public function max_answers($default) {
2302 * Returns the properties of this lesson page as an object
2305 public function properties() {
2306 $properties = clone($this->properties
);
2307 if ($this->answers
=== null) {
2308 $this->get_answers();
2310 if (count($this->answers
)>0) {
2312 $qtype = $properties->qtype
;
2313 foreach ($this->answers
as $answer) {
2314 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer
, 'format' => $answer->answerformat
);
2315 if ($qtype != LESSON_PAGE_MATCHING
) {
2316 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response
, 'format' => $answer->responseformat
);
2318 $properties->{'response_editor['.$count.']'} = $answer->response
;
2320 $properties->{'jumpto['.$count.']'} = $answer->jumpto
;
2321 $properties->{'score['.$count.']'} = $answer->score
;
2329 * Returns an array of options to display when choosing the jumpto for a page/answer
2331 * @param int $pageid
2332 * @param lesson $lesson
2335 public static function get_jumptooptions($pageid, lesson
$lesson) {
2338 $jump[0] = get_string("thispage", "lesson");
2339 $jump[LESSON_NEXTPAGE
] = get_string("nextpage", "lesson");
2340 $jump[LESSON_PREVIOUSPAGE
] = get_string("previouspage", "lesson");
2341 $jump[LESSON_EOL
] = get_string("endoflesson", "lesson");
2347 $pages = $lesson->load_all_pages();
2348 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
))) {
2349 $jump[LESSON_UNSEENBRANCHPAGE
] = get_string("unseenpageinbranch", "lesson");
2350 $jump[LESSON_RANDOMPAGE
] = get_string("randompageinbranch", "lesson");
2352 if($pages[$pageid]->qtype
== LESSON_PAGE_CLUSTER ||
$lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER
), array(LESSON_PAGE_ENDOFCLUSTER
))) {
2353 $jump[LESSON_CLUSTERJUMP
] = get_string("clusterjump", "lesson");
2355 if (!optional_param('firstpage', 0, PARAM_INT
)) {
2356 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id
, "prevpageid" => 0));
2359 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2360 $jump[$apageid] = strip_tags(format_string($title,true));
2361 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2363 // last page reached
2371 * Returns the contents field for the page properly formatted and with plugin
2372 * file url's converted
2375 public function get_contents() {
2377 if (!empty($this->properties
->contents
)) {
2378 if (!isset($this->properties
->contentsformat
)) {
2379 $this->properties
->contentsformat
= FORMAT_HTML
;
2381 $context = context_module
::instance($PAGE->cm
->id
);
2382 $contents = file_rewrite_pluginfile_urls($this->properties
->contents
, 'pluginfile.php', $context->id
, 'mod_lesson', 'page_contents', $this->properties
->id
); // must do this BEFORE format_text()!!!!!!
2383 return format_text($contents, $this->properties
->contentsformat
, array('context'=>$context, 'noclean'=>true)); // page edit is marked with XSS, we want all content here
2390 * Set to true if this page should display in the menu block
2393 protected function get_displayinmenublock() {
2398 * Get the string that describes the options of this page type
2401 public function option_description_string() {
2406 * Updates a table with the answers for this page
2407 * @param html_table $table
2408 * @return html_table
2410 public function display_answers(html_table
$table) {
2411 $answers = $this->get_answers();
2413 foreach ($answers as $answer) {
2415 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2416 $cells[] = $this->get_jump_name($answer->jumpto
);
2417 $table->data
[] = new html_table_row($cells);
2419 $table->data
[count($table->data
)-1]->cells
[0]->style
= 'width:20%;';
2427 * Determines if this page should be grayed out on the management/report screens
2428 * @return int 0 or 1
2430 protected function get_grayout() {
2435 * Adds stats for this page to the &pagestats object. This should be defined
2436 * for all page types that grade
2437 * @param array $pagestats
2441 public function stats(array &$pagestats, $tries) {
2446 * Formats the answers of this page for a report
2448 * @param object $answerpage
2449 * @param object $answerdata
2450 * @param object $useranswer
2451 * @param array $pagestats
2452 * @param int $i Count of first level answers
2453 * @param int $n Count of second level answers
2454 * @return object The answer page for this
2456 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2457 $answers = $this->get_answers();
2458 $formattextdefoptions = new stdClass
;
2459 $formattextdefoptions->para
= false; //I'll use it widely in this page
2460 foreach ($answers as $answer) {
2461 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto
));
2462 $answerdata->answers
[] = array($data, "");
2463 $answerpage->answerdata
= $answerdata;
2469 * Gets an array of the jumps used by the answers of this page
2473 public function get_jumps() {
2476 $params = array ("lessonid" => $this->lesson
->id
, "pageid" => $this->properties
->id
);
2477 if ($answers = $this->get_answers()) {
2478 foreach ($answers as $answer) {
2479 $jumps[] = $this->get_jump_name($answer->jumpto
);
2482 $jumps[] = $this->get_jump_name($this->properties
->nextpageid
);
2487 * Informs whether this page type require manual grading or not
2490 public function requires_manual_grading() {
2495 * A callback method that allows a page to override the next page a user will
2496 * see during when this page is being completed.
2499 public function override_next_page() {
2504 * This method is used to determine if this page is a valid page
2506 * @param array $validpages
2507 * @param array $pageviews
2508 * @return int The next page id to check
2510 public function valid_page_and_view(&$validpages, &$pageviews) {
2511 $validpages[$this->properties
->id
] = 1;
2512 return $this->properties
->nextpageid
;
2519 * Class used to represent an answer to a page
2521 * @property int $id The ID of this answer in the database
2522 * @property int $lessonid The ID of the lesson this answer belongs to
2523 * @property int $pageid The ID of the page this answer belongs to
2524 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2525 * @property int $grade The grade this answer is worth
2526 * @property int $score The score this answer will give
2527 * @property int $flags Used to store options for the answer
2528 * @property int $timecreated A timestamp of when the answer was created
2529 * @property int $timemodified A timestamp of when the answer was modified
2530 * @property string $answer The answer itself
2531 * @property string $response The response the user sees if selecting this answer
2533 * @copyright 2009 Sam Hemelryk
2534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2536 class lesson_page_answer
extends lesson_base
{
2539 * Loads an page answer from the DB
2542 * @return lesson_page_answer
2544 public static function load($id) {
2546 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2547 return new lesson_page_answer($answer);
2551 * Given an object of properties and a page created answer(s) and saves them
2554 * @param stdClass $properties
2555 * @param lesson_page $page
2558 public static function create($properties, lesson_page
$page) {
2559 return $page->create_answers($properties);
2565 * A management class for page types
2567 * This class is responsible for managing the different pages. A manager object can
2568 * be retrieved by calling the following line of code:
2570 * $manager = lesson_page_type_manager::get($lesson);
2572 * The first time the page type manager is retrieved the it includes all of the
2573 * different page types located in mod/lesson/pagetypes.
2575 * @copyright 2009 Sam Hemelryk
2576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2578 class lesson_page_type_manager
{
2581 * An array of different page type classes
2584 protected $types = array();
2587 * Retrieves the lesson page type manager object
2589 * If the object hasn't yet been created it is created here.
2591 * @staticvar lesson_page_type_manager $pagetypemanager
2592 * @param lesson $lesson
2593 * @return lesson_page_type_manager
2595 public static function get(lesson
$lesson) {
2596 static $pagetypemanager;
2597 if (!($pagetypemanager instanceof lesson_page_type_manager
)) {
2598 $pagetypemanager = new lesson_page_type_manager();
2599 $pagetypemanager->load_lesson_types($lesson);
2601 return $pagetypemanager;
2605 * Finds and loads all lesson page types in mod/lesson/pagetypes
2607 * @param lesson $lesson
2609 public function load_lesson_types(lesson
$lesson) {
2611 $basedir = $CFG->dirroot
.'/mod/lesson/pagetypes/';
2612 $dir = dir($basedir);
2613 while (false !== ($entry = $dir->read())) {
2614 if (strpos($entry, '.')===0 ||
!preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2617 require_once($basedir.$entry);
2618 $class = 'lesson_page_type_'.strtok($entry,'.');
2619 if (class_exists($class)) {
2620 $pagetype = new $class(new stdClass
, $lesson);
2621 $this->types
[$pagetype->typeid
] = $pagetype;
2628 * Returns an array of strings to describe the loaded page types
2630 * @param int $type Can be used to return JUST the string for the requested type
2633 public function get_page_type_strings($type=null, $special=true) {
2635 foreach ($this->types
as $pagetype) {
2636 if (($type===null ||
$pagetype->type
===$type) && ($special===true ||
$pagetype->is_standard())) {
2637 $types[$pagetype->typeid
] = $pagetype->typestring
;
2644 * Returns the basic string used to identify a page type provided with an id
2646 * This string can be used to instantiate or identify the page type class.
2647 * If the page type id is unknown then 'unknown' is returned
2652 public function get_page_type_idstring($id) {
2653 foreach ($this->types
as $pagetype) {
2654 if ((int)$pagetype->typeid
=== (int)$id) {
2655 return $pagetype->idstring
;
2662 * Loads a page for the provided lesson given it's id
2664 * This function loads a page from the lesson when given both the lesson it belongs
2665 * to as well as the page's id.
2666 * If the page doesn't exist an error is thrown
2668 * @param int $pageid The id of the page to load
2669 * @param lesson $lesson The lesson the page belongs to
2670 * @return lesson_page A class that extends lesson_page
2672 public function load_page($pageid, lesson
$lesson) {
2674 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id
)))) {
2675 print_error('cannotfindpages', 'lesson');
2677 $pagetype = get_class($this->types
[$page->qtype
]);
2678 $page = new $pagetype($page, $lesson);
2683 * This function loads ALL pages that belong to the lesson.
2685 * @param lesson $lesson
2686 * @return array An array of lesson_page_type_*
2688 public function load_all_pages(lesson
$lesson) {
2690 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id
)))) {
2691 print_error('cannotfindpages', 'lesson');
2693 foreach ($pages as $key=>$page) {
2694 $pagetype = get_class($this->types
[$page->qtype
]);
2695 $pages[$key] = new $pagetype($page, $lesson);
2698 $orderedpages = array();
2702 foreach ($pages as $page) {
2703 if ((int)$page->prevpageid
=== (int)$lastpageid) {
2704 $orderedpages[$page->id
] = $page;
2705 unset($pages[$page->id
]);
2706 $lastpageid = $page->id
;
2707 if ((int)$page->nextpageid
===0) {
2716 return $orderedpages;
2720 * Fetches an mform that can be used to create/edit an page
2722 * @param int $type The id for the page type
2723 * @param array $arguments Any arguments to pass to the mform
2724 * @return lesson_add_page_form_base
2726 public function get_page_form($type, $arguments) {
2727 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
2728 if (!class_exists($class) ||
get_parent_class($class)!=='lesson_add_page_form_base') {
2729 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER
);
2730 $class = 'lesson_add_page_form_selection';
2731 } else if ($class === 'lesson_add_page_form_unknown') {
2732 $class = 'lesson_add_page_form_selection';
2734 return new $class(null, $arguments);
2738 * Returns an array of links to use as add page links
2739 * @param int $previd The id of the previous page
2742 public function get_add_page_type_links($previd) {
2747 foreach ($this->types
as $key=>$type) {
2748 if ($link = $type->add_page_link($previd)) {
2749 $links[$key] = $link;