blocklib MDL-25654 fix API inconsistency be renaming add_pretend_block to add_fake_block.
[moodle.git] / mod / lesson / locallib.php
CommitLineData
87f83794 1<?php
2
0a4abb73
SH
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.
14//
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/>.
17
5491947a 18/**
19 * Local library file for Lesson. These are non-standard functions that are used
20 * only by Lesson.
21 *
cc3dbaaa
PS
22 * @package mod
23 * @subpackage lesson
0a4abb73 24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
cc3dbaaa 25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
5491947a 26 **/
4b55d2af 27
0a4abb73 28/** Make sure this isn't being directly accessed */
1e7f8ea2 29defined('MOODLE_INTERNAL') || die();
0a4abb73
SH
30
31/** Include the files that are required by this module */
1e7f8ea2 32require_once($CFG->dirroot.'/course/moodleform_mod.php');
0a4abb73
SH
33require_once($CFG->dirroot . '/mod/lesson/lib.php');
34
44cb7e63
PS
35/** This page */
36define('LESSON_THISPAGE', 0);
0a4abb73
SH
37/** Next page -> any page not seen before */
38define("LESSON_UNSEENPAGE", 1);
39/** Next page -> any page not answered correctly */
40define("LESSON_UNANSWEREDPAGE", 2);
41/** Jump to Next Page */
42define("LESSON_NEXTPAGE", -1);
43/** End of Lesson */
44define("LESSON_EOL", -9);
45/** Jump to an unseen page within a branch and end of branch or end of lesson */
46define("LESSON_UNSEENBRANCHPAGE", -50);
47/** Jump to Previous Page */
48define("LESSON_PREVIOUSPAGE", -40);
49/** Jump to a random page within a branch and end of branch or end of lesson */
50define("LESSON_RANDOMPAGE", -60);
51/** Jump to a random Branch */
52define("LESSON_RANDOMBRANCH", -70);
53/** Cluster Jump */
54define("LESSON_CLUSTERJUMP", -80);
55/** Undefined */
56define("LESSON_UNDEFINED", -99);
5e7856af 57
1e7f8ea2
PS
58/** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59define("LESSON_MAX_EVENT_LENGTH", "432000");
60
61
5e7856af 62//////////////////////////////////////////////////////////////////////////////////////
86342d63 63/// Any other lesson functions go here. Each of them must have a name that
5e7856af 64/// starts with lesson_
65
4b55d2af 66/**
86342d63 67 * Checks to see if a LESSON_CLUSTERJUMP or
4b55d2af 68 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
69 *
86342d63 70 * This function is only executed when a teacher is
4b55d2af 71 * checking the navigation for a lesson.
72 *
3983f2dc 73 * @param stdClass $lesson Id of the lesson that is to be checked.
4b55d2af 74 * @return boolean True or false.
75 **/
06469639 76function lesson_display_teacher_warning($lesson) {
646fc290 77 global $DB;
86342d63 78
ac8e16be 79 // get all of the lesson answers
0a4abb73 80 $params = array ("lessonid" => $lesson->id);
646fc290 81 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
64a3ce8c 82 // no answers, then not using cluster or unseen
ac8e16be 83 return false;
84 }
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;
89 }
90 }
86342d63 91
ac8e16be 92 // if no answers use either of the two jumps
93 return false;
5e7856af 94}
95
4b55d2af 96/**
97 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
86342d63 98 *
4b55d2af 99 * will return the pageid of a random unseen page that is within a branch
100 *
0a4abb73 101 * @param lesson $lesson
f521f98a 102 * @param int $userid Id of the user.
4b55d2af 103 * @param int $pageid Id of the page from which we are jumping.
104 * @return int Id of the next page.
4b55d2af 105 **/
5e7856af 106function lesson_unseen_question_jump($lesson, $user, $pageid) {
646fc290 107 global $DB;
86342d63 108
ac8e16be 109 // get the number of retakes
0a4abb73 110 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
ac8e16be 111 $retakes = 0;
112 }
113
114 // get all the lesson_attempts aka what the user has seen
0a4abb73 115 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
ac8e16be 116 foreach($viewedpages as $viewed) {
117 $seenpages[] = $viewed->pageid;
118 }
119 } else {
120 $seenpages = array();
121 }
122
123 // get the lesson pages
0a4abb73 124 $lessonpages = $lesson->load_all_pages();
86342d63 125
ac8e16be 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
128 }
129
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
0a4abb73 132 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 133 break;
134 }
135 $pageid = $lessonpages[$pageid]->prevpageid;
136 }
86342d63 137
97b4ec5e 138 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
86342d63 139
ac8e16be 140 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
141 $unseen = array();
86342d63 142 foreach($pagesinbranch as $page) {
ac8e16be 143 if (!in_array($page->id, $seenpages)) {
144 $unseen[] = $page->id;
145 }
146 }
147
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;
155 }
156 if ($nextpage == 0) {
157 return LESSON_EOL;
158 } else {
159 return $nextpage;
160 }
161 } else {
162 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
163 }
5e7856af 164}
165
4b55d2af 166/**
167 * Handles the unseen branch table jump.
168 *
0a4abb73 169 * @param lesson $lesson
f521f98a 170 * @param int $userid User id.
4b55d2af 171 * @return int Will return the page id of a branch table or end of lesson
4b55d2af 172 **/
0a4abb73 173function lesson_unseen_branch_jump($lesson, $userid) {
646fc290 174 global $DB;
86342d63 175
0a4abb73 176 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
ac8e16be 177 $retakes = 0;
178 }
179
0a4abb73 180 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
646fc290 181 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
ac8e16be 182 "timeseen DESC")) {
86f93345 183 print_error('cannotfindrecords', 'lesson');
ac8e16be 184 }
185
186 // get the lesson pages
0a4abb73 187 $lessonpages = $lesson->load_all_pages();
86342d63 188
ff85f902 189 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
ac8e16be 190 // which is the branch table that starts the unseenbranch function
86342d63 191 $seen = array();
ac8e16be 192 foreach ($seenbranches as $seenbranch) {
193 if (!$seenbranch->flag) {
194 $seen[$seenbranch->pageid] = $seenbranch->pageid;
195 } else {
196 $start = $seenbranch->pageid;
197 break;
198 }
199 }
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 while ($pageid != 0) { // grab all of the branch table till eol
0a4abb73 204 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 205 $branchtables[] = $lessonpages[$pageid]->id;
206 }
207 $pageid = $lessonpages[$pageid]->nextpageid;
208 }
209 $unseen = array();
210 foreach ($branchtables as $branchtable) {
211 // load all of the unseen branch tables into unseen
212 if (!array_key_exists($branchtable, $seen)) {
213 $unseen[] = $branchtable;
214 }
215 }
216 if (count($unseen) > 0) {
217 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
218 } else {
219 return LESSON_EOL; // has viewed all of the branch tables
220 }
5e7856af 221}
222
4b55d2af 223/**
224 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
86342d63 225 *
0a4abb73 226 * @param lesson $lesson
4b55d2af 227 * @param int $pageid The id of the page that we are jumping from (?)
228 * @return int The pageid of a random page that is within a branch table
4b55d2af 229 **/
0a4abb73 230function lesson_random_question_jump($lesson, $pageid) {
646fc290 231 global $DB;
86342d63 232
ac8e16be 233 // get the lesson pages
0a4abb73 234 $params = array ("lessonid" => $lesson->id);
646fc290 235 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
86f93345 236 print_error('cannotfindpages', 'lesson');
ac8e16be 237 }
238
239 // go up the pages till branch table
240 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
241
0a4abb73 242 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 243 break;
244 }
245 $pageid = $lessonpages[$pageid]->prevpageid;
246 }
247
86342d63 248 // get the pages within the branch
97b4ec5e 249 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
86342d63 250
ac8e16be 251 if(count($pagesinbranch) == 0) {
252 // there are no pages inside the branch, so return the next page
253 return $lessonpages[$pageid]->nextpageid;
254 } else {
255 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
256 }
5e7856af 257}
258
4b55d2af 259/**
260 * Calculates a user's grade for a lesson.
261 *
4b55d2af 262 * @param object $lesson The lesson that the user is taking.
4b55d2af 263 * @param int $retries The attempt number.
ff85f902 264 * @param int $userid Id of the user (optional, default current user).
88427c07 265 * @return object { nquestions => number of questions answered
266 attempts => number of question attempts
267 total => max points possible
268 earned => points earned by student
269 grade => calculated percentage grade
270 nmanual => number of manually graded questions
271 manualpoints => point value for manually graded questions }
4b55d2af 272 */
86342d63 273function lesson_grade($lesson, $ntries, $userid = 0) {
646fc290 274 global $USER, $DB;
ac8e16be 275
88427c07 276 if (empty($userid)) {
277 $userid = $USER->id;
278 }
86342d63 279
88427c07 280 // Zero out everything
281 $ncorrect = 0;
282 $nviewed = 0;
283 $score = 0;
284 $nmanual = 0;
285 $manualpoints = 0;
286 $thegrade = 0;
287 $nquestions = 0;
288 $total = 0;
289 $earned = 0;
290
646fc290 291 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
86342d63 292 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
646fc290 293 userid = :userid AND retry = :retry", $params, "timeseen")) {
88427c07 294 // group each try with its page
295 $attemptset = array();
296 foreach ($useranswers as $useranswer) {
86342d63 297 $attemptset[$useranswer->pageid][] = $useranswer;
ac8e16be 298 }
86342d63 299
88427c07 300 // Drop all attempts that go beyond max attempts for the lesson
301 foreach ($attemptset as $key => $set) {
302 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
303 }
86342d63 304
88427c07 305 // get only the pages and their answers that the user answered
646fc290 306 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
0a4abb73
SH
307 array_unshift($parameters, $lesson->id);
308 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
309 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
86342d63 310
88427c07 311 // Number of pages answered
312 $nquestions = count($pages);
313
314 foreach ($attemptset as $attempts) {
0a4abb73 315 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
88427c07 316 if ($lesson->custom) {
317 $attempt = end($attempts);
318 // If essay question, handle it, otherwise add to score
0a4abb73
SH
319 if ($page->requires_manual_grading()) {
320 $earned += $page->earned_score($answers, $attempt);
88427c07 321 $nmanual++;
322 $manualpoints += $answers[$attempt->answerid]->score;
ab1e7c39 323 } else if (!empty($attempt->answerid)) {
0a4abb73 324 $earned += $page->earned_score($answers, $attempt);
88427c07 325 }
326 } else {
327 foreach ($attempts as $attempt) {
328 $earned += $attempt->correct;
329 }
330 $attempt = end($attempts); // doesn't matter which one
331 // If essay question, increase numbers
0a4abb73 332 if ($page->requires_manual_grading()) {
88427c07 333 $nmanual++;
334 $manualpoints++;
ac8e16be 335 }
336 }
88427c07 337 // Number of times answered
338 $nviewed += count($attempts);
339 }
86342d63 340
88427c07 341 if ($lesson->custom) {
ac8e16be 342 $bestscores = array();
88427c07 343 // Find the highest possible score per page to get our total
344 foreach ($answers as $answer) {
46341ab7 345 if(!isset($bestscores[$answer->pageid])) {
88427c07 346 $bestscores[$answer->pageid] = $answer->score;
46341ab7 347 } else if ($bestscores[$answer->pageid] < $answer->score) {
88427c07 348 $bestscores[$answer->pageid] = $answer->score;
ac8e16be 349 }
350 }
88427c07 351 $total = array_sum($bestscores);
352 } else {
353 // Check to make sure the student has answered the minimum questions
354 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
355 // Nope, increase number viewed by the amount of unanswered questions
356 $total = $nviewed + ($lesson->minquestions - $nquestions);
357 } else {
358 $total = $nviewed;
359 }
ac8e16be 360 }
88427c07 361 }
86342d63 362
88427c07 363 if ($total) { // not zero
364 $thegrade = round(100 * $earned / $total, 5);
365 }
86342d63 366
88427c07 367 // Build the grade information object
368 $gradeinfo = new stdClass;
369 $gradeinfo->nquestions = $nquestions;
370 $gradeinfo->attempts = $nviewed;
371 $gradeinfo->total = $total;
372 $gradeinfo->earned = $earned;
373 $gradeinfo->grade = $thegrade;
374 $gradeinfo->nmanual = $nmanual;
375 $gradeinfo->manualpoints = $manualpoints;
86342d63 376
88427c07 377 return $gradeinfo;
378}
379
62eda6ea 380/**
381 * Determines if a user can view the left menu. The determining factor
382 * is whether a user has a grade greater than or equal to the lesson setting
383 * of displayleftif
384 *
385 * @param object $lesson Lesson object of the current lesson
386 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
62eda6ea 387 **/
388function lesson_displayleftif($lesson) {
646fc290 389 global $CFG, $USER, $DB;
86342d63 390
62eda6ea 391 if (!empty($lesson->displayleftif)) {
392 // get the current user's max grade for this lesson
646fc290 393 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
394 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)) {
62eda6ea 395 if ($maxgrade->maxgrade < $lesson->displayleftif) {
396 return 0; // turn off the displayleft
397 }
398 } else {
399 return 0; // no grades
400 }
401 }
86342d63 402
62eda6ea 403 // if we get to here, keep the original state of displayleft lesson setting
404 return $lesson->displayleft;
405}
5e7856af 406
4262a2f8 407/**
86342d63 408 *
4262a2f8 409 * @param $cm
410 * @param $lesson
411 * @param $page
412 * @return unknown_type
413 */
d9c26e21 414function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
4262a2f8 415 $bc = lesson_menu_block_contents($cm->id, $lesson);
416 if (!empty($bc)) {
417 $regions = $page->blocks->get_regions();
418 $firstregion = reset($regions);
d9c26e21 419 $page->blocks->add_fake_block($bc, $firstregion);
4262a2f8 420 }
421
422 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
423 if (!empty($bc)) {
d9c26e21 424 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
4262a2f8 425 }
426
427 if (!empty($timer)) {
428 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
429 if (!empty($bc)) {
d9c26e21 430 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
4262a2f8 431 }
432 }
433}
434
f521f98a 435/**
86342d63 436 * If there is a media file associated with this
4262a2f8 437 * lesson, return a block_contents that displays it.
f521f98a 438 *
439 * @param int $cmid Course Module ID for this lesson
440 * @param object $lesson Full lesson record object
4262a2f8 441 * @return block_contents
f521f98a 442 **/
4262a2f8 443function lesson_mediafile_block_contents($cmid, $lesson) {
d68ccdba 444 global $OUTPUT;
8d1a3963 445 if (empty($lesson->mediafile)) {
4262a2f8 446 return null;
f521f98a 447 }
4262a2f8 448
0a4abb73
SH
449 $options = array();
450 $options['menubar'] = 0;
451 $options['location'] = 0;
452 $options['left'] = 5;
453 $options['top'] = 5;
454 $options['scrollbars'] = 1;
455 $options['resizable'] = 1;
456 $options['width'] = $lesson->mediawidth;
457 $options['height'] = $lesson->mediaheight;
4262a2f8 458
9bf16314
PS
459 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
460 $action = new popup_action('click', $link, 'lessonmediafile', $options);
461 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
86342d63 462
4262a2f8 463 $bc = new block_contents();
464 $bc->title = get_string('linkedmedia', 'lesson');
0235e247 465 $bc->attributes['class'] = 'mediafile';
4262a2f8 466 $bc->content = $content;
467
468 return $bc;
f521f98a 469}
470
471/**
472 * If a timed lesson and not a teacher, then
4262a2f8 473 * return a block_contents containing the clock.
f521f98a 474 *
475 * @param int $cmid Course Module ID for this lesson
476 * @param object $lesson Full lesson record object
477 * @param object $timer Full timer record object
4262a2f8 478 * @return block_contents
f521f98a 479 **/
4262a2f8 480function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
481 // Display for timed lessons and for students only
f521f98a 482 $context = get_context_instance(CONTEXT_MODULE, $cmid);
4262a2f8 483 if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) {
484 return null;
485 }
f521f98a 486
4262a2f8 487 $content = '<div class="jshidewhenenabled">';
0a4abb73 488 $content .= $lesson->time_remaining($timer->starttime);
4262a2f8 489 $content .= '</div>';
ba458143 490
4262a2f8 491 $clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
227255b8
PS
492 $page->requires->data_for_js('clocksettings', $clocksettings);
493 $page->requires->js('/mod/lesson/timer.js');
494 $page->requires->js_function_call('show_clock');
ba458143 495
4262a2f8 496 $bc = new block_contents();
497 $bc->title = get_string('timeremaining', 'lesson');
6605ff8c 498 $bc->attributes['class'] = 'clock block';
4262a2f8 499 $bc->content = $content;
500
501 return $bc;
f521f98a 502}
503
504/**
505 * If left menu is turned on, then this will
506 * print the menu in a block
507 *
508 * @param int $cmid Course Module ID for this lesson
0a4abb73 509 * @param lesson $lesson Full lesson record object
f521f98a 510 * @return void
511 **/
4262a2f8 512function lesson_menu_block_contents($cmid, $lesson) {
646fc290 513 global $CFG, $DB;
f521f98a 514
4262a2f8 515 if (!$lesson->displayleft) {
516 return null;
517 }
f521f98a 518
0a4abb73
SH
519 $pages = $lesson->load_all_pages();
520 foreach ($pages as $page) {
521 if ((int)$page->prevpageid === 0) {
522 $pageid = $page->id;
523 break;
524 }
525 }
4262a2f8 526 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
f521f98a 527
4262a2f8 528 if (!$pageid || !$pages) {
529 return null;
f521f98a 530 }
f521f98a 531
4262a2f8 532 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
888f0c54 533
4262a2f8 534 while ($pageid != 0) {
535 $page = $pages[$pageid];
536
537 // Only process branch tables with display turned on
0a4abb73 538 if ($page->displayinmenublock && $page->display) {
86342d63 539 if ($page->id == $currentpageid) {
4262a2f8 540 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
541 } else {
542 $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";
543 }
86342d63 544
888f0c54 545 }
4262a2f8 546 $pageid = $page->nextpageid;
888f0c54 547 }
4262a2f8 548 $content .= "</ul>\n</div>\n";
888f0c54 549
4262a2f8 550 $bc = new block_contents();
551 $bc->title = get_string('lessonmenu', 'lesson');
6605ff8c 552 $bc->attributes['class'] = 'menu block';
4262a2f8 553 $bc->content = $content;
888f0c54 554
4262a2f8 555 return $bc;
448052a5
SH
556}
557
558/**
559 * Adds header buttons to the page for the lesson
560 *
561 * @param object $cm
562 * @param object $context
563 * @param bool $extraeditbuttons
564 * @param int $lessonpageid
565 */
566function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
567 global $CFG, $PAGE, $OUTPUT;
92059c7e
SH
568 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
569 if ($lessonpageid === null) {
570 print_error('invalidpageid', 'lesson');
571 }
572 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
52b2f0ba 573 $url = new moodle_url('/mod/lesson/editpage.php', array('id'=>$cm->id, 'pageid'=>$lessonpageid, 'edit'=>1));
5c2ed7e2 574 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
448052a5 575 }
448052a5 576 }
5c2ed7e2 577}
9b56a34f
PS
578
579/**
580 * This is a function used to detect media types and generate html code.
581 *
582 * @global object $CFG
583 * @global object $PAGE
584 * @param object $lesson
585 * @param object $context
586 * @return string $code the html code of media
587 */
588function lesson_get_media_html($lesson, $context) {
589 global $CFG, $PAGE, $OUTPUT;
590 require_once("$CFG->libdir/resourcelib.php");
591
64f93798 592 // get the media file link
8d1a3963
PS
593 if (strpos($lesson->mediafile, '://') !== false) {
594 $url = new moodle_url($lesson->mediafile);
595 } else {
596 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
597 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
598 }
9b56a34f
PS
599 $title = $lesson->mediafile;
600
8d1a3963 601 $clicktoopen = html_writer::link($url, get_string('download'));
9b56a34f
PS
602
603 $mimetype = resourcelib_guess_url_mimetype($url);
604
605 // find the correct type and print it out
606 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
607 $code = resourcelib_embed_image($url, $title);
608
609 } else if ($mimetype == 'audio/mp3') {
610 // MP3 audio file
611 $code = resourcelib_embed_mp3($url, $title, $clicktoopen);
612
613 } else if ($mimetype == 'video/x-flv') {
614 // Flash video file
615 $code = resourcelib_embed_flashvideo($url, $title, $clicktoopen);
616
617 } else if ($mimetype == 'application/x-shockwave-flash') {
618 // Flash file
619 $code = resourcelib_embed_flash($url, $title, $clicktoopen);
620
621 } else if (substr($mimetype, 0, 10) == 'video/x-ms') {
622 // Windows Media Player file
623 $code = resourcelib_embed_mediaplayer($url, $title, $clicktoopen);
624
625 } else if ($mimetype == 'video/quicktime') {
626 // Quicktime file
627 $code = resourcelib_embed_quicktime($url, $title, $clicktoopen);
628
629 } else if ($mimetype == 'video/mpeg') {
630 // Mpeg file
631 $code = resourcelib_embed_mpeg($url, $title, $clicktoopen);
632
633 } else if ($mimetype == 'audio/x-pn-realaudio-plugin') {
634 // RealMedia file
635 $code = resourcelib_embed_real($url, $title, $clicktoopen);
636
637 } else {
638 // anything else - just try object tag enlarged as much as possible
639 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
640 }
641
642 return $code;
643}
1e7f8ea2
PS
644
645
646/**
647 * Abstract class that page type's MUST inherit from.
648 *
649 * This is the abstract class that ALL add page type forms must extend.
650 * You will notice that all but two of the methods this class contains are final.
651 * Essentially the only thing that extending classes can do is extend custom_definition.
652 * OR if it has a special requirement on creation it can extend construction_override
653 *
654 * @abstract
cc3dbaaa
PS
655 * @copyright 2009 Sam Hemelryk
656 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
657 */
658abstract class lesson_add_page_form_base extends moodleform {
659
660 /**
661 * This is the classic define that is used to identify this pagetype.
662 * Will be one of LESSON_*
663 * @var int
664 */
665 public $qtype;
666
667 /**
668 * The simple string that describes the page type e.g. truefalse, multichoice
669 * @var string
670 */
671 public $qtypestring;
672
673 /**
674 * An array of options used in the htmleditor
675 * @var array
676 */
677 protected $editoroptions = array();
678
679 /**
680 * True if this is a standard page of false if it does something special.
681 * Questions are standard pages, branch tables are not
682 * @var bool
683 */
684 protected $standard = true;
685
686 /**
687 * Each page type can and should override this to add any custom elements to
688 * the basic form that they want
689 */
690 public function custom_definition() {}
691
692 /**
693 * Used to determine if this is a standard page or a special page
694 * @return bool
695 */
696 public final function is_standard() {
697 return (bool)$this->standard;
698 }
699
700 /**
701 * Add the required basic elements to the form.
702 *
703 * This method adds the basic elements to the form including title and contents
704 * and then calls custom_definition();
705 */
706 public final function definition() {
707 $mform = $this->_form;
708 $editoroptions = $this->_customdata['editoroptions'];
709
710 $mform->addElement('header', 'qtypeheading', get_string('addaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
711
712 $mform->addElement('hidden', 'id');
713 $mform->setType('id', PARAM_INT);
714
715 $mform->addElement('hidden', 'pageid');
716 $mform->setType('pageid', PARAM_INT);
717
718 if ($this->standard === true) {
719 $mform->addElement('hidden', 'qtype');
3fa2f030 720 $mform->setType('qtype', PARAM_SAFEDIR);
1e7f8ea2 721
3fa2f030 722 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1e7f8ea2 723 $mform->setType('title', PARAM_TEXT);
3fa2f030
PS
724 $mform->addRule('title', get_string('required'), 'required', null, 'client');
725
1e7f8ea2 726 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
3fa2f030
PS
727 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
728 $mform->setType('contents_editor', PARAM_RAW);
729 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1e7f8ea2
PS
730 }
731
732 $this->custom_definition();
733
734 if ($this->_customdata['edit'] === true) {
735 $mform->addElement('hidden', 'edit', 1);
3fa2f030 736 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1e7f8ea2 737 } else {
3fa2f030 738 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1e7f8ea2
PS
739 }
740 }
741
742 /**
743 * Convenience function: Adds a jumpto select element
744 *
745 * @param string $name
746 * @param string|null $label
747 * @param int $selected The page to select by default
748 */
749 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
750 $title = get_string("jump", "lesson");
751 if ($label === null) {
752 $label = $title;
753 }
754 if (is_int($name)) {
755 $name = "jumpto[$name]";
756 }
757 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
758 $this->_form->setDefault($name, $selected);
759 $this->_form->addHelpButton($name, 'jumps', 'lesson');
760 }
761
762 /**
763 * Convenience function: Adds a score input element
764 *
765 * @param string $name
766 * @param string|null $label
767 * @param mixed $value The default value
768 */
769 protected final function add_score($name, $label=null, $value=null) {
770 if ($label === null) {
771 $label = get_string("score", "lesson");
772 }
773 if (is_int($name)) {
774 $name = "score[$name]";
775 }
776 $this->_form->addElement('text', $name, $label, array('size'=>5));
777 if ($value !== null) {
778 $this->_form->setDefault($name, $value);
779 }
780 }
781
782 /**
783 * Convenience function: Adds an answer editor
784 *
785 * @param int $count The count of the element to add
a675ada5
PS
786 * @param string $label, NULL means default
787 * @param bool $required
788 * @return void
1e7f8ea2 789 */
a675ada5
PS
790 protected final function add_answer($count, $label = NULL, $required = false) {
791 if ($label === NULL) {
792 $label = get_string('answer', 'lesson');
793 }
cb2c1963 794 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
1e7f8ea2 795 $this->_form->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
a675ada5
PS
796 if ($required) {
797 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
798 }
1e7f8ea2
PS
799 }
800 /**
801 * Convenience function: Adds an response editor
802 *
803 * @param int $count The count of the element to add
a675ada5
PS
804 * @param string $label, NULL means default
805 * @param bool $required
806 * @return void
1e7f8ea2 807 */
a675ada5
PS
808 protected final function add_response($count, $label = NULL, $required = false) {
809 if ($label === NULL) {
810 $label = get_string('response', 'lesson');
811 }
cb2c1963 812 $this->_form->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
1e7f8ea2 813 $this->_form->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
a675ada5
PS
814 if ($required) {
815 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
816 }
1e7f8ea2
PS
817 }
818
819 /**
820 * A function that gets called upon init of this object by the calling script.
821 *
822 * This can be used to process an immediate action if required. Currently it
823 * is only used in special cases by non-standard page types.
824 *
825 * @return bool
826 */
827 public function construction_override() {
828 return true;
829 }
830}
831
832
833
834/**
835 * Class representation of a lesson
836 *
837 * This class is used the interact with, and manage a lesson once instantiated.
838 * If you need to fetch a lesson object you can do so by calling
839 *
840 * <code>
841 * lesson::load($lessonid);
842 * // or
843 * $lessonrecord = $DB->get_record('lesson', $lessonid);
844 * $lesson = new lesson($lessonrecord);
845 * </code>
846 *
847 * The class itself extends lesson_base as all classes within the lesson module should
848 *
849 * These properties are from the database
850 * @property int $id The id of this lesson
851 * @property int $course The ID of the course this lesson belongs to
852 * @property string $name The name of this lesson
853 * @property int $practice Flag to toggle this as a practice lesson
854 * @property int $modattempts Toggle to allow the user to go back and review answers
855 * @property int $usepassword Toggle the use of a password for entry
856 * @property string $password The password to require users to enter
ff85f902 857 * @property int $dependency ID of another lesson this lesson is dependent on
1e7f8ea2
PS
858 * @property string $conditions Conditions of the lesson dependency
859 * @property int $grade The maximum grade a user can achieve (%)
860 * @property int $custom Toggle custom scoring on or off
861 * @property int $ongoing Toggle display of an ongoing score
862 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
863 * @property int $maxanswers The max number of answers or branches
864 * @property int $maxattempts The maximum number of attempts a user can record
865 * @property int $review Toggle use or wrong answer review button
866 * @property int $nextpagedefault Override the default next page
867 * @property int $feedback Toggles display of default feedback
868 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
869 * @property int $maxpages Maximum number of pages this lesson can contain
870 * @property int $retake Flag to allow users to retake a lesson
871 * @property int $activitylink Relate this lesson to another lesson
872 * @property string $mediafile File to pop up to or webpage to display
873 * @property int $mediaheight Sets the height of the media file popup
874 * @property int $mediawidth Sets the width of the media file popup
875 * @property int $mediaclose Toggle display of a media close button
876 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
877 * @property int $width Width of slideshow
878 * @property int $height Height of slideshow
879 * @property string $bgcolor Background colour of slideshow
ff85f902 880 * @property int $displayleft Display a left menu
1e7f8ea2
PS
881 * @property int $displayleftif Sets the condition on which the left menu is displayed
882 * @property int $progressbar Flag to toggle display of a lesson progress bar
883 * @property int $highscores Flag to toggle collection of high scores
884 * @property int $maxhighscores Number of high scores to limit to
885 * @property int $available Timestamp of when this lesson becomes available
886 * @property int $deadline Timestamp of when this lesson is no longer available
887 * @property int $timemodified Timestamp when lesson was last modified
888 *
889 * These properties are calculated
890 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
891 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
892 *
cc3dbaaa
PS
893 * @copyright 2009 Sam Hemelryk
894 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
895 */
896class lesson extends lesson_base {
897
898 /**
899 * The id of the first page (where prevpageid = 0) gets set and retrieved by
900 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
901 * @var int
902 */
903 protected $firstpageid = null;
904 /**
905 * The id of the last page (where nextpageid = 0) gets set and retrieved by
906 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
907 * @var int
908 */
909 protected $lastpageid = null;
910 /**
911 * An array used to cache the pages associated with this lesson after the first
912 * time they have been loaded.
913 * A note to developers: If you are going to be working with MORE than one or
914 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
915 * in order to save excess database queries.
916 * @var array An array of lesson_page objects
917 */
918 protected $pages = array();
919 /**
920 * Flag that gets set to true once all of the pages associated with the lesson
921 * have been loaded.
922 * @var bool
923 */
924 protected $loadedallpages = false;
925
926 /**
927 * Simply generates a lesson object given an array/object of properties
928 * Overrides {@see lesson_base->create()}
929 * @static
930 * @param object|array $properties
931 * @return lesson
932 */
933 public static function create($properties) {
934 return new lesson($properties);
935 }
936
937 /**
938 * Generates a lesson object from the database given its id
939 * @static
940 * @param int $lessonid
941 * @return lesson
942 */
943 public static function load($lessonid) {
3983f2dc
PS
944 global $DB;
945
1e7f8ea2
PS
946 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
947 print_error('invalidcoursemodule');
948 }
949 return new lesson($lesson);
950 }
951
952 /**
953 * Deletes this lesson from the database
954 */
955 public function delete() {
956 global $CFG, $DB;
957 require_once($CFG->libdir.'/gradelib.php');
958 require_once($CFG->dirroot.'/calendar/lib.php');
959
960 $DB->delete_records("lesson", array("id"=>$this->properties->id));;
961 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
962 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
963 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
964 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
965 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
966 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
967 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
968 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
969 foreach($events as $event) {
970 $event = calendar_event::load($event);
971 $event->delete();
972 }
973 }
974
975 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, NULL, array('deleted'=>1));
976 return true;
977 }
978
979 /**
980 * Fetches messages from the session that may have been set in previous page
981 * actions.
982 *
983 * <code>
984 * // Do not call this method directly instead use
985 * $lesson->messages;
986 * </code>
987 *
988 * @return array
989 */
990 protected function get_messages() {
991 global $SESSION;
992
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]);
997 }
998
999 return $messages;
1000 }
1001
1002 /**
1003 * Get all of the attempts for the current user.
1004 *
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
1010 */
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;
1016 }
1017 if ($pageid !== null) {
1018 $params['pageid'] = $pageid;
1019 }
1020 if ($userid === null) {
1021 $params['userid'] = $USER->id;
1022 }
ef4ba975 1023 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1e7f8ea2
PS
1024 }
1025
1026 /**
1027 * Returns the first page for the lesson or false if there isn't one.
1028 *
1029 * This method should be called via the magic method __get();
1030 * <code>
1031 * $firstpage = $lesson->firstpage;
1032 * </code>
1033 *
1034 * @return lesson_page|bool Returns the lesson_page specialised object or false
1035 */
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;
1042 }
1043 }
1044 }
1045 return false;
1046 }
1047
1048 /**
1049 * Returns the last page for the lesson or false if there isn't one.
1050 *
1051 * This method should be called via the magic method __get();
1052 * <code>
1053 * $lastpage = $lesson->lastpage;
1054 * </code>
1055 *
1056 * @return lesson_page|bool Returns the lesson_page specialised object or false
1057 */
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;
1064 }
1065 }
1066 }
1067 return false;
1068 }
1069
1070 /**
1071 * Returns the id of the first page of this lesson. (prevpageid = 0)
1072 * @return int
1073 */
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');
1081 }
1082 $this->firstpageid = $firstpageid;
1083 } else {
1084 $firstpage = $this->get_firstpage();
1085 $this->firstpageid = $firstpage->id;
1086 }
1087 }
1088 return $this->firstpageid;
1089 }
1090
1091 /**
1092 * Returns the id of the last page of this lesson. (nextpageid = 0)
1093 * @return int
1094 */
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');
1102 }
1103 $this->lastpageid = $lastpageid;
1104 } else {
1105 $lastpageid = $this->get_lastpage();
1106 $this->lastpageid = $lastpageid->id;
1107 }
1108 }
1109
1110 return $this->lastpageid;
1111 }
1112
1113 /**
1114 * Gets the next page to display after the one that is provided.
1115 * @param int $nextpageid
1116 * @return bool
1117 */
1118 public function get_next_page($nextpageid) {
3983f2dc 1119 global $USER, $DB;
1e7f8ea2
PS
1120 $allpages = $this->load_all_pages();
1121 if ($this->properties->nextpagedefault) {
1122 // in Flash Card mode...first get number of retakes
b0ee1802 1123 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$USER->id));
1e7f8ea2
PS
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;
1131 }
1132 }
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;
1138 }
1139 }
1140 }
1141 if ($found) {
1142 if ($this->properties->maxpages) {
1143 // check number of pages viewed (in the lesson)
1e7f8ea2
PS
1144 if ($DB->count_records("lesson_attempts", array("lessonid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes)) >= $this->properties->maxpages) {
1145 return false;
1146 }
1147 }
1148 return $nextpage;
1149 }
1150 }
1151 // In a normal lesson mode
1152 foreach ($allpages as $nextpage) {
1153 if ((int)$nextpage->id===(int)$nextpageid) {
1154 return $nextpage;
1155 }
1156 }
1157 return false;
1158 }
1159
1160 /**
1161 * Sets a message against the session for this lesson that will displayed next
1162 * time the lesson processes messages
1163 *
1164 * @param string $message
1165 * @param string $class
1166 * @param string $align
1167 * @return bool
1168 */
1169 public function add_message($message, $class="notifyproblem", $align='center') {
1170 global $SESSION;
1171
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();
1177 }
1178
1179 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1180
1181 return true;
1182 }
1183
1184 /**
1185 * Check if the lesson is accessible at the present time
1186 * @return bool True if the lesson is accessible, false otherwise
1187 */
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));
1192 }
1193
1194 /**
1195 * Starts the lesson time for the current user
1196 * @return bool Returns true
1197 */
1198 public function start_timer() {
1199 global $USER, $DB;
1200 $USER->startlesson[$this->properties->id] = true;
1201 $startlesson = new stdClass;
1202 $startlesson->lessonid = $this->properties->id;
1203 $startlesson->userid = $USER->id;
1204 $startlesson->starttime = time();
1205 $startlesson->lessontime = time();
1206 $DB->insert_record('lesson_timer', $startlesson);
1207 if ($this->properties->timed) {
1208 $this->add_message(get_string('maxtimewarning', 'lesson', $this->properties->maxtime), 'center');
1209 }
1210 return true;
1211 }
1212
1213 /**
1214 * Updates the timer to the current time and returns the new timer object
1215 * @param bool $restart If set to true the timer is restarted
1216 * @param bool $continue If set to true AND $restart=true then the timer
1217 * will continue from a previous attempt
1218 * @return stdClass The new timer
1219 */
1220 public function update_timer($restart=false, $continue=false) {
1221 global $USER, $DB;
1222 // clock code
1223 // get time information for this user
1224 if (!$timer = $DB->get_records('lesson_timer', array ("lessonid" => $this->properties->id, "userid" => $USER->id), 'starttime DESC', '*', 0, 1)) {
1225 print_error('cannotfindtimer', 'lesson');
1226 } else {
1227 $timer = current($timer); // this will get the latest start time record
1228 }
1229
1230 if ($restart) {
1231 if ($continue) {
1232 // continue a previous test, need to update the clock (think this option is disabled atm)
1233 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1234 } else {
1235 // starting over, so reset the clock
1236 $timer->starttime = time();
1237 }
1238 }
1239
1240 $timer->lessontime = time();
1241 $DB->update_record('lesson_timer', $timer);
1242 return $timer;
1243 }
1244
1245 /**
1246 * Updates the timer to the current time then stops it by unsetting the user var
1247 * @return bool Returns true
1248 */
1249 public function stop_timer() {
1250 global $USER, $DB;
1251 unset($USER->startlesson[$this->properties->id]);
1252 return $this->update_timer(false, false);
1253 }
1254
1255 /**
1256 * Checks to see if the lesson has pages
1257 */
1258 public function has_pages() {
1259 global $DB;
1260 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1261 return ($pagecount>0);
1262 }
1263
1264 /**
1265 * Returns the link for the related activity
1266 * @return array|false
1267 */
1268 public function link_for_activitylink() {
1269 global $DB;
1270 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1271 if ($module) {
1272 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1273 if ($modname) {
1274 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1275 if ($instancename) {
1276 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1277 get_string('returnto', 'lesson', get_string('activitylinkname', 'lesson', $instancename)),
1278 array('class'=>'centerpadded lessonbutton standardbutton'));
1279 }
1280 }
1281 }
1282 return '';
1283 }
1284
1285 /**
1286 * Loads the requested page.
1287 *
1288 * This function will return the requested page id as either a specialised
1289 * lesson_page object OR as a generic lesson_page.
1290 * If the page has been loaded previously it will be returned from the pages
1291 * array, otherwise it will be loaded from the database first
1292 *
1293 * @param int $pageid
1294 * @return lesson_page A lesson_page object or an object that extends it
1295 */
1296 public function load_page($pageid) {
1297 if (!array_key_exists($pageid, $this->pages)) {
1298 $manager = lesson_page_type_manager::get($this);
1299 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1300 }
1301 return $this->pages[$pageid];
1302 }
1303
1304 /**
1305 * Loads ALL of the pages for this lesson
1306 *
1307 * @return array An array containing all pages from this lesson
1308 */
1309 public function load_all_pages() {
1310 if (!$this->loadedallpages) {
1311 $manager = lesson_page_type_manager::get($this);
1312 $this->pages = $manager->load_all_pages($this);
1313 $this->loadedallpages = true;
1314 }
1315 return $this->pages;
1316 }
1317
1318 /**
ff85f902 1319 * Determines if a jumpto value is correct or not.
1e7f8ea2
PS
1320 *
1321 * returns true if jumpto page is (logically) after the pageid page or
1322 * if the jumpto value is a special value. Returns false in all other cases.
1323 *
1324 * @param int $pageid Id of the page from which you are jumping from.
1325 * @param int $jumpto The jumpto number.
1326 * @return boolean True or false after a series of tests.
1327 **/
1328 public function jumpto_is_correct($pageid, $jumpto) {
1329 global $DB;
1330
1331 // first test the special values
1332 if (!$jumpto) {
1333 // same page
1334 return false;
1335 } elseif ($jumpto == LESSON_NEXTPAGE) {
1336 return true;
1337 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1338 return true;
1339 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1340 return true;
1341 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1342 return true;
1343 } elseif ($jumpto == LESSON_EOL) {
1344 return true;
1345 }
1346
1347 $pages = $this->load_all_pages();
1348 $apageid = $pages[$pageid]->nextpageid;
1349 while ($apageid != 0) {
1350 if ($jumpto == $apageid) {
1351 return true;
1352 }
1353 $apageid = $pages[$apageid]->nextpageid;
1354 }
1355 return false;
1356 }
1357
1358 /**
1359 * Returns the time a user has remaining on this lesson
1360 * @param int $starttime Starttime timestamp
1361 * @return string
1362 */
1363 public function time_remaining($starttime) {
1364 $timeleft = $starttime + $this->maxtime * 60 - time();
1365 $hours = floor($timeleft/3600);
1366 $timeleft = $timeleft - ($hours * 3600);
1367 $minutes = floor($timeleft/60);
1368 $secs = $timeleft - ($minutes * 60);
1369
1370 if ($minutes < 10) {
1371 $minutes = "0$minutes";
1372 }
1373 if ($secs < 10) {
1374 $secs = "0$secs";
1375 }
1376 $output = array();
1377 $output[] = $hours;
1378 $output[] = $minutes;
1379 $output[] = $secs;
1380 $output = implode(':', $output);
1381 return $output;
1382 }
1383
1384 /**
1385 * Interprets LESSON_CLUSTERJUMP jumpto value.
1386 *
1387 * This will select a page randomly
ff85f902 1388 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1e7f8ea2
PS
1389 * and the page selected will be a page that has not been viewed already
1390 * and if any pages are within a branch table or end of branch then only 1 page within
1391 * the branch table or end of branch will be randomly selected (sub clustering).
1392 *
1393 * @param int $pageid Id of the current page from which we are jumping from.
1394 * @param int $userid Id of the user.
1395 * @return int The id of the next page.
1396 **/
1397 public function cluster_jump($pageid, $userid=null) {
1398 global $DB, $USER;
1399
1400 if ($userid===null) {
1401 $userid = $USER->id;
1402 }
1403 // get the number of retakes
1404 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1405 $retakes = 0;
1406 }
1407 // get all the lesson_attempts aka what the user has seen
1408 $seenpages = array();
1409 if ($attempts = $this->get_attempts($retakes)) {
1410 foreach ($attempts as $attempt) {
1411 $seenpages[$attempt->pageid] = $attempt->pageid;
1412 }
1413
1414 }
1415
1416 // get the lesson pages
1417 $lessonpages = $this->load_all_pages();
1418 // find the start of the cluster
1419 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1420 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1421 break;
1422 }
1423 $pageid = $lessonpages[$pageid]->prevpageid;
1424 }
1425
1426 $clusterpages = array();
1427 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1428 $unseen = array();
1429 foreach ($clusterpages as $key=>$cluster) {
1430 if ($cluster->type !== lesson_page::TYPE_QUESTION) {
1431 unset($clusterpages[$key]);
1432 } elseif ($cluster->is_unseen($seenpages)) {
1433 $unseen[] = $cluster;
1434 }
1435 }
1436
1437 if (count($unseen) > 0) {
1438 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1439 $nextpage = $unseen[rand(0, count($unseen)-1)];
1440 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1441 // if branch table, then pick a random page inside of it
1442 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1443 return $branchpages[rand(0, count($branchpages)-1)]->id;
1444 } else { // otherwise, return the page's id
1445 return $nextpage->id;
1446 }
1447 } else {
1448 // seen all there is to see, leave the cluster
1449 if (end($clusterpages)->nextpageid == 0) {
1450 return LESSON_EOL;
1451 } else {
1452 $clusterendid = $pageid;
1453 while ($clusterendid != 0) { // this condition should not be satisfied... should be a cluster page
1454 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_CLUSTER) {
1455 break;
1456 }
1457 $clusterendid = $lessonpages[$clusterendid]->prevpageid;
1458 }
1459 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1460 if ($exitjump == LESSON_NEXTPAGE) {
1461 $exitjump = $lessonpages[$pageid]->nextpageid;
1462 }
1463 if ($exitjump == 0) {
1464 return LESSON_EOL;
1465 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1466 return $exitjump;
1467 } else {
1468 if (!array_key_exists($exitjump, $lessonpages)) {
1469 $found = false;
1470 foreach ($lessonpages as $page) {
1471 if ($page->id === $clusterendid) {
1472 $found = true;
1473 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1474 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1475 break;
1476 }
1477 }
1478 }
1479 if (!array_key_exists($exitjump, $lessonpages)) {
1480 return LESSON_EOL;
1481 }
1482 return $exitjump;
1483 }
1484 }
1485 }
1486 }
1487
1488 /**
1489 * Finds all pages that appear to be a subtype of the provided pageid until
1490 * an end point specified within $ends is encountered or no more pages exist
1491 *
1492 * @param int $pageid
1493 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1494 * the subtype
1495 * @return array An array of specialised lesson_page objects
1496 */
1497 public function get_sub_pages_of($pageid, array $ends) {
1498 $lessonpages = $this->load_all_pages();
1499 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1500 $pages = array();
1501
1502 while (true) {
1503 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1504 break;
1505 }
1506 $pages[] = $lessonpages[$pageid];
1507 $pageid = $lessonpages[$pageid]->nextpageid;
1508 }
1509
1510 return $pages;
1511 }
1512
1513 /**
1514 * Checks to see if the specified page[id] is a subpage of a type specified in
1515 * the $types array, until either there are no more pages of we find a type
ff85f902 1516 * corresponding to that of a type specified in $ends
1e7f8ea2
PS
1517 *
1518 * @param int $pageid The id of the page to check
1519 * @param array $types An array of types that would signify this page was a subpage
1520 * @param array $ends An array of types that mean this is not a subpage
1521 * @return bool
1522 */
1523 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1524 $pages = $this->load_all_pages();
1525 $pageid = $pages[$pageid]->prevpageid; // move up one
1526
1527 array_unshift($ends, 0);
1528 // go up the pages till branch table
1529 while (true) {
1530 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1531 return false;
1532 } else if (in_array($pages[$pageid]->qtype, $types)) {
1533 return true;
1534 }
1535 $pageid = $pages[$pageid]->prevpageid;
1536 }
1537 }
1538}
1539
1540
1541/**
1542 * Abstract class to provide a core functions to the all lesson classes
1543 *
1544 * This class should be abstracted by ALL classes with the lesson module to ensure
1545 * that all classes within this module can be interacted with in the same way.
1546 *
1547 * This class provides the user with a basic properties array that can be fetched
ff85f902 1548 * or set via magic methods, or alternatively by defining methods get_blah() or
1e7f8ea2
PS
1549 * set_blah() within the extending object.
1550 *
cc3dbaaa
PS
1551 * @copyright 2009 Sam Hemelryk
1552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
1553 */
1554abstract class lesson_base {
1555
1556 /**
1557 * An object containing properties
1558 * @var stdClass
1559 */
1560 protected $properties;
1561
1562 /**
1563 * The constructor
1564 * @param stdClass $properties
1565 */
1566 public function __construct($properties) {
1567 $this->properties = (object)$properties;
1568 }
1569
1570 /**
1571 * Magic property method
1572 *
1573 * Attempts to call a set_$key method if one exists otherwise falls back
1574 * to simply set the property
1575 *
1576 * @param string $key
1577 * @param mixed $value
1578 */
1579 public function __set($key, $value) {
1580 if (method_exists($this, 'set_'.$key)) {
1581 $this->{'set_'.$key}($value);
1582 }
1583 $this->properties->{$key} = $value;
1584 }
1585
1586 /**
1587 * Magic get method
1588 *
1589 * Attempts to call a get_$key method to return the property and ralls over
1590 * to return the raw property
1591 *
1592 * @param str $key
1593 * @return mixed
1594 */
1595 public function __get($key) {
1596 if (method_exists($this, 'get_'.$key)) {
1597 return $this->{'get_'.$key}();
1598 }
1599 return $this->properties->{$key};
1600 }
1601
1602 /**
1603 * Stupid PHP needs an isset magic method if you use the get magic method and
1604 * still want empty calls to work.... blah ~!
1605 *
1606 * @param string $key
1607 * @return bool
1608 */
1609 public function __isset($key) {
1610 if (method_exists($this, 'get_'.$key)) {
1611 $val = $this->{'get_'.$key}();
1612 return !empty($val);
1613 }
1614 return !empty($this->properties->{$key});
1615 }
1616
1617 /**
ff85f902 1618 * If overridden should create a new instance, save it in the DB and return it
1e7f8ea2
PS
1619 */
1620 public static function create() {}
1621 /**
ff85f902 1622 * If overridden should load an instance from the DB and return it
1e7f8ea2
PS
1623 */
1624 public static function load() {}
1625 /**
1626 * Fetches all of the properties of the object
1627 * @return stdClass
1628 */
1629 public function properties() {
1630 return $this->properties;
1631 }
1632}
1633
1634
1635/**
1636 * Abstract class representation of a page associated with a lesson.
1637 *
1638 * This class should MUST be extended by all specialised page types defined in
1639 * mod/lesson/pagetypes/.
1640 * There are a handful of abstract methods that need to be defined as well as
1641 * severl methods that can optionally be defined in order to make the page type
1642 * operate in the desired way
1643 *
1644 * Database properties
1645 * @property int $id The id of this lesson page
1646 * @property int $lessonid The id of the lesson this page belongs to
1647 * @property int $prevpageid The id of the page before this one
1648 * @property int $nextpageid The id of the next page in the page sequence
1649 * @property int $qtype Identifies the page type of this page
1650 * @property int $qoption Used to record page type specific options
1651 * @property int $layout Used to record page specific layout selections
1652 * @property int $display Used to record page specific display selections
1653 * @property int $timecreated Timestamp for when the page was created
1654 * @property int $timemodified Timestamp for when the page was last modified
1655 * @property string $title The title of this page
1656 * @property string $contents The rich content shown to describe the page
1657 * @property int $contentsformat The format of the contents field
1658 *
1659 * Calculated properties
1660 * @property-read array $answers An array of answers for this page
1661 * @property-read bool $displayinmenublock Toggles display in the left menu block
1662 * @property-read array $jumps An array containing all the jumps this page uses
1663 * @property-read lesson $lesson The lesson this page belongs to
1664 * @property-read int $type The type of the page [question | structure]
1665 * @property-read typeid The unique identifier for the page type
1666 * @property-read typestring The string that describes this page type
1667 *
1668 * @abstract
cc3dbaaa
PS
1669 * @copyright 2009 Sam Hemelryk
1670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
1671 */
1672abstract class lesson_page extends lesson_base {
1673
1674 /**
1675 * A reference to the lesson this page belongs to
1676 * @var lesson
1677 */
1678 protected $lesson = null;
1679 /**
1680 * Contains the answers to this lesson_page once loaded
1681 * @var null|array
1682 */
1683 protected $answers = null;
1684 /**
1685 * This sets the type of the page, can be one of the constants defined below
1686 * @var int
1687 */
1688 protected $type = 0;
1689
1690 /**
1691 * Constants used to identify the type of the page
1692 */
1693 const TYPE_QUESTION = 0;
1694 const TYPE_STRUCTURE = 1;
1695
1696 /**
1697 * This method should return the integer used to identify the page type within
ff85f902 1698 * the database and throughout code. This maps back to the defines used in 1.x
1e7f8ea2
PS
1699 * @abstract
1700 * @return int
1701 */
1702 abstract protected function get_typeid();
1703 /**
1704 * This method should return the string that describes the pagetype
1705 * @abstract
1706 * @return string
1707 */
1708 abstract protected function get_typestring();
1709
1710 /**
1711 * This method gets called to display the page to the user taking the lesson
1712 * @abstract
1713 * @param object $renderer
1714 * @param object $attempt
1715 * @return string
1716 */
1717 abstract public function display($renderer, $attempt);
1718
1719 /**
1720 * Creates a new lesson_page within the database and returns the correct pagetype
1721 * object to use to interact with the new lesson
1722 *
1723 * @final
1724 * @static
1725 * @param object $properties
1726 * @param lesson $lesson
1727 * @return lesson_page Specialised object that extends lesson_page
1728 */
1729 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
1730 global $DB;
1731 $newpage = new stdClass;
1732 $newpage->title = $properties->title;
1733 $newpage->contents = $properties->contents_editor['text'];
1734 $newpage->contentsformat = $properties->contents_editor['format'];
1735 $newpage->lessonid = $lesson->id;
1736 $newpage->timecreated = time();
1737 $newpage->qtype = $properties->qtype;
1738 $newpage->qoption = (isset($properties->qoption))?1:0;
1739 $newpage->layout = (isset($properties->layout))?1:0;
1740 $newpage->display = (isset($properties->display))?1:0;
1741 $newpage->prevpageid = 0; // this is a first page
1742 $newpage->nextpageid = 0; // this is the only page
1743
1744 if ($properties->pageid) {
1745 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
1746 if (!$prevpage) {
1747 print_error('cannotfindpages', 'lesson');
1748 }
1749 $newpage->prevpageid = $prevpage->id;
1750 $newpage->nextpageid = $prevpage->nextpageid;
1751 } else {
1752 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
1753 if ($nextpage) {
1754 // This is the first page, there are existing pages put this at the start
1755 $newpage->nextpageid = $nextpage->id;
1756 }
1757 }
1758
1759 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
1760
1761 $editor = new stdClass;
1762 $editor->id = $newpage->id;
1763 $editor->contents_editor = $properties->contents_editor;
1764 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
1765 $DB->update_record("lesson_pages", $editor);
1766
1767 if ($newpage->prevpageid > 0) {
1768 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
1769 }
1770 if ($newpage->nextpageid > 0) {
1771 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
1772 }
1773
1774 $page = lesson_page::load($newpage, $lesson);
1775 $page->create_answers($properties);
1776
1777 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
1778
1779 return $page;
1780 }
1781
1782 /**
1783 * This method loads a page object from the database and returns it as a
1784 * specialised object that extends lesson_page
1785 *
1786 * @final
1787 * @static
1788 * @param int $id
1789 * @param lesson $lesson
1790 * @return lesson_page Specialised lesson_page object
1791 */
1792 final public static function load($id, lesson $lesson) {
1793 global $DB;
1794
1795 if (is_object($id) && !empty($id->qtype)) {
1796 $page = $id;
1797 } else {
1798 $page = $DB->get_record("lesson_pages", array("id" => $id));
1799 if (!$page) {
1800 print_error('cannotfindpages', 'lesson');
1801 }
1802 }
1803 $manager = lesson_page_type_manager::get($lesson);
1804
1805 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
1806 if (!class_exists($class)) {
1807 $class = 'lesson_page';
1808 }
1809
1810 return new $class($page, $lesson);
1811 }
1812
1813 /**
1814 * Deletes a lesson_page from the database as well as any associated records.
1815 * @final
1816 * @return bool
1817 */
1818 final public function delete() {
1819 global $DB;
1820 // first delete all the associated records...
1821 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
1822 // ...now delete the answers...
1823 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
1824 // ..and the page itself
1825 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
1826
1827 // repair the hole in the linkage
1828 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
1829 //This is the only page, no repair needed
1830 } elseif (!$this->properties->prevpageid) {
1831 // this is the first page...
1832 $page = $this->lesson->load_page($this->properties->nextpageid);
1833 $page->move(null, 0);
1834 } elseif (!$this->properties->nextpageid) {
1835 // this is the last page...
1836 $page = $this->lesson->load_page($this->properties->prevpageid);
1837 $page->move(0);
1838 } else {
1839 // page is in the middle...
1840 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
1841 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
1842
1843 $prevpage->move($nextpage->id);
1844 $nextpage->move(null, $prevpage->id);
1845 }
1846 return true;
1847 }
1848
1849 /**
1850 * Moves a page by updating its nextpageid and prevpageid values within
1851 * the database
1852 *
1853 * @final
1854 * @param int $nextpageid
1855 * @param int $prevpageid
1856 */
1857 final public function move($nextpageid=null, $prevpageid=null) {
1858 global $DB;
1859 if ($nextpageid === null) {
1860 $nextpageid = $this->properties->nextpageid;
1861 }
1862 if ($prevpageid === null) {
1863 $prevpageid = $this->properties->prevpageid;
1864 }
1865 $obj = new stdClass;
1866 $obj->id = $this->properties->id;
1867 $obj->prevpageid = $prevpageid;
1868 $obj->nextpageid = $nextpageid;
1869 $DB->update_record('lesson_pages', $obj);
1870 }
1871
1872 /**
1873 * Returns the answers that are associated with this page in the database
1874 *
1875 * @final
1876 * @return array
1877 */
1878 final public function get_answers() {
1879 global $DB;
1880 if ($this->answers === null) {
1881 $this->answers = array();
1882 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
1883 if (!$answers) {
1884 debugging(get_string('cannotfindanswer', 'lesson'));
1885 return array();
1886 }
1887 foreach ($answers as $answer) {
1888 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
1889 }
1890 }
1891 return $this->answers;
1892 }
1893
1894 /**
1895 * Returns the lesson this page is associated with
1896 * @final
1897 * @return lesson
1898 */
1899 final protected function get_lesson() {
1900 return $this->lesson;
1901 }
1902
1903 /**
1904 * Returns the type of page this is. Not to be confused with page type
1905 * @final
1906 * @return int
1907 */
1908 final protected function get_type() {
1909 return $this->type;
1910 }
1911
1912 /**
1913 * Records an attempt at this page
1914 *
1915 * @final
1916 * @param stdClass $context
1917 * @return stdClass Returns the result of the attempt
1918 */
1919 final public function record_attempt($context) {
1920 global $DB, $USER, $OUTPUT;
1921
1922 /**
ff85f902 1923 * This should be overridden by each page type to actually check the response
1e7f8ea2
PS
1924 * against what ever custom criteria they have defined
1925 */
1926 $result = $this->check_answer();
1927
1928 $result->attemptsremaining = 0;
1929 $result->maxattemptsreached = false;
1930
1931 if ($result->noanswer) {
1932 $result->newpageid = $this->properties->id; // display same page again
1933 $result->feedback = get_string('noanswer', 'lesson');
1934 } else {
1935 if (!has_capability('mod/lesson:manage', $context)) {
1936 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
1937 // record student's attempt
1938 $attempt = new stdClass;
1939 $attempt->lessonid = $this->lesson->id;
1940 $attempt->pageid = $this->properties->id;
1941 $attempt->userid = $USER->id;
1942 $attempt->answerid = $result->answerid;
1943 $attempt->retry = $nretakes;
1944 $attempt->correct = $result->correctanswer;
1945 if($result->userresponse !== null) {
1946 $attempt->useranswer = $result->userresponse;
1947 }
1948
1949 $attempt->timeseen = time();
1950 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
1951 if (isset($USER->modattempts[$this->lesson->id])) {
1952 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
1953 }
1954
1955 $DB->insert_record("lesson_attempts", $attempt);
1956 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
1957 // displaying of message(s) is at the end of page for more ergonomic display
1958 if (!$result->correctanswer && ($result->newpageid == 0)) {
1959 // wrong answer and student is stuck on this page - check how many attempts
1960 // the student has had at this page/question
1961 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id),"retry", $nretakes);
1962 // retreive the number of attempts left counter for displaying at bottom of feedback page
1963 if ($nattempts >= $this->lesson->maxattempts) {
1964 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
1965 $result->maxattemptsreached = true;
1966 }
1967 $result->newpageid = LESSON_NEXTPAGE;
1968 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
1969 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
1970 }
1971 }
1972 }
1973 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
1974 if ($result->newpageid == 0) {
1975 $result->newpageid = $this->properties->id;
1976 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
1977 $nextpage = $this->lesson->get_next_page($this->properties->nextpageid);
1978 if ($nextpage === false) {
1979 $result->newpageid = LESSON_EOL;
1980 } else {
1981 $result->newpageid = $nextpage->id;
1982 }
1983 }
1984
1985 // Determine default feedback if necessary
1986 if (empty($result->response)) {
1987 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
1988 // These conditions have been met:
1989 // 1. The lesson manager has not supplied feedback to the student
1990 // 2. Not displaying default feedback
1991 // 3. The user did provide an answer
1992 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
1993
1994 $result->nodefaultresponse = true; // This will cause a redirect below
1995 } else if ($result->isessayquestion) {
1996 $result->response = get_string('defaultessayresponse', 'lesson');
1997 } else if ($result->correctanswer) {
1998 $result->response = get_string('thatsthecorrectanswer', 'lesson');
1999 } else {
2000 $result->response = get_string('thatsthewronganswer', 'lesson');
2001 }
2002 }
2003
2004 if ($result->response) {
2005 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2006 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2007 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2008 if ($qattempts == 1) {
2009 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2010 } else {
2011 $result->feedback = $OUTPUT->BOX(get_string("secondpluswrong", "lesson"), 'feedback');
2012 }
2013 } else {
2014 $class = 'response';
2015 if ($result->correctanswer) {
2016 $class .= ' correct'; //CSS over-ride this if they exist (!important)
2017 } else if (!$result->isessayquestion) {
2018 $class .= ' incorrect'; //CSS over-ride this if they exist (!important)
2019 }
2020 $options = new stdClass;
2021 $options->noclean = true;
2022 $options->para = true;
367a75fa 2023 $options->overflowdiv = true;
89970a13 2024 $result->feedback = $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 'generalbox boxaligncenter');
1e7f8ea2
PS
2025 $result->feedback .= '<div class="correctanswer generalbox"><em>'.get_string("youranswer", "lesson").'</em> : '.$result->studentanswer; // already in clean html
2026 $result->feedback .= $OUTPUT->box($result->response, $class); // already conerted to HTML
2027 echo "</div>";
2028 }
2029 }
2030 }
2031
2032 return $result;
2033 }
2034
2035 /**
2036 * Returns the string for a jump name
2037 *
2038 * @final
2039 * @param int $jumpto Jump code or page ID
2040 * @return string
2041 **/
2042 final protected function get_jump_name($jumpto) {
2043 global $DB;
2044 static $jumpnames = array();
2045
2046 if (!array_key_exists($jumpto, $jumpnames)) {
44cb7e63 2047 if ($jumpto == LESSON_THISPAGE) {
1e7f8ea2
PS
2048 $jumptitle = get_string('thispage', 'lesson');
2049 } elseif ($jumpto == LESSON_NEXTPAGE) {
2050 $jumptitle = get_string('nextpage', 'lesson');
2051 } elseif ($jumpto == LESSON_EOL) {
2052 $jumptitle = get_string('endoflesson', 'lesson');
2053 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2054 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2055 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2056 $jumptitle = get_string('previouspage', 'lesson');
2057 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2058 $jumptitle = get_string('randompageinbranch', 'lesson');
2059 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2060 $jumptitle = get_string('randombranch', 'lesson');
2061 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2062 $jumptitle = get_string('clusterjump', 'lesson');
2063 } else {
2064 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2065 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2066 }
2067 }
2068 $jumpnames[$jumpto] = format_string($jumptitle,true);
2069 }
2070
2071 return $jumpnames[$jumpto];
2072 }
2073
2074 /**
ff85f902 2075 * Constructor method
1e7f8ea2
PS
2076 * @param object $properties
2077 * @param lesson $lesson
2078 */
2079 public function __construct($properties, lesson $lesson) {
2080 parent::__construct($properties);
2081 $this->lesson = $lesson;
2082 }
2083
2084 /**
2085 * Returns the score for the attempt
ff85f902 2086 * This may be overridden by page types that require manual grading
1e7f8ea2
PS
2087 * @param array $answers
2088 * @param object $attempt
2089 * @return int
2090 */
2091 public function earned_score($answers, $attempt) {
2092 return $answers[$attempt->answerid]->score;
2093 }
2094
2095 /**
2096 * This is a callback method that can be override and gets called when ever a page
2097 * is viewed
2098 *
2099 * @param bool $canmanage True if the user has the manage cap
2100 * @return mixed
2101 */
2102 public function callback_on_view($canmanage) {
2103 return true;
2104 }
2105
2106 /**
2107 * Updates a lesson page and its answers within the database
2108 *
2109 * @param object $properties
2110 * @return bool
2111 */
2112 public function update($properties, $context = null, $maxbytes = null) {
7b30b24b 2113 global $DB, $PAGE;
1e7f8ea2
PS
2114 $answers = $this->get_answers();
2115 $properties->id = $this->properties->id;
2116 $properties->lessonid = $this->lesson->id;
2117 if (empty($properties->qoption)) {
2118 $properties->qoption = '0';
2119 }
2120 if (empty($context)) {
2121 $context = $PAGE->context;
2122 }
2123 if ($maxbytes === null) {
2124 $maxbytes =get_max_upload_file_size();
2125 }
2126 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2127 $DB->update_record("lesson_pages", $properties);
2128
2129 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2130 if (!array_key_exists($i, $this->answers)) {
2131 $this->answers[$i] = new stdClass;
2132 $this->answers[$i]->lessonid = $this->lesson->id;
2133 $this->answers[$i]->pageid = $this->id;
2134 $this->answers[$i]->timecreated = $this->timecreated;
2135 }
2136 if (!empty($properties->answer_editor[$i])) {
2137 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2138 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2139 if (isset($properties->response_editor[$i])) {
2140 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2141 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
2142 }
2143 if (isset($properties->jumpto[$i])) {
2144 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2145 }
2146 if ($this->lesson->custom && isset($properties->score[$i])) {
2147 $this->answers[$i]->score = $properties->score[$i];
2148 }
2149 if (!isset($this->answers[$i]->id)) {
2150 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2151 } else {
2152 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2153 }
2154
2155 } else {
2156 break;
2157 }
2158 }
2159 return true;
2160 }
2161
2162 /**
2163 * Can be set to true if the page requires a static link to create a new instance
2164 * instead of simply being included in the dropdown
2165 * @param int $previd
2166 * @return bool
2167 */
2168 public function add_page_link($previd) {
2169 return false;
2170 }
2171
2172 /**
2173 * Returns true if a page has been viewed before
2174 *
2175 * @param array|int $param Either an array of pages that have been seen or the
2176 * number of retakes a user has had
2177 * @return bool
2178 */
2179 public function is_unseen($param) {
2180 global $USER, $DB;
2181 if (is_array($param)) {
2182 $seenpages = $param;
2183 return (!array_key_exists($this->properties->id, $seenpages));
2184 } else {
2185 $nretakes = $param;
2186 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2187 return true;
2188 }
2189 }
2190 return false;
2191 }
2192
2193 /**
2194 * Checks to see if a page has been answered previously
2195 * @param int $nretakes
2196 * @return bool
2197 */
2198 public function is_unanswered($nretakes) {
2199 global $DB, $USER;
2200 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2201 return true;
2202 }
2203 return false;
2204 }
2205
2206 /**
2207 * Creates answers within the database for this lesson_page. Usually only ever
2208 * called when creating a new page instance
2209 * @param object $properties
2210 * @return array
2211 */
2212 public function create_answers($properties) {
2213 global $DB;
2214 // now add the answers
2215 $newanswer = new stdClass;
2216 $newanswer->lessonid = $this->lesson->id;
2217 $newanswer->pageid = $this->properties->id;
2218 $newanswer->timecreated = $this->properties->timecreated;
2219
2220 $answers = array();
2221
2222 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2223 $answer = clone($newanswer);
2224 if (!empty($properties->answer_editor[$i])) {
2225 $answer->answer = $properties->answer_editor[$i]['text'];
2226 $answer->answerformat = $properties->answer_editor[$i]['format'];
2227 if (isset($properties->response_editor[$i])) {
2228 $answer->response = $properties->response_editor[$i]['text'];
2229 $answer->responseformat = $properties->response_editor[$i]['format'];
2230 }
2231 if (isset($properties->jumpto[$i])) {
2232 $answer->jumpto = $properties->jumpto[$i];
2233 }
2234 if ($this->lesson->custom && isset($properties->score[$i])) {
2235 $answer->score = $properties->score[$i];
2236 }
2237 $answer->id = $DB->insert_record("lesson_answers", $answer);
2238 $answers[$answer->id] = new lesson_page_answer($answer);
2239 } else {
2240 break;
2241 }
2242 }
2243
2244 $this->answers = $answers;
2245 return $answers;
2246 }
2247
2248 /**
ff85f902 2249 * This method MUST be overridden by all question page types, or page types that
1e7f8ea2
PS
2250 * wish to score a page.
2251 *
2252 * The structure of result should always be the same so it is a good idea when
2253 * overriding this method on a page type to call
2254 * <code>
2255 * $result = parent::check_answer();
2256 * </code>
ff85f902 2257 * before modifying it as required.
1e7f8ea2
PS
2258 *
2259 * @return stdClass
2260 */
2261 public function check_answer() {
2262 $result = new stdClass;
2263 $result->answerid = 0;
2264 $result->noanswer = false;
2265 $result->correctanswer = false;
2266 $result->isessayquestion = false; // use this to turn off review button on essay questions
2267 $result->response = '';
2268 $result->newpageid = 0; // stay on the page
2269 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2270 $result->userresponse = null;
2271 $result->feedback = '';
2272 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2273 return $result;
2274 }
2275
2276 /**
2277 * True if the page uses a custom option
2278 *
2279 * Should be override and set to true if the page uses a custom option.
2280 *
2281 * @return bool
2282 */
2283 public function has_option() {
2284 return false;
2285 }
2286
2287 /**
2288 * Returns the maximum number of answers for this page given the maximum number
2289 * of answers permitted by the lesson.
2290 *
2291 * @param int $default
2292 * @return int
2293 */
2294 public function max_answers($default) {
2295 return $default;
2296 }
2297
2298 /**
2299 * Returns the properties of this lesson page as an object
2300 * @return stdClass;
2301 */
2302 public function properties() {
2303 $properties = clone($this->properties);
2304 if ($this->answers === null) {
2305 $this->get_answers();
2306 }
2307 if (count($this->answers)>0) {
2308 $count = 0;
2309 foreach ($this->answers as $answer) {
2310 $properties->{'answer_editor['.$count.']'} = array('text'=>$answer->answer, 'format'=>$answer->answerformat);
2311 $properties->{'response_editor['.$count.']'} = array('text'=>$answer->response, 'format'=>$answer->responseformat);
2312 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2313 $properties->{'score['.$count.']'} = $answer->score;
2314 $count++;
2315 }
2316 }
2317 return $properties;
2318 }
2319
2320 /**
ff85f902 2321 * Returns an array of options to display when choosing the jumpto for a page/answer
1e7f8ea2
PS
2322 * @static
2323 * @param int $pageid
2324 * @param lesson $lesson
2325 * @return array
2326 */
2327 public static function get_jumptooptions($pageid, lesson $lesson) {
2328 global $DB;
2329 $jump = array();
2330 $jump[0] = get_string("thispage", "lesson");
2331 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2332 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2333 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2334
2335 if ($pageid == 0) {
2336 return $jump;
2337 }
2338
2339 $pages = $lesson->load_all_pages();
2340 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))) {
2341 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
2342 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
2343 }
2344 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
2345 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
2346 }
2347 if (!optional_param('firstpage', 0, PARAM_INT)) {
2348 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
2349 while (true) {
2350 if ($apageid) {
2351 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
2352 $jump[$apageid] = strip_tags(format_string($title,true));
2353 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
2354 } else {
2355 // last page reached
2356 break;
2357 }
2358 }
2359 }
2360 return $jump;
2361 }
2362 /**
2363 * Returns the contents field for the page properly formatted and with plugin
2364 * file url's converted
2365 * @return string
2366 */
2367 public function get_contents() {
2368 global $PAGE;
2369 if (!empty($this->properties->contents)) {
2370 if (!isset($this->properties->contentsformat)) {
2371 $this->properties->contentsformat = FORMAT_HTML;
2372 }
2373 $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id);
7a0873d1
PS
2374 $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()!!!!!!
2375 return format_text($contents, $this->properties->contentsformat, array('context'=>$context, 'noclean'=>true)); // page edit is marked with XSS, we want all content here
1e7f8ea2
PS
2376 } else {
2377 return '';
2378 }
2379 }
2380
2381 /**
2382 * Set to true if this page should display in the menu block
2383 * @return bool
2384 */
2385 protected function get_displayinmenublock() {
2386 return false;
2387 }
2388
2389 /**
2390 * Get the string that describes the options of this page type
2391 * @return string
2392 */
2393 public function option_description_string() {
2394 return '';
2395 }
2396
2397 /**
2398 * Updates a table with the answers for this page
2399 * @param html_table $table
2400 * @return html_table
2401 */
2402 public function display_answers(html_table $table) {
2403 $answers = $this->get_answers();
2404 $i = 1;
2405 foreach ($answers as $answer) {
2406 $cells = array();
2407 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
2408 $cells[] = $this->get_jump_name($answer->jumpto);
2409 $table->data[] = new html_table_row($cells);
2410 if ($i === 1){
2411 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
2412 }
2413 $i++;
2414 }
2415 return $table;
2416 }
2417
2418 /**
2419 * Determines if this page should be grayed out on the management/report screens
2420 * @return int 0 or 1
2421 */
2422 protected function get_grayout() {
2423 return 0;
2424 }
2425
2426 /**
2427 * Adds stats for this page to the &pagestats object. This should be defined
2428 * for all page types that grade
2429 * @param array $pagestats
2430 * @param int $tries
2431 * @return bool
2432 */
2433 public function stats(array &$pagestats, $tries) {
2434 return true;
2435 }
2436
2437 /**
2438 * Formats the answers of this page for a report
2439 *
2440 * @param object $answerpage
2441 * @param object $answerdata
2442 * @param object $useranswer
2443 * @param array $pagestats
2444 * @param int $i Count of first level answers
2445 * @param int $n Count of second level answers
2446 * @return object The answer page for this
2447 */
2448 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
2449 $answers = $this->get_answers();
2450 $formattextdefoptions = new stdClass;
2451 $formattextdefoptions->para = false; //I'll use it widely in this page
2452 foreach ($answers as $answer) {
2453 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
2454 $answerdata->answers[] = array($data, "");
2455 $answerpage->answerdata = $answerdata;
2456 }
2457 return $answerpage;
2458 }
2459
2460 /**
2461 * Gets an array of the jumps used by the answers of this page
2462 *
2463 * @return array
2464 */
2465 public function get_jumps() {
2466 global $DB;
2467 $jumps = array();
2468 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
2469 if ($answers = $this->get_answers()) {
2470 foreach ($answers as $answer) {
2471 $jumps[] = $this->get_jump_name($answer->jumpto);
2472 }
2473 }
2474 return $jumps;
2475 }
2476 /**
2477 * Informs whether this page type require manual grading or not
2478 * @return bool
2479 */
2480 public function requires_manual_grading() {
2481 return false;
2482 }
2483
2484 /**
2485 * A callback method that allows a page to override the next page a user will
2486 * see during when this page is being completed.
2487 * @return false|int
2488 */
2489 public function override_next_page() {
2490 return false;
2491 }
2492
2493 /**
2494 * This method is used to determine if this page is a valid page
2495 *
2496 * @param array $validpages
2497 * @param array $pageviews
2498 * @return int The next page id to check
2499 */
2500 public function valid_page_and_view(&$validpages, &$pageviews) {
2501 $validpages[$this->properties->id] = 1;
2502 return $this->properties->nextpageid;
2503 }
2504}
2505
2506
2507
2508/**
2509 * Class used to represent an answer to a page
2510 *
2511 * @property int $id The ID of this answer in the database
2512 * @property int $lessonid The ID of the lesson this answer belongs to
2513 * @property int $pageid The ID of the page this answer belongs to
2514 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
2515 * @property int $grade The grade this answer is worth
2516 * @property int $score The score this answer will give
2517 * @property int $flags Used to store options for the answer
2518 * @property int $timecreated A timestamp of when the answer was created
2519 * @property int $timemodified A timestamp of when the answer was modified
2520 * @property string $answer The answer itself
2521 * @property string $response The response the user sees if selecting this answer
2522 *
cc3dbaaa
PS
2523 * @copyright 2009 Sam Hemelryk
2524 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
2525 */
2526class lesson_page_answer extends lesson_base {
2527
2528 /**
2529 * Loads an page answer from the DB
2530 *
2531 * @param int $id
2532 * @return lesson_page_answer
2533 */
2534 public static function load($id) {
2535 global $DB;
2536 $answer = $DB->get_record("lesson_answers", array("id" => $id));
2537 return new lesson_page_answer($answer);
2538 }
2539
2540 /**
2541 * Given an object of properties and a page created answer(s) and saves them
2542 * in the database.
2543 *
2544 * @param stdClass $properties
2545 * @param lesson_page $page
2546 * @return array
2547 */
2548 public static function create($properties, lesson_page $page) {
2549 return $page->create_answers($properties);
2550 }
2551
2552}
2553
2554/**
2555 * A management class for page types
2556 *
2557 * This class is responsible for managing the different pages. A manager object can
2558 * be retrieved by calling the following line of code:
2559 * <code>
2560 * $manager = lesson_page_type_manager::get($lesson);
2561 * </code>
2562 * The first time the page type manager is retrieved the it includes all of the
2563 * different page types located in mod/lesson/pagetypes.
2564 *
cc3dbaaa
PS
2565 * @copyright 2009 Sam Hemelryk
2566 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
2567 */
2568class lesson_page_type_manager {
2569
2570 /**
2571 * An array of different page type classes
2572 * @var array
2573 */
2574 protected $types = array();
2575
2576 /**
2577 * Retrieves the lesson page type manager object
2578 *
2579 * If the object hasn't yet been created it is created here.
2580 *
2581 * @staticvar lesson_page_type_manager $pagetypemanager
2582 * @param lesson $lesson
2583 * @return lesson_page_type_manager
2584 */
2585 public static function get(lesson $lesson) {
2586 static $pagetypemanager;
2587 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
2588 $pagetypemanager = new lesson_page_type_manager();
2589 $pagetypemanager->load_lesson_types($lesson);
2590 }
2591 return $pagetypemanager;
2592 }
2593
2594 /**
2595 * Finds and loads all lesson page types in mod/lesson/pagetypes
2596 *
2597 * @param lesson $lesson
2598 */
2599 public function load_lesson_types(lesson $lesson) {
2600 global $CFG;
2601 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
2602 $dir = dir($basedir);
2603 while (false !== ($entry = $dir->read())) {
2604 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
2605 continue;
2606 }
2607 require_once($basedir.$entry);
2608 $class = 'lesson_page_type_'.strtok($entry,'.');
2609 if (class_exists($class)) {
2610 $pagetype = new $class(new stdClass, $lesson);
2611 $this->types[$pagetype->typeid] = $pagetype;
2612 }
2613 }
2614
2615 }
2616
2617 /**
2618 * Returns an array of strings to describe the loaded page types
2619 *
2620 * @param int $type Can be used to return JUST the string for the requested type
2621 * @return array
2622 */
2623 public function get_page_type_strings($type=null, $special=true) {
2624 $types = array();
2625 foreach ($this->types as $pagetype) {
2626 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
2627 $types[$pagetype->typeid] = $pagetype->typestring;
2628 }
2629 }
2630 return $types;
2631 }
2632
2633 /**
2634 * Returns the basic string used to identify a page type provided with an id
2635 *
2636 * This string can be used to instantiate or identify the page type class.
2637 * If the page type id is unknown then 'unknown' is returned
2638 *
2639 * @param int $id
2640 * @return string
2641 */
2642 public function get_page_type_idstring($id) {
2643 foreach ($this->types as $pagetype) {
2644 if ((int)$pagetype->typeid === (int)$id) {
2645 return $pagetype->idstring;
2646 }
2647 }
2648 return 'unknown';
2649 }
2650
2651 /**
2652 * Loads a page for the provided lesson given it's id
2653 *
2654 * This function loads a page from the lesson when given both the lesson it belongs
2655 * to as well as the page's id.
2656 * If the page doesn't exist an error is thrown
2657 *
2658 * @param int $pageid The id of the page to load
2659 * @param lesson $lesson The lesson the page belongs to
2660 * @return lesson_page A class that extends lesson_page
2661 */
2662 public function load_page($pageid, lesson $lesson) {
2663 global $DB;
2664 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
2665 print_error('cannotfindpages', 'lesson');
2666 }
2667 $pagetype = get_class($this->types[$page->qtype]);
2668 $page = new $pagetype($page, $lesson);
2669 return $page;
2670 }
2671
2672 /**
2673 * This function loads ALL pages that belong to the lesson.
2674 *
2675 * @param lesson $lesson
2676 * @return array An array of lesson_page_type_*
2677 */
2678 public function load_all_pages(lesson $lesson) {
2679 global $DB;
2680 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
2681 print_error('cannotfindpages', 'lesson');
2682 }
2683 foreach ($pages as $key=>$page) {
2684 $pagetype = get_class($this->types[$page->qtype]);
2685 $pages[$key] = new $pagetype($page, $lesson);
2686 }
2687
2688 $orderedpages = array();
2689 $lastpageid = 0;
2690
2691 while (true) {
2692 foreach ($pages as $page) {
2693 if ((int)$page->prevpageid === (int)$lastpageid) {
2694 $orderedpages[$page->id] = $page;
2695 unset($pages[$page->id]);
2696 $lastpageid = $page->id;
2697 if ((int)$page->nextpageid===0) {
2698 break 2;
2699 } else {
2700 break 1;
2701 }
2702 }
2703 }
2704 }
2705
2706 return $orderedpages;
2707 }
2708
2709 /**
ff85f902 2710 * Fetches an mform that can be used to create/edit an page
1e7f8ea2
PS
2711 *
2712 * @param int $type The id for the page type
2713 * @param array $arguments Any arguments to pass to the mform
2714 * @return lesson_add_page_form_base
2715 */
2716 public function get_page_form($type, $arguments) {
2717 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
2718 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
2719 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
2720 $class = 'lesson_add_page_form_selection';
2721 } else if ($class === 'lesson_add_page_form_unknown') {
2722 $class = 'lesson_add_page_form_selection';
2723 }
2724 return new $class(null, $arguments);
2725 }
2726
2727 /**
2728 * Returns an array of links to use as add page links
2729 * @param int $previd The id of the previous page
2730 * @return array
2731 */
2732 public function get_add_page_type_links($previd) {
2733 global $OUTPUT;
2734
2735 $links = array();
2736
2737 foreach ($this->types as $key=>$type) {
2738 if ($link = $type->add_page_link($previd)) {
2739 $links[$key] = $link;
2740 }
2741 }
2742
2743 return $links;
2744 }
2745}