Merge branch 'MDL-34102' of git://github.com/jmvedrine/moodle
[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 *
9b24f68b 22 * @package mod_lesson
0a4abb73 23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
cc3dbaaa 24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
5491947a 25 **/
4b55d2af 26
0a4abb73 27/** Make sure this isn't being directly accessed */
1e7f8ea2 28defined('MOODLE_INTERNAL') || die();
0a4abb73
SH
29
30/** Include the files that are required by this module */
1e7f8ea2 31require_once($CFG->dirroot.'/course/moodleform_mod.php');
0a4abb73 32require_once($CFG->dirroot . '/mod/lesson/lib.php');
99d19c13 33require_once($CFG->libdir . '/filelib.php');
0a4abb73 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
a1556aaf
SB
61/** Answer format is HTML */
62define("LESSON_ANSWER_HTML", "HTML");
1e7f8ea2 63
5e7856af 64//////////////////////////////////////////////////////////////////////////////////////
86342d63 65/// Any other lesson functions go here. Each of them must have a name that
5e7856af 66/// starts with lesson_
67
4b55d2af 68/**
86342d63 69 * Checks to see if a LESSON_CLUSTERJUMP or
4b55d2af 70 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
71 *
86342d63 72 * This function is only executed when a teacher is
4b55d2af 73 * checking the navigation for a lesson.
74 *
3983f2dc 75 * @param stdClass $lesson Id of the lesson that is to be checked.
4b55d2af 76 * @return boolean True or false.
77 **/
06469639 78function lesson_display_teacher_warning($lesson) {
646fc290 79 global $DB;
86342d63 80
ac8e16be 81 // get all of the lesson answers
0a4abb73 82 $params = array ("lessonid" => $lesson->id);
646fc290 83 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
64a3ce8c 84 // no answers, then not using cluster or unseen
ac8e16be 85 return false;
86 }
87 // just check for the first one that fulfills the requirements
88 foreach ($lessonanswers as $lessonanswer) {
89 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
90 return true;
91 }
92 }
86342d63 93
ac8e16be 94 // if no answers use either of the two jumps
95 return false;
5e7856af 96}
97
4b55d2af 98/**
99 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
86342d63 100 *
4b55d2af 101 * will return the pageid of a random unseen page that is within a branch
102 *
0a4abb73 103 * @param lesson $lesson
f521f98a 104 * @param int $userid Id of the user.
4b55d2af 105 * @param int $pageid Id of the page from which we are jumping.
106 * @return int Id of the next page.
4b55d2af 107 **/
5e7856af 108function lesson_unseen_question_jump($lesson, $user, $pageid) {
646fc290 109 global $DB;
86342d63 110
ac8e16be 111 // get the number of retakes
0a4abb73 112 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
ac8e16be 113 $retakes = 0;
114 }
115
116 // get all the lesson_attempts aka what the user has seen
0a4abb73 117 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
ac8e16be 118 foreach($viewedpages as $viewed) {
119 $seenpages[] = $viewed->pageid;
120 }
121 } else {
122 $seenpages = array();
123 }
124
125 // get the lesson pages
0a4abb73 126 $lessonpages = $lesson->load_all_pages();
86342d63 127
ac8e16be 128 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
129 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
130 }
131
132 // go up the pages till branch table
133 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
0a4abb73 134 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 135 break;
136 }
137 $pageid = $lessonpages[$pageid]->prevpageid;
138 }
86342d63 139
97b4ec5e 140 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
86342d63 141
ac8e16be 142 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
143 $unseen = array();
86342d63 144 foreach($pagesinbranch as $page) {
ac8e16be 145 if (!in_array($page->id, $seenpages)) {
146 $unseen[] = $page->id;
147 }
148 }
149
150 if(count($unseen) == 0) {
151 if(isset($pagesinbranch)) {
152 $temp = end($pagesinbranch);
153 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
154 } else {
155 // there are no pages inside the branch, so return the next page
156 $nextpage = $lessonpages[$pageid]->nextpageid;
157 }
158 if ($nextpage == 0) {
159 return LESSON_EOL;
160 } else {
161 return $nextpage;
162 }
163 } else {
164 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
165 }
5e7856af 166}
167
4b55d2af 168/**
169 * Handles the unseen branch table jump.
170 *
0a4abb73 171 * @param lesson $lesson
f521f98a 172 * @param int $userid User id.
4b55d2af 173 * @return int Will return the page id of a branch table or end of lesson
4b55d2af 174 **/
0a4abb73 175function lesson_unseen_branch_jump($lesson, $userid) {
646fc290 176 global $DB;
86342d63 177
0a4abb73 178 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
ac8e16be 179 $retakes = 0;
180 }
181
0a4abb73 182 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
646fc290 183 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
ac8e16be 184 "timeseen DESC")) {
86f93345 185 print_error('cannotfindrecords', 'lesson');
ac8e16be 186 }
187
188 // get the lesson pages
0a4abb73 189 $lessonpages = $lesson->load_all_pages();
86342d63 190
ff85f902 191 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
ac8e16be 192 // which is the branch table that starts the unseenbranch function
86342d63 193 $seen = array();
ac8e16be 194 foreach ($seenbranches as $seenbranch) {
195 if (!$seenbranch->flag) {
196 $seen[$seenbranch->pageid] = $seenbranch->pageid;
197 } else {
198 $start = $seenbranch->pageid;
199 break;
200 }
201 }
202 // this function searches through the lesson pages to find all the branch tables
203 // that follow the flagged branch table
204 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
0f6e2f02 205 $branchtables = array();
ac8e16be 206 while ($pageid != 0) { // grab all of the branch table till eol
0a4abb73 207 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 208 $branchtables[] = $lessonpages[$pageid]->id;
209 }
210 $pageid = $lessonpages[$pageid]->nextpageid;
211 }
212 $unseen = array();
213 foreach ($branchtables as $branchtable) {
214 // load all of the unseen branch tables into unseen
215 if (!array_key_exists($branchtable, $seen)) {
216 $unseen[] = $branchtable;
217 }
218 }
219 if (count($unseen) > 0) {
220 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
221 } else {
222 return LESSON_EOL; // has viewed all of the branch tables
223 }
5e7856af 224}
225
4b55d2af 226/**
227 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
86342d63 228 *
0a4abb73 229 * @param lesson $lesson
4b55d2af 230 * @param int $pageid The id of the page that we are jumping from (?)
231 * @return int The pageid of a random page that is within a branch table
4b55d2af 232 **/
0a4abb73 233function lesson_random_question_jump($lesson, $pageid) {
646fc290 234 global $DB;
86342d63 235
ac8e16be 236 // get the lesson pages
0a4abb73 237 $params = array ("lessonid" => $lesson->id);
646fc290 238 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
86f93345 239 print_error('cannotfindpages', 'lesson');
ac8e16be 240 }
241
242 // go up the pages till branch table
243 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
244
0a4abb73 245 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
ac8e16be 246 break;
247 }
248 $pageid = $lessonpages[$pageid]->prevpageid;
249 }
250
86342d63 251 // get the pages within the branch
97b4ec5e 252 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
86342d63 253
ac8e16be 254 if(count($pagesinbranch) == 0) {
255 // there are no pages inside the branch, so return the next page
256 return $lessonpages[$pageid]->nextpageid;
257 } else {
258 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
259 }
5e7856af 260}
261
4b55d2af 262/**
263 * Calculates a user's grade for a lesson.
264 *
4b55d2af 265 * @param object $lesson The lesson that the user is taking.
4b55d2af 266 * @param int $retries The attempt number.
ff85f902 267 * @param int $userid Id of the user (optional, default current user).
88427c07 268 * @return object { nquestions => number of questions answered
269 attempts => number of question attempts
270 total => max points possible
271 earned => points earned by student
272 grade => calculated percentage grade
273 nmanual => number of manually graded questions
274 manualpoints => point value for manually graded questions }
4b55d2af 275 */
86342d63 276function lesson_grade($lesson, $ntries, $userid = 0) {
646fc290 277 global $USER, $DB;
ac8e16be 278
88427c07 279 if (empty($userid)) {
280 $userid = $USER->id;
281 }
86342d63 282
88427c07 283 // Zero out everything
284 $ncorrect = 0;
285 $nviewed = 0;
286 $score = 0;
287 $nmanual = 0;
288 $manualpoints = 0;
289 $thegrade = 0;
290 $nquestions = 0;
291 $total = 0;
292 $earned = 0;
293
646fc290 294 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
86342d63 295 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
646fc290 296 userid = :userid AND retry = :retry", $params, "timeseen")) {
88427c07 297 // group each try with its page
298 $attemptset = array();
299 foreach ($useranswers as $useranswer) {
86342d63 300 $attemptset[$useranswer->pageid][] = $useranswer;
ac8e16be 301 }
86342d63 302
88427c07 303 // Drop all attempts that go beyond max attempts for the lesson
304 foreach ($attemptset as $key => $set) {
305 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
306 }
86342d63 307
88427c07 308 // get only the pages and their answers that the user answered
646fc290 309 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
0a4abb73
SH
310 array_unshift($parameters, $lesson->id);
311 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
312 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
86342d63 313
88427c07 314 // Number of pages answered
315 $nquestions = count($pages);
316
317 foreach ($attemptset as $attempts) {
0a4abb73 318 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
88427c07 319 if ($lesson->custom) {
320 $attempt = end($attempts);
321 // If essay question, handle it, otherwise add to score
0a4abb73 322 if ($page->requires_manual_grading()) {
f672e3e9
RW
323 $useranswerobj = unserialize($attempt->useranswer);
324 if (isset($useranswerobj->score)) {
325 $earned += $useranswerobj->score;
326 }
88427c07 327 $nmanual++;
328 $manualpoints += $answers[$attempt->answerid]->score;
ab1e7c39 329 } else if (!empty($attempt->answerid)) {
0a4abb73 330 $earned += $page->earned_score($answers, $attempt);
88427c07 331 }
332 } else {
333 foreach ($attempts as $attempt) {
334 $earned += $attempt->correct;
335 }
336 $attempt = end($attempts); // doesn't matter which one
337 // If essay question, increase numbers
0a4abb73 338 if ($page->requires_manual_grading()) {
88427c07 339 $nmanual++;
340 $manualpoints++;
ac8e16be 341 }
342 }
88427c07 343 // Number of times answered
344 $nviewed += count($attempts);
345 }
86342d63 346
88427c07 347 if ($lesson->custom) {
ac8e16be 348 $bestscores = array();
88427c07 349 // Find the highest possible score per page to get our total
350 foreach ($answers as $answer) {
46341ab7 351 if(!isset($bestscores[$answer->pageid])) {
88427c07 352 $bestscores[$answer->pageid] = $answer->score;
46341ab7 353 } else if ($bestscores[$answer->pageid] < $answer->score) {
88427c07 354 $bestscores[$answer->pageid] = $answer->score;
ac8e16be 355 }
356 }
88427c07 357 $total = array_sum($bestscores);
358 } else {
359 // Check to make sure the student has answered the minimum questions
360 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
361 // Nope, increase number viewed by the amount of unanswered questions
362 $total = $nviewed + ($lesson->minquestions - $nquestions);
363 } else {
364 $total = $nviewed;
365 }
ac8e16be 366 }
88427c07 367 }
86342d63 368
88427c07 369 if ($total) { // not zero
370 $thegrade = round(100 * $earned / $total, 5);
371 }
86342d63 372
88427c07 373 // Build the grade information object
374 $gradeinfo = new stdClass;
375 $gradeinfo->nquestions = $nquestions;
376 $gradeinfo->attempts = $nviewed;
377 $gradeinfo->total = $total;
378 $gradeinfo->earned = $earned;
379 $gradeinfo->grade = $thegrade;
380 $gradeinfo->nmanual = $nmanual;
381 $gradeinfo->manualpoints = $manualpoints;
86342d63 382
88427c07 383 return $gradeinfo;
384}
385
62eda6ea 386/**
387 * Determines if a user can view the left menu. The determining factor
388 * is whether a user has a grade greater than or equal to the lesson setting
389 * of displayleftif
390 *
391 * @param object $lesson Lesson object of the current lesson
392 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
62eda6ea 393 **/
394function lesson_displayleftif($lesson) {
646fc290 395 global $CFG, $USER, $DB;
86342d63 396
62eda6ea 397 if (!empty($lesson->displayleftif)) {
398 // get the current user's max grade for this lesson
646fc290 399 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
400 if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
62eda6ea 401 if ($maxgrade->maxgrade < $lesson->displayleftif) {
402 return 0; // turn off the displayleft
403 }
404 } else {
405 return 0; // no grades
406 }
407 }
86342d63 408
62eda6ea 409 // if we get to here, keep the original state of displayleft lesson setting
410 return $lesson->displayleft;
411}
5e7856af 412
4262a2f8 413/**
86342d63 414 *
4262a2f8 415 * @param $cm
416 * @param $lesson
417 * @param $page
418 * @return unknown_type
419 */
d9c26e21 420function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
4262a2f8 421 $bc = lesson_menu_block_contents($cm->id, $lesson);
422 if (!empty($bc)) {
423 $regions = $page->blocks->get_regions();
424 $firstregion = reset($regions);
d9c26e21 425 $page->blocks->add_fake_block($bc, $firstregion);
4262a2f8 426 }
427
428 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
429 if (!empty($bc)) {
d9c26e21 430 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
4262a2f8 431 }
432
433 if (!empty($timer)) {
434 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
435 if (!empty($bc)) {
d9c26e21 436 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
4262a2f8 437 }
438 }
439}
440
f521f98a 441/**
86342d63 442 * If there is a media file associated with this
4262a2f8 443 * lesson, return a block_contents that displays it.
f521f98a 444 *
445 * @param int $cmid Course Module ID for this lesson
446 * @param object $lesson Full lesson record object
4262a2f8 447 * @return block_contents
f521f98a 448 **/
4262a2f8 449function lesson_mediafile_block_contents($cmid, $lesson) {
d68ccdba 450 global $OUTPUT;
8d1a3963 451 if (empty($lesson->mediafile)) {
4262a2f8 452 return null;
f521f98a 453 }
4262a2f8 454
0a4abb73
SH
455 $options = array();
456 $options['menubar'] = 0;
457 $options['location'] = 0;
458 $options['left'] = 5;
459 $options['top'] = 5;
460 $options['scrollbars'] = 1;
461 $options['resizable'] = 1;
462 $options['width'] = $lesson->mediawidth;
463 $options['height'] = $lesson->mediaheight;
4262a2f8 464
9bf16314
PS
465 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
466 $action = new popup_action('click', $link, 'lessonmediafile', $options);
467 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
86342d63 468
4262a2f8 469 $bc = new block_contents();
470 $bc->title = get_string('linkedmedia', 'lesson');
ca332713 471 $bc->attributes['class'] = 'mediafile block';
4262a2f8 472 $bc->content = $content;
473
474 return $bc;
f521f98a 475}
476
477/**
478 * If a timed lesson and not a teacher, then
4262a2f8 479 * return a block_contents containing the clock.
f521f98a 480 *
481 * @param int $cmid Course Module ID for this lesson
482 * @param object $lesson Full lesson record object
483 * @param object $timer Full timer record object
4262a2f8 484 * @return block_contents
f521f98a 485 **/
4262a2f8 486function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
487 // Display for timed lessons and for students only
5918e371 488 $context = context_module::instance($cmid);
a1acc001 489 if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
4262a2f8 490 return null;
491 }
f521f98a 492
50d70c5c 493 $content = '<div id="lesson-timer">';
0a4abb73 494 $content .= $lesson->time_remaining($timer->starttime);
4262a2f8 495 $content .= '</div>';
ba458143 496
a1acc001 497 $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
50d70c5c
JMV
498 $page->requires->data_for_js('clocksettings', $clocksettings, true);
499 $page->requires->strings_for_js(array('timeisup'), 'lesson');
227255b8 500 $page->requires->js('/mod/lesson/timer.js');
50d70c5c 501 $page->requires->js_init_call('show_clock');
ba458143 502
4262a2f8 503 $bc = new block_contents();
504 $bc->title = get_string('timeremaining', 'lesson');
6605ff8c 505 $bc->attributes['class'] = 'clock block';
4262a2f8 506 $bc->content = $content;
507
508 return $bc;
f521f98a 509}
510
511/**
512 * If left menu is turned on, then this will
513 * print the menu in a block
514 *
515 * @param int $cmid Course Module ID for this lesson
0a4abb73 516 * @param lesson $lesson Full lesson record object
f521f98a 517 * @return void
518 **/
4262a2f8 519function lesson_menu_block_contents($cmid, $lesson) {
646fc290 520 global $CFG, $DB;
f521f98a 521
4262a2f8 522 if (!$lesson->displayleft) {
523 return null;
524 }
f521f98a 525
0a4abb73
SH
526 $pages = $lesson->load_all_pages();
527 foreach ($pages as $page) {
528 if ((int)$page->prevpageid === 0) {
529 $pageid = $page->id;
530 break;
531 }
532 }
4262a2f8 533 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
f521f98a 534
4262a2f8 535 if (!$pageid || !$pages) {
536 return null;
f521f98a 537 }
f521f98a 538
4262a2f8 539 $content = '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson')."</a>\n<div class=\"menuwrapper\">\n<ul>\n";
888f0c54 540
4262a2f8 541 while ($pageid != 0) {
542 $page = $pages[$pageid];
543
544 // Only process branch tables with display turned on
0a4abb73 545 if ($page->displayinmenublock && $page->display) {
86342d63 546 if ($page->id == $currentpageid) {
4262a2f8 547 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
548 } else {
549 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&amp;pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
550 }
86342d63 551
888f0c54 552 }
4262a2f8 553 $pageid = $page->nextpageid;
888f0c54 554 }
4262a2f8 555 $content .= "</ul>\n</div>\n";
888f0c54 556
4262a2f8 557 $bc = new block_contents();
558 $bc->title = get_string('lessonmenu', 'lesson');
6605ff8c 559 $bc->attributes['class'] = 'menu block';
4262a2f8 560 $bc->content = $content;
888f0c54 561
4262a2f8 562 return $bc;
448052a5
SH
563}
564
565/**
566 * Adds header buttons to the page for the lesson
567 *
568 * @param object $cm
569 * @param object $context
570 * @param bool $extraeditbuttons
571 * @param int $lessonpageid
572 */
573function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
574 global $CFG, $PAGE, $OUTPUT;
92059c7e
SH
575 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
576 if ($lessonpageid === null) {
577 print_error('invalidpageid', 'lesson');
578 }
579 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
32495414
MA
580 $url = new moodle_url('/mod/lesson/editpage.php', array(
581 'id' => $cm->id,
582 'pageid' => $lessonpageid,
583 'edit' => 1,
584 'returnto' => $PAGE->url->out(false)
585 ));
5c2ed7e2 586 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
448052a5 587 }
448052a5 588 }
5c2ed7e2 589}
9b56a34f
PS
590
591/**
592 * This is a function used to detect media types and generate html code.
593 *
594 * @global object $CFG
595 * @global object $PAGE
596 * @param object $lesson
597 * @param object $context
598 * @return string $code the html code of media
599 */
600function lesson_get_media_html($lesson, $context) {
601 global $CFG, $PAGE, $OUTPUT;
602 require_once("$CFG->libdir/resourcelib.php");
603
64f93798 604 // get the media file link
8d1a3963
PS
605 if (strpos($lesson->mediafile, '://') !== false) {
606 $url = new moodle_url($lesson->mediafile);
607 } else {
608 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
609 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
610 }
9b56a34f
PS
611 $title = $lesson->mediafile;
612
8d1a3963 613 $clicktoopen = html_writer::link($url, get_string('download'));
9b56a34f
PS
614
615 $mimetype = resourcelib_guess_url_mimetype($url);
616
fcd2cbaf
PS
617 $extension = resourcelib_get_extension($url->out(false));
618
8b7d95b6 619 $mediarenderer = $PAGE->get_renderer('core', 'media');
620 $embedoptions = array(
621 core_media::OPTION_TRUSTED => true,
622 core_media::OPTION_BLOCK => true
623 );
624
9b56a34f
PS
625 // find the correct type and print it out
626 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
627 $code = resourcelib_embed_image($url, $title);
628
8b7d95b6 629 } else if ($mediarenderer->can_embed_url($url, $embedoptions)) {
630 // Media (audio/video) file.
631 $code = $mediarenderer->embed_url($url, $title, 0, 0, $embedoptions);
9b56a34f
PS
632
633 } else {
634 // anything else - just try object tag enlarged as much as possible
635 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
636 }
637
638 return $code;
639}
1e7f8ea2 640
e0e1a83e
JMV
641/**
642 * Logic to happen when a/some group(s) has/have been deleted in a course.
643 *
644 * @param int $courseid The course ID.
247980b0 645 * @param int $groupid The group id if it is known
e0e1a83e
JMV
646 * @return void
647 */
247980b0 648function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
e0e1a83e
JMV
649 global $DB;
650
e0e1a83e 651 $params = array('courseid' => $courseid);
247980b0
JMV
652 if ($groupid) {
653 $params['groupid'] = $groupid;
654 // We just update the group that was deleted.
655 $sql = "SELECT o.id, o.lessonid
656 FROM {lesson_overrides} o
657 JOIN {lesson} lesson ON lesson.id = o.lessonid
658 WHERE lesson.course = :courseid
659 AND o.groupid = :groupid";
660 } else {
661 // No groupid, we update all orphaned group overrides for all lessons in course.
662 $sql = "SELECT o.id, o.lessonid
663 FROM {lesson_overrides} o
664 JOIN {lesson} lesson ON lesson.id = o.lessonid
665 LEFT JOIN {groups} grp ON grp.id = o.groupid
666 WHERE lesson.course = :courseid
667 AND o.groupid IS NOT NULL
668 AND grp.id IS NULL";
669 }
e0e1a83e
JMV
670 $records = $DB->get_records_sql_menu($sql, $params);
671 if (!$records) {
672 return; // Nothing to do.
673 }
674 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
675}
1e7f8ea2
PS
676
677/**
678 * Abstract class that page type's MUST inherit from.
679 *
680 * This is the abstract class that ALL add page type forms must extend.
681 * You will notice that all but two of the methods this class contains are final.
682 * Essentially the only thing that extending classes can do is extend custom_definition.
683 * OR if it has a special requirement on creation it can extend construction_override
684 *
685 * @abstract
cc3dbaaa
PS
686 * @copyright 2009 Sam Hemelryk
687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
688 */
689abstract class lesson_add_page_form_base extends moodleform {
690
691 /**
692 * This is the classic define that is used to identify this pagetype.
693 * Will be one of LESSON_*
694 * @var int
695 */
696 public $qtype;
697
698 /**
699 * The simple string that describes the page type e.g. truefalse, multichoice
700 * @var string
701 */
702 public $qtypestring;
703
704 /**
705 * An array of options used in the htmleditor
706 * @var array
707 */
708 protected $editoroptions = array();
709
710 /**
711 * True if this is a standard page of false if it does something special.
712 * Questions are standard pages, branch tables are not
713 * @var bool
714 */
715 protected $standard = true;
716
ceeab150
RT
717 /**
718 * Answer format supported by question type.
719 */
720 protected $answerformat = '';
721
722 /**
723 * Response format supported by question type.
724 */
725 protected $responseformat = '';
726
1e7f8ea2
PS
727 /**
728 * Each page type can and should override this to add any custom elements to
729 * the basic form that they want
730 */
731 public function custom_definition() {}
732
733 /**
ceeab150
RT
734 * Returns answer format used by question type.
735 */
736 public function get_answer_format() {
737 return $this->answerformat;
738 }
739
740 /**
741 * Returns response format used by question type.
742 */
743 public function get_response_format() {
744 return $this->responseformat;
745 }
746
747 /**
1e7f8ea2
PS
748 * Used to determine if this is a standard page or a special page
749 * @return bool
750 */
751 public final function is_standard() {
752 return (bool)$this->standard;
753 }
754
755 /**
756 * Add the required basic elements to the form.
757 *
758 * This method adds the basic elements to the form including title and contents
759 * and then calls custom_definition();
760 */
761 public final function definition() {
762 $mform = $this->_form;
763 $editoroptions = $this->_customdata['editoroptions'];
764
7f8ce025 765 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
1e7f8ea2 766
32495414
MA
767 if (!empty($this->_customdata['returnto'])) {
768 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
769 $mform->setType('returnto', PARAM_URL);
770 }
771
1e7f8ea2
PS
772 $mform->addElement('hidden', 'id');
773 $mform->setType('id', PARAM_INT);
774
775 $mform->addElement('hidden', 'pageid');
776 $mform->setType('pageid', PARAM_INT);
777
778 if ($this->standard === true) {
779 $mform->addElement('hidden', 'qtype');
05db3cc7 780 $mform->setType('qtype', PARAM_INT);
1e7f8ea2 781
3fa2f030 782 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1e7f8ea2 783 $mform->setType('title', PARAM_TEXT);
3fa2f030
PS
784 $mform->addRule('title', get_string('required'), 'required', null, 'client');
785
1e7f8ea2 786 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
3fa2f030
PS
787 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
788 $mform->setType('contents_editor', PARAM_RAW);
789 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1e7f8ea2
PS
790 }
791
792 $this->custom_definition();
793
794 if ($this->_customdata['edit'] === true) {
795 $mform->addElement('hidden', 'edit', 1);
747d5b1c 796 $mform->setType('edit', PARAM_BOOL);
3fa2f030 797 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
272bc0a6 798 } else if ($this->qtype === 'questiontype') {
3fa2f030 799 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
272bc0a6
RW
800 } else {
801 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1e7f8ea2
PS
802 }
803 }
804
805 /**
806 * Convenience function: Adds a jumpto select element
807 *
808 * @param string $name
809 * @param string|null $label
810 * @param int $selected The page to select by default
811 */
812 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
813 $title = get_string("jump", "lesson");
814 if ($label === null) {
815 $label = $title;
816 }
817 if (is_int($name)) {
818 $name = "jumpto[$name]";
819 }
820 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
821 $this->_form->setDefault($name, $selected);
822 $this->_form->addHelpButton($name, 'jumps', 'lesson');
823 }
824
825 /**
826 * Convenience function: Adds a score input element
827 *
828 * @param string $name
829 * @param string|null $label
830 * @param mixed $value The default value
831 */
832 protected final function add_score($name, $label=null, $value=null) {
833 if ($label === null) {
834 $label = get_string("score", "lesson");
835 }
a015bc03 836
1e7f8ea2
PS
837 if (is_int($name)) {
838 $name = "score[$name]";
839 }
840 $this->_form->addElement('text', $name, $label, array('size'=>5));
a015bc03 841 $this->_form->setType($name, PARAM_INT);
1e7f8ea2
PS
842 if ($value !== null) {
843 $this->_form->setDefault($name, $value);
844 }
20685b28
AG
845 $this->_form->addHelpButton($name, 'score', 'lesson');
846
847 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
848 if (!$this->_customdata['lesson']->custom) {
849 $this->_form->freeze($name);
850 }
1e7f8ea2
PS
851 }
852
853 /**
854 * Convenience function: Adds an answer editor
855 *
856 * @param int $count The count of the element to add
ecea65ca 857 * @param string $label, null means default
a675ada5 858 * @param bool $required
a1556aaf 859 * @param string $format
a675ada5 860 * @return void
1e7f8ea2 861 */
a1556aaf 862 protected final function add_answer($count, $label = null, $required = false, $format= '') {
ecea65ca 863 if ($label === null) {
a675ada5
PS
864 $label = get_string('answer', 'lesson');
865 }
0abc18cf 866
a1556aaf 867 if ($format == LESSON_ANSWER_HTML) {
0abc18cf
JMV
868 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
869 array('rows' => '4', 'columns' => '80'),
870 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
871 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
872 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
a1556aaf 873 } else {
a1300e98
JMV
874 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
875 array('size' => '50', 'maxlength' => '200'));
876 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
0abc18cf
JMV
877 }
878
a675ada5
PS
879 if ($required) {
880 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
881 }
1e7f8ea2
PS
882 }
883 /**
884 * Convenience function: Adds an response editor
885 *
886 * @param int $count The count of the element to add
ecea65ca 887 * @param string $label, null means default
a675ada5
PS
888 * @param bool $required
889 * @return void
1e7f8ea2 890 */
ecea65ca
RW
891 protected final function add_response($count, $label = null, $required = false) {
892 if ($label === null) {
a675ada5
PS
893 $label = get_string('response', 'lesson');
894 }
0abc18cf
JMV
895 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
896 array('rows' => '4', 'columns' => '80'),
897 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
898 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
899 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
900
a675ada5
PS
901 if ($required) {
902 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
903 }
1e7f8ea2
PS
904 }
905
906 /**
907 * A function that gets called upon init of this object by the calling script.
908 *
909 * This can be used to process an immediate action if required. Currently it
910 * is only used in special cases by non-standard page types.
911 *
912 * @return bool
913 */
0ed6f712 914 public function construction_override($pageid, lesson $lesson) {
1e7f8ea2
PS
915 return true;
916 }
917}
918
919
920
921/**
922 * Class representation of a lesson
923 *
924 * This class is used the interact with, and manage a lesson once instantiated.
925 * If you need to fetch a lesson object you can do so by calling
926 *
927 * <code>
928 * lesson::load($lessonid);
929 * // or
930 * $lessonrecord = $DB->get_record('lesson', $lessonid);
931 * $lesson = new lesson($lessonrecord);
932 * </code>
933 *
934 * The class itself extends lesson_base as all classes within the lesson module should
935 *
936 * These properties are from the database
937 * @property int $id The id of this lesson
938 * @property int $course The ID of the course this lesson belongs to
939 * @property string $name The name of this lesson
940 * @property int $practice Flag to toggle this as a practice lesson
941 * @property int $modattempts Toggle to allow the user to go back and review answers
942 * @property int $usepassword Toggle the use of a password for entry
943 * @property string $password The password to require users to enter
ff85f902 944 * @property int $dependency ID of another lesson this lesson is dependent on
1e7f8ea2
PS
945 * @property string $conditions Conditions of the lesson dependency
946 * @property int $grade The maximum grade a user can achieve (%)
947 * @property int $custom Toggle custom scoring on or off
948 * @property int $ongoing Toggle display of an ongoing score
949 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
950 * @property int $maxanswers The max number of answers or branches
951 * @property int $maxattempts The maximum number of attempts a user can record
952 * @property int $review Toggle use or wrong answer review button
953 * @property int $nextpagedefault Override the default next page
954 * @property int $feedback Toggles display of default feedback
955 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
956 * @property int $maxpages Maximum number of pages this lesson can contain
957 * @property int $retake Flag to allow users to retake a lesson
958 * @property int $activitylink Relate this lesson to another lesson
959 * @property string $mediafile File to pop up to or webpage to display
960 * @property int $mediaheight Sets the height of the media file popup
961 * @property int $mediawidth Sets the width of the media file popup
962 * @property int $mediaclose Toggle display of a media close button
963 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
964 * @property int $width Width of slideshow
965 * @property int $height Height of slideshow
966 * @property string $bgcolor Background colour of slideshow
ff85f902 967 * @property int $displayleft Display a left menu
1e7f8ea2
PS
968 * @property int $displayleftif Sets the condition on which the left menu is displayed
969 * @property int $progressbar Flag to toggle display of a lesson progress bar
970 * @property int $highscores Flag to toggle collection of high scores
971 * @property int $maxhighscores Number of high scores to limit to
972 * @property int $available Timestamp of when this lesson becomes available
973 * @property int $deadline Timestamp of when this lesson is no longer available
974 * @property int $timemodified Timestamp when lesson was last modified
975 *
976 * These properties are calculated
977 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
978 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
979 *
cc3dbaaa
PS
980 * @copyright 2009 Sam Hemelryk
981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
982 */
983class lesson extends lesson_base {
984
985 /**
986 * The id of the first page (where prevpageid = 0) gets set and retrieved by
987 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
988 * @var int
989 */
990 protected $firstpageid = null;
991 /**
992 * The id of the last page (where nextpageid = 0) gets set and retrieved by
993 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
994 * @var int
995 */
996 protected $lastpageid = null;
997 /**
998 * An array used to cache the pages associated with this lesson after the first
999 * time they have been loaded.
1000 * A note to developers: If you are going to be working with MORE than one or
1001 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1002 * in order to save excess database queries.
1003 * @var array An array of lesson_page objects
1004 */
1005 protected $pages = array();
1006 /**
1007 * Flag that gets set to true once all of the pages associated with the lesson
1008 * have been loaded.
1009 * @var bool
1010 */
1011 protected $loadedallpages = false;
1012
1013 /**
1014 * Simply generates a lesson object given an array/object of properties
1015 * Overrides {@see lesson_base->create()}
1016 * @static
1017 * @param object|array $properties
1018 * @return lesson
1019 */
1020 public static function create($properties) {
1021 return new lesson($properties);
1022 }
1023
1024 /**
1025 * Generates a lesson object from the database given its id
1026 * @static
1027 * @param int $lessonid
1028 * @return lesson
1029 */
1030 public static function load($lessonid) {
3983f2dc
PS
1031 global $DB;
1032
1e7f8ea2
PS
1033 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1034 print_error('invalidcoursemodule');
1035 }
1036 return new lesson($lesson);
1037 }
1038
1039 /**
1040 * Deletes this lesson from the database
1041 */
1042 public function delete() {
1043 global $CFG, $DB;
1044 require_once($CFG->libdir.'/gradelib.php');
1045 require_once($CFG->dirroot.'/calendar/lib.php');
1046
582ba677
FM
1047 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1048 $context = context_module::instance($cm->id);
1049
e0e1a83e
JMV
1050 $this->delete_all_overrides();
1051
0e35ba6f 1052 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1e7f8ea2
PS
1053 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1054 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1055 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1056 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1057 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1058 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1059 $DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
1060 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1061 foreach($events as $event) {
1062 $event = calendar_event::load($event);
1063 $event->delete();
1064 }
1065 }
1066
582ba677
FM
1067 // Delete files associated with this module.
1068 $fs = get_file_storage();
1069 $fs->delete_area_files($context->id);
1070
ecea65ca 1071 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1e7f8ea2
PS
1072 return true;
1073 }
1074
e0e1a83e
JMV
1075 /**
1076 * Deletes a lesson override from the database and clears any corresponding calendar events
1077 *
1078 * @param int $overrideid The id of the override being deleted
1079 * @return bool true on success
1080 */
1081 public function delete_override($overrideid) {
1082 global $CFG, $DB;
1083
1084 require_once($CFG->dirroot . '/calendar/lib.php');
1085
1086 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1087
1088 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1089
1090 // Delete the events.
1091 $conds = array('modulename' => 'lesson',
1092 'instance' => $this->properties->id);
1093 if (isset($override->userid)) {
1094 $conds['userid'] = $override->userid;
1095 } else {
1096 $conds['groupid'] = $override->groupid;
1097 }
1098 $events = $DB->get_records('event', $conds);
1099 foreach ($events as $event) {
1100 $eventold = calendar_event::load($event);
1101 $eventold->delete();
1102 }
1103
1104 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1105
1106 // Set the common parameters for one of the events we will be triggering.
1107 $params = array(
1108 'objectid' => $override->id,
1109 'context' => context_module::instance($cm->id),
1110 'other' => array(
1111 'lessonid' => $override->lessonid
1112 )
1113 );
1114 // Determine which override deleted event to fire.
1115 if (!empty($override->userid)) {
1116 $params['relateduserid'] = $override->userid;
1117 $event = \mod_lesson\event\user_override_deleted::create($params);
1118 } else {
1119 $params['other']['groupid'] = $override->groupid;
1120 $event = \mod_lesson\event\group_override_deleted::create($params);
1121 }
1122
1123 // Trigger the override deleted event.
1124 $event->add_record_snapshot('lesson_overrides', $override);
1125 $event->trigger();
1126
1127 return true;
1128 }
1129
1130 /**
1131 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1132 */
1133 public function delete_all_overrides() {
1134 global $DB;
1135
1136 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1137 foreach ($overrides as $override) {
1138 $this->delete_override($override->id);
1139 }
1140 }
1141
1142 /**
1143 * Updates the lesson properties with override information for a user.
1144 *
1145 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1146 * then use that otherwise, if there are group-specific overrides, return the most
1147 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1148 *
1149 * Special case: if there is more than one password that applies to the user, then
1150 * lesson->extrapasswords will contain an array of strings giving the remaining
1151 * passwords.
1152 *
1153 * @param int $userid The userid.
1154 */
1155 public function update_effective_access($userid) {
1156 global $DB;
1157
1158 // Check for user override.
1159 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1160
1161 if (!$override) {
1162 $override = new stdClass();
1163 $override->available = null;
1164 $override->deadline = null;
1165 $override->timelimit = null;
1166 $override->review = null;
1167 $override->maxattempts = null;
1168 $override->retake = null;
1169 $override->password = null;
1170 }
1171
1172 // Check for group overrides.
1173 $groupings = groups_get_user_groups($this->properties->course, $userid);
1174
1175 if (!empty($groupings[0])) {
1176 // Select all overrides that apply to the User's groups.
1177 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1178 $sql = "SELECT * FROM {lesson_overrides}
1179 WHERE groupid $extra AND lessonid = ?";
1180 $params[] = $this->properties->id;
1181 $records = $DB->get_records_sql($sql, $params);
1182
1183 // Combine the overrides.
1184 $availables = array();
1185 $deadlines = array();
1186 $timelimits = array();
1187 $reviews = array();
1188 $attempts = array();
1189 $retakes = array();
1190 $passwords = array();
1191
1192 foreach ($records as $gpoverride) {
1193 if (isset($gpoverride->available)) {
1194 $availables[] = $gpoverride->available;
1195 }
1196 if (isset($gpoverride->deadline)) {
1197 $deadlines[] = $gpoverride->deadline;
1198 }
1199 if (isset($gpoverride->timelimit)) {
1200 $timelimits[] = $gpoverride->timelimit;
1201 }
1202 if (isset($gpoverride->review)) {
1203 $reviews[] = $gpoverride->review;
1204 }
1205 if (isset($gpoverride->maxattempts)) {
1206 $attempts[] = $gpoverride->maxattempts;
1207 }
1208 if (isset($gpoverride->retake)) {
1209 $retakes[] = $gpoverride->retake;
1210 }
1211 if (isset($gpoverride->password)) {
1212 $passwords[] = $gpoverride->password;
1213 }
1214 }
1215 // If there is a user override for a setting, ignore the group override.
1216 if (is_null($override->available) && count($availables)) {
1217 $override->available = min($availables);
1218 }
1219 if (is_null($override->deadline) && count($deadlines)) {
1220 if (in_array(0, $deadlines)) {
1221 $override->deadline = 0;
1222 } else {
1223 $override->deadline = max($deadlines);
1224 }
1225 }
1226 if (is_null($override->timelimit) && count($timelimits)) {
1227 if (in_array(0, $timelimits)) {
1228 $override->timelimit = 0;
1229 } else {
1230 $override->timelimit = max($timelimits);
1231 }
1232 }
1233 if (is_null($override->review) && count($reviews)) {
1234 $override->review = max($reviews);
1235 }
1236 if (is_null($override->maxattempts) && count($attempts)) {
1237 $override->maxattempts = max($attempts);
1238 }
1239 if (is_null($override->retake) && count($retakes)) {
1240 $override->retake = max($retakes);
1241 }
1242 if (is_null($override->password) && count($passwords)) {
1243 $override->password = array_shift($passwords);
1244 if (count($passwords)) {
1245 $override->extrapasswords = $passwords;
1246 }
1247 }
1248
1249 }
1250
1251 // Merge with lesson defaults.
1252 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1253 foreach ($keys as $key) {
1254 if (isset($override->{$key})) {
1255 $this->properties->{$key} = $override->{$key};
1256 }
1257 }
1258
1259 // Special handling of lesson usepassword and password.
1260 if (isset($override->password)) {
1261 if ($override->password == '') {
1262 $this->properties->usepassword = 0;
1263 } else {
1264 $this->properties->usepassword = 1;
1265 $this->properties->password = $override->password;
1266 if (isset($override->extrapasswords)) {
1267 $this->properties->extrapasswords = $override->extrapasswords;
1268 }
1269 }
1270 }
1271 }
1272
1e7f8ea2
PS
1273 /**
1274 * Fetches messages from the session that may have been set in previous page
1275 * actions.
1276 *
1277 * <code>
1278 * // Do not call this method directly instead use
1279 * $lesson->messages;
1280 * </code>
1281 *
1282 * @return array
1283 */
1284 protected function get_messages() {
1285 global $SESSION;
1286
1287 $messages = array();
1288 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1289 $messages = $SESSION->lesson_messages[$this->properties->id];
1290 unset($SESSION->lesson_messages[$this->properties->id]);
1291 }
1292
1293 return $messages;
1294 }
1295
1296 /**
1297 * Get all of the attempts for the current user.
1298 *
1299 * @param int $retries
1300 * @param bool $correct Optional: only fetch correct attempts
1301 * @param int $pageid Optional: only fetch attempts at the given page
1302 * @param int $userid Optional: defaults to the current user if not set
1303 * @return array|false
1304 */
1305 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1306 global $USER, $DB;
1307 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1308 if ($correct) {
1309 $params['correct'] = 1;
1310 }
1311 if ($pageid !== null) {
1312 $params['pageid'] = $pageid;
1313 }
1314 if ($userid === null) {
1315 $params['userid'] = $USER->id;
1316 }
ef4ba975 1317 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1e7f8ea2
PS
1318 }
1319
1320 /**
1321 * Returns the first page for the lesson or false if there isn't one.
1322 *
1323 * This method should be called via the magic method __get();
1324 * <code>
1325 * $firstpage = $lesson->firstpage;
1326 * </code>
1327 *
1328 * @return lesson_page|bool Returns the lesson_page specialised object or false
1329 */
1330 protected function get_firstpage() {
1331 $pages = $this->load_all_pages();
1332 if (count($pages) > 0) {
1333 foreach ($pages as $page) {
1334 if ((int)$page->prevpageid === 0) {
1335 return $page;
1336 }
1337 }
1338 }
1339 return false;
1340 }
1341
1342 /**
1343 * Returns the last page for the lesson or false if there isn't one.
1344 *
1345 * This method should be called via the magic method __get();
1346 * <code>
1347 * $lastpage = $lesson->lastpage;
1348 * </code>
1349 *
1350 * @return lesson_page|bool Returns the lesson_page specialised object or false
1351 */
1352 protected function get_lastpage() {
1353 $pages = $this->load_all_pages();
1354 if (count($pages) > 0) {
1355 foreach ($pages as $page) {
1356 if ((int)$page->nextpageid === 0) {
1357 return $page;
1358 }
1359 }
1360 }
1361 return false;
1362 }
1363
1364 /**
1365 * Returns the id of the first page of this lesson. (prevpageid = 0)
1366 * @return int
1367 */
1368 protected function get_firstpageid() {
1369 global $DB;
1370 if ($this->firstpageid == null) {
1371 if (!$this->loadedallpages) {
1372 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1373 if (!$firstpageid) {
1374 print_error('cannotfindfirstpage', 'lesson');
1375 }
1376 $this->firstpageid = $firstpageid;
1377 } else {
1378 $firstpage = $this->get_firstpage();
1379 $this->firstpageid = $firstpage->id;
1380 }
1381 }
1382 return $this->firstpageid;
1383 }
1384
1385 /**
1386 * Returns the id of the last page of this lesson. (nextpageid = 0)
1387 * @return int
1388 */
1389 public function get_lastpageid() {
1390 global $DB;
1391 if ($this->lastpageid == null) {
1392 if (!$this->loadedallpages) {
1393 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1394 if (!$lastpageid) {
1395 print_error('cannotfindlastpage', 'lesson');
1396 }
1397 $this->lastpageid = $lastpageid;
1398 } else {
1399 $lastpageid = $this->get_lastpage();
1400 $this->lastpageid = $lastpageid->id;
1401 }
1402 }
1403
1404 return $this->lastpageid;
1405 }
1406
1407 /**
0343553f 1408 * Gets the next page id to display after the one that is provided.
1e7f8ea2
PS
1409 * @param int $nextpageid
1410 * @return bool
1411 */
1412 public function get_next_page($nextpageid) {
3983f2dc 1413 global $USER, $DB;
1e7f8ea2
PS
1414 $allpages = $this->load_all_pages();
1415 if ($this->properties->nextpagedefault) {
1416 // in Flash Card mode...first get number of retakes
0343553f 1417 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1e7f8ea2
PS
1418 shuffle($allpages);
1419 $found = false;
1420 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1421 foreach ($allpages as $nextpage) {
0343553f 1422 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1e7f8ea2
PS
1423 $found = true;
1424 break;
1425 }
1426 }
1427 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1428 foreach ($allpages as $nextpage) {
0343553f 1429 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1e7f8ea2
PS
1430 $found = true;
1431 break;
1432 }
1433 }
1434 }
1435 if ($found) {
1436 if ($this->properties->maxpages) {
1437 // check number of pages viewed (in the lesson)
0343553f
RW
1438 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1439 return LESSON_EOL;
1e7f8ea2
PS
1440 }
1441 }
0343553f 1442 return $nextpage->id;
1e7f8ea2
PS
1443 }
1444 }
1445 // In a normal lesson mode
1446 foreach ($allpages as $nextpage) {
0343553f
RW
1447 if ((int)$nextpage->id === (int)$nextpageid) {
1448 return $nextpage->id;
1e7f8ea2
PS
1449 }
1450 }
0343553f 1451 return LESSON_EOL;
1e7f8ea2
PS
1452 }
1453
1454 /**
1455 * Sets a message against the session for this lesson that will displayed next
1456 * time the lesson processes messages
1457 *
1458 * @param string $message
1459 * @param string $class
1460 * @param string $align
1461 * @return bool
1462 */
1463 public function add_message($message, $class="notifyproblem", $align='center') {
1464 global $SESSION;
1465
1466 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1467 $SESSION->lesson_messages = array();
1468 $SESSION->lesson_messages[$this->properties->id] = array();
1469 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1470 $SESSION->lesson_messages[$this->properties->id] = array();
1471 }
1472
1473 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1474
1475 return true;
1476 }
1477
1478 /**
1479 * Check if the lesson is accessible at the present time
1480 * @return bool True if the lesson is accessible, false otherwise
1481 */
1482 public function is_accessible() {
1483 $available = $this->properties->available;
1484 $deadline = $this->properties->deadline;
1485 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1486 }
1487
1488 /**
1489 * Starts the lesson time for the current user
1490 * @return bool Returns true
1491 */
1492 public function start_timer() {
1493 global $USER, $DB;
9c192d81
MN
1494
1495 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1496 false, MUST_EXIST);
1497
1498 // Trigger lesson started event.
1499 $event = \mod_lesson\event\lesson_started::create(array(
1500 'objectid' => $this->properties()->id,
1501 'context' => context_module::instance($cm->id),
1502 'courseid' => $this->properties()->course
1503 ));
1504 $event->trigger();
1505
1e7f8ea2
PS
1506 $USER->startlesson[$this->properties->id] = true;
1507 $startlesson = new stdClass;
1508 $startlesson->lessonid = $this->properties->id;
1509 $startlesson->userid = $USER->id;
1510 $startlesson->starttime = time();
1511 $startlesson->lessontime = time();
1512 $DB->insert_record('lesson_timer', $startlesson);
a1acc001
JMV
1513 if ($this->properties->timelimit) {
1514 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
1e7f8ea2
PS
1515 }
1516 return true;
1517 }
1518
1519 /**
1520 * Updates the timer to the current time and returns the new timer object
1521 * @param bool $restart If set to true the timer is restarted
1522 * @param bool $continue If set to true AND $restart=true then the timer
1523 * will continue from a previous attempt
1524 * @return stdClass The new timer
1525 */
25345cb4 1526 public function update_timer($restart=false, $continue=false, $endreached =false) {
1e7f8ea2 1527 global $USER, $DB;
e0f7b963
SB
1528
1529 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1530
1e7f8ea2
PS
1531 // clock code
1532 // get time information for this user
5ca2e765
JMV
1533 $params = array("lessonid" => $this->properties->id, "userid" => $USER->id);
1534 if (!$timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1)) {
1535 $this->start_timer();
1536 $timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1);
1e7f8ea2 1537 }
5ca2e765 1538 $timer = current($timer); // This will get the latest start time record.
1e7f8ea2
PS
1539
1540 if ($restart) {
1541 if ($continue) {
1542 // continue a previous test, need to update the clock (think this option is disabled atm)
1543 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
e0f7b963
SB
1544
1545 // Trigger lesson resumed event.
1546 $event = \mod_lesson\event\lesson_resumed::create(array(
1547 'objectid' => $this->properties->id,
1548 'context' => context_module::instance($cm->id),
1549 'courseid' => $this->properties->course
1550 ));
1551 $event->trigger();
1552
1e7f8ea2
PS
1553 } else {
1554 // starting over, so reset the clock
1555 $timer->starttime = time();
e0f7b963
SB
1556
1557 // Trigger lesson restarted event.
1558 $event = \mod_lesson\event\lesson_restarted::create(array(
1559 'objectid' => $this->properties->id,
1560 'context' => context_module::instance($cm->id),
1561 'courseid' => $this->properties->course
1562 ));
1563 $event->trigger();
1564
1e7f8ea2
PS
1565 }
1566 }
1567
1568 $timer->lessontime = time();
25345cb4 1569 $timer->completed = $endreached;
1e7f8ea2 1570 $DB->update_record('lesson_timer', $timer);
4b570f71
JMV
1571
1572 // Update completion state.
1573 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1574 false, MUST_EXIST);
1575 $course = get_course($cm->course);
1576 $completion = new completion_info($course);
1577 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
1578 $completion->update_state($cm, COMPLETION_COMPLETE);
1579 }
1e7f8ea2
PS
1580 return $timer;
1581 }
1582
1583 /**
1584 * Updates the timer to the current time then stops it by unsetting the user var
1585 * @return bool Returns true
1586 */
1587 public function stop_timer() {
1588 global $USER, $DB;
1589 unset($USER->startlesson[$this->properties->id]);
00c027c7
MN
1590
1591 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1592 false, MUST_EXIST);
1593
1594 // Trigger lesson ended event.
1595 $event = \mod_lesson\event\lesson_ended::create(array(
1596 'objectid' => $this->properties()->id,
1597 'context' => context_module::instance($cm->id),
1598 'courseid' => $this->properties()->course
1599 ));
1600 $event->trigger();
1601
25345cb4 1602 return $this->update_timer(false, false, true);
1e7f8ea2
PS
1603 }
1604
1605 /**
1606 * Checks to see if the lesson has pages
1607 */
1608 public function has_pages() {
1609 global $DB;
1610 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1611 return ($pagecount>0);
1612 }
1613
1614 /**
1615 * Returns the link for the related activity
1616 * @return array|false
1617 */
1618 public function link_for_activitylink() {
1619 global $DB;
1620 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1621 if ($module) {
1622 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1623 if ($modname) {
1624 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1625 if ($instancename) {
1626 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
560f5495 1627 get_string('activitylinkname', 'lesson', $instancename),
1e7f8ea2
PS
1628 array('class'=>'centerpadded lessonbutton standardbutton'));
1629 }
1630 }
1631 }
1632 return '';
1633 }
1634
1635 /**
1636 * Loads the requested page.
1637 *
1638 * This function will return the requested page id as either a specialised
1639 * lesson_page object OR as a generic lesson_page.
1640 * If the page has been loaded previously it will be returned from the pages
1641 * array, otherwise it will be loaded from the database first
1642 *
1643 * @param int $pageid
1644 * @return lesson_page A lesson_page object or an object that extends it
1645 */
1646 public function load_page($pageid) {
1647 if (!array_key_exists($pageid, $this->pages)) {
1648 $manager = lesson_page_type_manager::get($this);
1649 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1650 }
1651 return $this->pages[$pageid];
1652 }
1653
1654 /**
1655 * Loads ALL of the pages for this lesson
1656 *
1657 * @return array An array containing all pages from this lesson
1658 */
1659 public function load_all_pages() {
1660 if (!$this->loadedallpages) {
1661 $manager = lesson_page_type_manager::get($this);
1662 $this->pages = $manager->load_all_pages($this);
1663 $this->loadedallpages = true;
1664 }
1665 return $this->pages;
1666 }
1667
1668 /**
ff85f902 1669 * Determines if a jumpto value is correct or not.
1e7f8ea2
PS
1670 *
1671 * returns true if jumpto page is (logically) after the pageid page or
1672 * if the jumpto value is a special value. Returns false in all other cases.
1673 *
1674 * @param int $pageid Id of the page from which you are jumping from.
1675 * @param int $jumpto The jumpto number.
1676 * @return boolean True or false after a series of tests.
1677 **/
1678 public function jumpto_is_correct($pageid, $jumpto) {
1679 global $DB;
1680
1681 // first test the special values
1682 if (!$jumpto) {
1683 // same page
1684 return false;
1685 } elseif ($jumpto == LESSON_NEXTPAGE) {
1686 return true;
1687 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1688 return true;
1689 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1690 return true;
1691 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1692 return true;
1693 } elseif ($jumpto == LESSON_EOL) {
1694 return true;
1695 }
1696
1697 $pages = $this->load_all_pages();
1698 $apageid = $pages[$pageid]->nextpageid;
1699 while ($apageid != 0) {
1700 if ($jumpto == $apageid) {
1701 return true;
1702 }
1703 $apageid = $pages[$apageid]->nextpageid;
1704 }
1705 return false;
1706 }
1707
1708 /**
1709 * Returns the time a user has remaining on this lesson
1710 * @param int $starttime Starttime timestamp
1711 * @return string
1712 */
1713 public function time_remaining($starttime) {
e0e1a83e 1714 $timeleft = $starttime + $this->properties->timelimit - time();
1e7f8ea2
PS
1715 $hours = floor($timeleft/3600);
1716 $timeleft = $timeleft - ($hours * 3600);
1717 $minutes = floor($timeleft/60);
1718 $secs = $timeleft - ($minutes * 60);
1719
1720 if ($minutes < 10) {
1721 $minutes = "0$minutes";
1722 }
1723 if ($secs < 10) {
1724 $secs = "0$secs";
1725 }
1726 $output = array();
1727 $output[] = $hours;
1728 $output[] = $minutes;
1729 $output[] = $secs;
1730 $output = implode(':', $output);
1731 return $output;
1732 }
1733
1734 /**
1735 * Interprets LESSON_CLUSTERJUMP jumpto value.
1736 *
1737 * This will select a page randomly
ff85f902 1738 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1e7f8ea2
PS
1739 * and the page selected will be a page that has not been viewed already
1740 * and if any pages are within a branch table or end of branch then only 1 page within
1741 * the branch table or end of branch will be randomly selected (sub clustering).
1742 *
1743 * @param int $pageid Id of the current page from which we are jumping from.
1744 * @param int $userid Id of the user.
1745 * @return int The id of the next page.
1746 **/
1747 public function cluster_jump($pageid, $userid=null) {
1748 global $DB, $USER;
1749
1750 if ($userid===null) {
1751 $userid = $USER->id;
1752 }
1753 // get the number of retakes
1754 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1755 $retakes = 0;
1756 }
1757 // get all the lesson_attempts aka what the user has seen
1758 $seenpages = array();
1759 if ($attempts = $this->get_attempts($retakes)) {
1760 foreach ($attempts as $attempt) {
1761 $seenpages[$attempt->pageid] = $attempt->pageid;
1762 }
1763
1764 }
1765
1766 // get the lesson pages
1767 $lessonpages = $this->load_all_pages();
1768 // find the start of the cluster
1769 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1770 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1771 break;
1772 }
1773 $pageid = $lessonpages[$pageid]->prevpageid;
1774 }
1775
1776 $clusterpages = array();
1777 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1778 $unseen = array();
1779 foreach ($clusterpages as $key=>$cluster) {
fc16a1ac
JMV
1780 // Remove the page if it is in a branch table or is an endofbranch.
1781 if ($this->is_sub_page_of_type($cluster->id,
1782 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
1783 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1e7f8ea2 1784 unset($clusterpages[$key]);
fc16a1ac
JMV
1785 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
1786 // If branchtable, check to see if any pages inside have been viewed.
1787 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1788 $flag = true;
1789 foreach ($branchpages as $branchpage) {
1790 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
1791 $flag = false;
1792 }
1793 }
1794 if ($flag && count($branchpages) > 0) {
1795 // Add branch table.
1796 $unseen[] = $cluster;
1797 }
1e7f8ea2
PS
1798 } elseif ($cluster->is_unseen($seenpages)) {
1799 $unseen[] = $cluster;
1800 }
1801 }
1802
1803 if (count($unseen) > 0) {
1804 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1805 $nextpage = $unseen[rand(0, count($unseen)-1)];
1806 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1807 // if branch table, then pick a random page inside of it
1808 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1809 return $branchpages[rand(0, count($branchpages)-1)]->id;
1810 } else { // otherwise, return the page's id
1811 return $nextpage->id;
1812 }
1813 } else {
1814 // seen all there is to see, leave the cluster
1815 if (end($clusterpages)->nextpageid == 0) {
1816 return LESSON_EOL;
1817 } else {
1818 $clusterendid = $pageid;
a30e935a
JMV
1819 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
1820 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1e7f8ea2
PS
1821 break;
1822 }
a30e935a 1823 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1e7f8ea2
PS
1824 }
1825 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1826 if ($exitjump == LESSON_NEXTPAGE) {
a30e935a 1827 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1e7f8ea2
PS
1828 }
1829 if ($exitjump == 0) {
1830 return LESSON_EOL;
1831 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1832 return $exitjump;
1833 } else {
1834 if (!array_key_exists($exitjump, $lessonpages)) {
1835 $found = false;
1836 foreach ($lessonpages as $page) {
1837 if ($page->id === $clusterendid) {
1838 $found = true;
1839 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1840 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
0d4705c7
JMV
1841 if ($exitjump == LESSON_NEXTPAGE) {
1842 $exitjump = $lessonpages[$page->id]->nextpageid;
1843 }
1e7f8ea2
PS
1844 break;
1845 }
1846 }
1847 }
1848 if (!array_key_exists($exitjump, $lessonpages)) {
1849 return LESSON_EOL;
1850 }
1851 return $exitjump;
1852 }
1853 }
1854 }
1855 }
1856
1857 /**
1858 * Finds all pages that appear to be a subtype of the provided pageid until
1859 * an end point specified within $ends is encountered or no more pages exist
1860 *
1861 * @param int $pageid
1862 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1863 * the subtype
1864 * @return array An array of specialised lesson_page objects
1865 */
1866 public function get_sub_pages_of($pageid, array $ends) {
1867 $lessonpages = $this->load_all_pages();
1868 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1869 $pages = array();
1870
1871 while (true) {
1872 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1873 break;
1874 }
1875 $pages[] = $lessonpages[$pageid];
1876 $pageid = $lessonpages[$pageid]->nextpageid;
1877 }
1878
1879 return $pages;
1880 }
1881
1882 /**
1883 * Checks to see if the specified page[id] is a subpage of a type specified in
1884 * the $types array, until either there are no more pages of we find a type
ff85f902 1885 * corresponding to that of a type specified in $ends
1e7f8ea2
PS
1886 *
1887 * @param int $pageid The id of the page to check
1888 * @param array $types An array of types that would signify this page was a subpage
1889 * @param array $ends An array of types that mean this is not a subpage
1890 * @return bool
1891 */
1892 public function is_sub_page_of_type($pageid, array $types, array $ends) {
1893 $pages = $this->load_all_pages();
1894 $pageid = $pages[$pageid]->prevpageid; // move up one
1895
1896 array_unshift($ends, 0);
1897 // go up the pages till branch table
1898 while (true) {
1899 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
1900 return false;
1901 } else if (in_array($pages[$pageid]->qtype, $types)) {
1902 return true;
1903 }
1904 $pageid = $pages[$pageid]->prevpageid;
1905 }
1906 }
b7bfbfee
DM
1907
1908 /**
1909 * Move a page resorting all other pages.
1910 *
1911 * @param int $pageid
1912 * @param int $after
1913 * @return void
1914 */
1915 public function resort_pages($pageid, $after) {
1916 global $CFG;
1917
1918 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1919 $context = context_module::instance($cm->id);
1920
1921 $pages = $this->load_all_pages();
1922
1923 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
1924 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
1925 }
1926
1927 $pagetomove = clone($pages[$pageid]);
1928 unset($pages[$pageid]);
1929
1930 $pageids = array();
1931 if ($after === 0) {
1932 $pageids['p0'] = $pageid;
1933 }
1934 foreach ($pages as $page) {
1935 $pageids[] = $page->id;
1936 if ($page->id == $after) {
1937 $pageids[] = $pageid;
1938 }
1939 }
1940
1941 $pageidsref = $pageids;
1942 reset($pageidsref);
1943 $prev = 0;
1944 $next = next($pageidsref);
1945 foreach ($pageids as $pid) {
1946 if ($pid === $pageid) {
1947 $page = $pagetomove;
1948 } else {
1949 $page = $pages[$pid];
1950 }
1951 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
1952 $page->move($next, $prev);
1953
1954 if ($pid === $pageid) {
1955 // We will trigger an event.
1956 $pageupdated = array('next' => $next, 'prev' => $prev);
1957 }
1958 }
1959
1960 $prev = $page->id;
1961 $next = next($pageidsref);
1962 if (!$next) {
1963 $next = 0;
1964 }
1965 }
1966
1967 // Trigger an event: page moved.
1968 if (!empty($pageupdated)) {
1969 $eventparams = array(
1970 'context' => $context,
1971 'objectid' => $pageid,
1972 'other' => array(
1973 'pagetype' => $page->get_typestring(),
1974 'prevpageid' => $pageupdated['prev'],
1975 'nextpageid' => $pageupdated['next']
1976 )
1977 );
1978 $event = \mod_lesson\event\page_moved::create($eventparams);
1979 $event->trigger();
1980 }
1981
1982 }
1e7f8ea2
PS
1983}
1984
1985
1986/**
1987 * Abstract class to provide a core functions to the all lesson classes
1988 *
1989 * This class should be abstracted by ALL classes with the lesson module to ensure
1990 * that all classes within this module can be interacted with in the same way.
1991 *
1992 * This class provides the user with a basic properties array that can be fetched
ff85f902 1993 * or set via magic methods, or alternatively by defining methods get_blah() or
1e7f8ea2
PS
1994 * set_blah() within the extending object.
1995 *
cc3dbaaa
PS
1996 * @copyright 2009 Sam Hemelryk
1997 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
1998 */
1999abstract class lesson_base {
2000
2001 /**
2002 * An object containing properties
2003 * @var stdClass
2004 */
2005 protected $properties;
2006
2007 /**
2008 * The constructor
2009 * @param stdClass $properties
2010 */
2011 public function __construct($properties) {
2012 $this->properties = (object)$properties;
2013 }
2014
2015 /**
2016 * Magic property method
2017 *
2018 * Attempts to call a set_$key method if one exists otherwise falls back
2019 * to simply set the property
2020 *
2021 * @param string $key
2022 * @param mixed $value
2023 */
2024 public function __set($key, $value) {
2025 if (method_exists($this, 'set_'.$key)) {
2026 $this->{'set_'.$key}($value);
2027 }
2028 $this->properties->{$key} = $value;
2029 }
2030
2031 /**
2032 * Magic get method
2033 *
2034 * Attempts to call a get_$key method to return the property and ralls over
2035 * to return the raw property
2036 *
2037 * @param str $key
2038 * @return mixed
2039 */
2040 public function __get($key) {
2041 if (method_exists($this, 'get_'.$key)) {
2042 return $this->{'get_'.$key}();
2043 }
2044 return $this->properties->{$key};
2045 }
2046
2047 /**
2048 * Stupid PHP needs an isset magic method if you use the get magic method and
2049 * still want empty calls to work.... blah ~!
2050 *
2051 * @param string $key
2052 * @return bool
2053 */
2054 public function __isset($key) {
2055 if (method_exists($this, 'get_'.$key)) {
2056 $val = $this->{'get_'.$key}();
2057 return !empty($val);
2058 }
2059 return !empty($this->properties->{$key});
2060 }
2061
0ed6f712
PS
2062 //NOTE: E_STRICT does not allow to change function signature!
2063
1e7f8ea2 2064 /**
0ed6f712 2065 * If implemented should create a new instance, save it in the DB and return it
1e7f8ea2 2066 */
0ed6f712 2067 //public static function create() {}
1e7f8ea2 2068 /**
0ed6f712 2069 * If implemented should load an instance from the DB and return it
1e7f8ea2 2070 */
0ed6f712 2071 //public static function load() {}
1e7f8ea2
PS
2072 /**
2073 * Fetches all of the properties of the object
2074 * @return stdClass
2075 */
2076 public function properties() {
2077 return $this->properties;
2078 }
2079}
2080
2081
2082/**
2083 * Abstract class representation of a page associated with a lesson.
2084 *
2085 * This class should MUST be extended by all specialised page types defined in
2086 * mod/lesson/pagetypes/.
2087 * There are a handful of abstract methods that need to be defined as well as
2088 * severl methods that can optionally be defined in order to make the page type
2089 * operate in the desired way
2090 *
2091 * Database properties
2092 * @property int $id The id of this lesson page
2093 * @property int $lessonid The id of the lesson this page belongs to
2094 * @property int $prevpageid The id of the page before this one
2095 * @property int $nextpageid The id of the next page in the page sequence
2096 * @property int $qtype Identifies the page type of this page
2097 * @property int $qoption Used to record page type specific options
2098 * @property int $layout Used to record page specific layout selections
2099 * @property int $display Used to record page specific display selections
2100 * @property int $timecreated Timestamp for when the page was created
2101 * @property int $timemodified Timestamp for when the page was last modified
2102 * @property string $title The title of this page
2103 * @property string $contents The rich content shown to describe the page
2104 * @property int $contentsformat The format of the contents field
2105 *
2106 * Calculated properties
2107 * @property-read array $answers An array of answers for this page
2108 * @property-read bool $displayinmenublock Toggles display in the left menu block
2109 * @property-read array $jumps An array containing all the jumps this page uses
2110 * @property-read lesson $lesson The lesson this page belongs to
2111 * @property-read int $type The type of the page [question | structure]
2112 * @property-read typeid The unique identifier for the page type
2113 * @property-read typestring The string that describes this page type
2114 *
2115 * @abstract
cc3dbaaa
PS
2116 * @copyright 2009 Sam Hemelryk
2117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
2118 */
2119abstract class lesson_page extends lesson_base {
2120
2121 /**
2122 * A reference to the lesson this page belongs to
2123 * @var lesson
2124 */
2125 protected $lesson = null;
2126 /**
2127 * Contains the answers to this lesson_page once loaded
2128 * @var null|array
2129 */
2130 protected $answers = null;
2131 /**
2132 * This sets the type of the page, can be one of the constants defined below
2133 * @var int
2134 */
2135 protected $type = 0;
2136
2137 /**
2138 * Constants used to identify the type of the page
2139 */
2140 const TYPE_QUESTION = 0;
2141 const TYPE_STRUCTURE = 1;
2142
2143 /**
2144 * This method should return the integer used to identify the page type within
ff85f902 2145 * the database and throughout code. This maps back to the defines used in 1.x
1e7f8ea2
PS
2146 * @abstract
2147 * @return int
2148 */
2149 abstract protected function get_typeid();
2150 /**
2151 * This method should return the string that describes the pagetype
2152 * @abstract
2153 * @return string
2154 */
2155 abstract protected function get_typestring();
2156
2157 /**
2158 * This method gets called to display the page to the user taking the lesson
2159 * @abstract
2160 * @param object $renderer
2161 * @param object $attempt
2162 * @return string
2163 */
2164 abstract public function display($renderer, $attempt);
2165
2166 /**
2167 * Creates a new lesson_page within the database and returns the correct pagetype
2168 * object to use to interact with the new lesson
2169 *
2170 * @final
2171 * @static
2172 * @param object $properties
2173 * @param lesson $lesson
2174 * @return lesson_page Specialised object that extends lesson_page
2175 */
2176 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
2177 global $DB;
2178 $newpage = new stdClass;
2179 $newpage->title = $properties->title;
2180 $newpage->contents = $properties->contents_editor['text'];
2181 $newpage->contentsformat = $properties->contents_editor['format'];
2182 $newpage->lessonid = $lesson->id;
2183 $newpage->timecreated = time();
2184 $newpage->qtype = $properties->qtype;
2185 $newpage->qoption = (isset($properties->qoption))?1:0;
2186 $newpage->layout = (isset($properties->layout))?1:0;
2187 $newpage->display = (isset($properties->display))?1:0;
2188 $newpage->prevpageid = 0; // this is a first page
2189 $newpage->nextpageid = 0; // this is the only page
2190
2191 if ($properties->pageid) {
2192 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
2193 if (!$prevpage) {
2194 print_error('cannotfindpages', 'lesson');
2195 }
2196 $newpage->prevpageid = $prevpage->id;
2197 $newpage->nextpageid = $prevpage->nextpageid;
2198 } else {
2199 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
2200 if ($nextpage) {
2201 // This is the first page, there are existing pages put this at the start
2202 $newpage->nextpageid = $nextpage->id;
2203 }
2204 }
2205
2206 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
2207
2208 $editor = new stdClass;
2209 $editor->id = $newpage->id;
2210 $editor->contents_editor = $properties->contents_editor;
2211 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
2212 $DB->update_record("lesson_pages", $editor);
2213
2214 if ($newpage->prevpageid > 0) {
2215 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
2216 }
2217 if ($newpage->nextpageid > 0) {
2218 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
2219 }
2220
2221 $page = lesson_page::load($newpage, $lesson);
2222 $page->create_answers($properties);
2223
1cf8ca34
SB
2224 // Trigger an event: page created.
2225 $eventparams = array(
2226 'context' => $context,
2227 'objectid' => $newpage->id,
2228 'other' => array(
2229 'pagetype' => $page->get_typestring()
2230 )
2231 );
2232 $event = \mod_lesson\event\page_created::create($eventparams);
2233 $snapshot = clone($newpage);
2234 $snapshot->timemodified = 0;
2235 $event->add_record_snapshot('lesson_pages', $snapshot);
2236 $event->trigger();
2237
1e7f8ea2
PS
2238 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
2239
2240 return $page;
2241 }
2242
2243 /**
2244 * This method loads a page object from the database and returns it as a
2245 * specialised object that extends lesson_page
2246 *
2247 * @final
2248 * @static
2249 * @param int $id
2250 * @param lesson $lesson
2251 * @return lesson_page Specialised lesson_page object
2252 */
2253 final public static function load($id, lesson $lesson) {
2254 global $DB;
2255
2256 if (is_object($id) && !empty($id->qtype)) {
2257 $page = $id;
2258 } else {
2259 $page = $DB->get_record("lesson_pages", array("id" => $id));
2260 if (!$page) {
2261 print_error('cannotfindpages', 'lesson');
2262 }
2263 }
2264 $manager = lesson_page_type_manager::get($lesson);
2265
2266 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
2267 if (!class_exists($class)) {
2268 $class = 'lesson_page';
2269 }
2270
2271 return new $class($page, $lesson);
2272 }
2273
2274 /**
2275 * Deletes a lesson_page from the database as well as any associated records.
2276 * @final
2277 * @return bool
2278 */
2279 final public function delete() {
2280 global $DB;
ebf5ad4f
JMV
2281
2282 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
2283 $context = context_module::instance($cm->id);
2284
2285 // Delete files associated with attempts.
2286 $fs = get_file_storage();
2287 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
2288 foreach ($attempts as $attempt) {
2289 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
2290 }
2291 }
2292
2293 // Then delete all the associated records...
1e7f8ea2 2294 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
7e0551fc
JMV
2295
2296 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
1e7f8ea2
PS
2297 // ...now delete the answers...
2298 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
2299 // ..and the page itself
2300 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
2301
1cf8ca34
SB
2302 // Trigger an event: page deleted.
2303 $eventparams = array(
2304 'context' => $context,
2305 'objectid' => $this->properties->id,
2306 'other' => array(
2307 'pagetype' => $this->get_typestring()
2308 )
2309 );
2310 $event = \mod_lesson\event\page_deleted::create($eventparams);
2311 $event->add_record_snapshot('lesson_pages', $this->properties);
2312 $event->trigger();
2313
582ba677 2314 // Delete files associated with this page.
582ba677 2315 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
0abc18cf
JMV
2316 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $this->properties->id);
2317 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $this->properties->id);
582ba677 2318
1e7f8ea2
PS
2319 // repair the hole in the linkage
2320 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
2321 //This is the only page, no repair needed
2322 } elseif (!$this->properties->prevpageid) {
2323 // this is the first page...
2324 $page = $this->lesson->load_page($this->properties->nextpageid);
2325 $page->move(null, 0);
2326 } elseif (!$this->properties->nextpageid) {
2327 // this is the last page...
2328 $page = $this->lesson->load_page($this->properties->prevpageid);
2329 $page->move(0);
2330 } else {
2331 // page is in the middle...
2332 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
2333 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
2334
2335 $prevpage->move($nextpage->id);
2336 $nextpage->move(null, $prevpage->id);
2337 }
2338 return true;
2339 }
2340
2341 /**
2342 * Moves a page by updating its nextpageid and prevpageid values within
2343 * the database
2344 *
2345 * @final
2346 * @param int $nextpageid
2347 * @param int $prevpageid
2348 */
2349 final public function move($nextpageid=null, $prevpageid=null) {
2350 global $DB;
2351 if ($nextpageid === null) {
2352 $nextpageid = $this->properties->nextpageid;
2353 }
2354 if ($prevpageid === null) {
2355 $prevpageid = $this->properties->prevpageid;
2356 }
2357 $obj = new stdClass;
2358 $obj->id = $this->properties->id;
2359 $obj->prevpageid = $prevpageid;
2360 $obj->nextpageid = $nextpageid;
2361 $DB->update_record('lesson_pages', $obj);
2362 }
2363
2364 /**
2365 * Returns the answers that are associated with this page in the database
2366 *
2367 * @final
2368 * @return array
2369 */
2370 final public function get_answers() {
2371 global $DB;
2372 if ($this->answers === null) {
2373 $this->answers = array();
2374 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
2375 if (!$answers) {
1c510e2e
SH
2376 // It is possible that a lesson upgraded from Moodle 1.9 still
2377 // contains questions without any answers [MDL-25632].
2378 // debugging(get_string('cannotfindanswer', 'lesson'));
1e7f8ea2
PS
2379 return array();
2380 }
2381 foreach ($answers as $answer) {
2382 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
2383 }
2384 }
2385 return $this->answers;
2386 }
2387
2388 /**
2389 * Returns the lesson this page is associated with
2390 * @final
2391 * @return lesson
2392 */
2393 final protected function get_lesson() {
2394 return $this->lesson;
2395 }
2396
2397 /**
2398 * Returns the type of page this is. Not to be confused with page type
2399 * @final
2400 * @return int
2401 */
2402 final protected function get_type() {
2403 return $this->type;
2404 }
2405
2406 /**
2407 * Records an attempt at this page
2408 *
2409 * @final
26063f4b 2410 * @global moodle_database $DB
1e7f8ea2
PS
2411 * @param stdClass $context
2412 * @return stdClass Returns the result of the attempt
2413 */
2414 final public function record_attempt($context) {
8101328a 2415 global $DB, $USER, $OUTPUT, $PAGE;
1e7f8ea2
PS
2416
2417 /**
ff85f902 2418 * This should be overridden by each page type to actually check the response
1e7f8ea2
PS
2419 * against what ever custom criteria they have defined
2420 */
2421 $result = $this->check_answer();
2422
2423 $result->attemptsremaining = 0;
2424 $result->maxattemptsreached = false;
2425
2426 if ($result->noanswer) {
2427 $result->newpageid = $this->properties->id; // display same page again
2428 $result->feedback = get_string('noanswer', 'lesson');
2429 } else {
2430 if (!has_capability('mod/lesson:manage', $context)) {
2431 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2432 // record student's attempt
2433 $attempt = new stdClass;
2434 $attempt->lessonid = $this->lesson->id;
2435 $attempt->pageid = $this->properties->id;
2436 $attempt->userid = $USER->id;
2437 $attempt->answerid = $result->answerid;
2438 $attempt->retry = $nretakes;
2439 $attempt->correct = $result->correctanswer;
2440 if($result->userresponse !== null) {
2441 $attempt->useranswer = $result->userresponse;
2442 }
2443
2444 $attempt->timeseen = time();
2445 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
0aec842e 2446 $userisreviewing = false;
1e7f8ea2
PS
2447 if (isset($USER->modattempts[$this->lesson->id])) {
2448 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
0aec842e 2449 $userisreviewing = true;
1e7f8ea2
PS
2450 }
2451
0aec842e
AG
2452 // Only insert a record if we are not reviewing the lesson.
2453 if (!$userisreviewing) {
2454 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
8101328a
SB
2455 $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
2456 // Trigger an event: question answered.
2457 $eventparams = array(
2458 'context' => context_module::instance($PAGE->cm->id),
2459 'objectid' => $this->properties->id,
2460 'other' => array(
2461 'pagetype' => $this->get_typestring()
2462 )
2463 );
2464 $event = \mod_lesson\event\question_answered::create($eventparams);
2465 $event->add_record_snapshot('lesson_attempts', $attempt);
2466 $event->trigger();
2467
0aec842e 2468 }
abd5c24e 2469 }
1e7f8ea2
PS
2470 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
2471 // displaying of message(s) is at the end of page for more ergonomic display
2472 if (!$result->correctanswer && ($result->newpageid == 0)) {
2473 // wrong answer and student is stuck on this page - check how many attempts
2474 // the student has had at this page/question
abd5c24e 2475 $nattempts = $DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry" => $attempt->retry));
1e7f8ea2
PS
2476 // retreive the number of attempts left counter for displaying at bottom of feedback page
2477 if ($nattempts >= $this->lesson->maxattempts) {
2478 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2479 $result->maxattemptsreached = true;
2480 }
2481 $result->newpageid = LESSON_NEXTPAGE;
2482 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2483 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
2484 }
2485 }
2486 }
2487 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
2488 if ($result->newpageid == 0) {
2489 $result->newpageid = $this->properties->id;
2490 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
0343553f 2491 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
1e7f8ea2
PS
2492 }
2493
2494 // Determine default feedback if necessary
2495 if (empty($result->response)) {
2496 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2497 // These conditions have been met:
2498 // 1. The lesson manager has not supplied feedback to the student
2499 // 2. Not displaying default feedback
2500 // 3. The user did provide an answer
2501 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2502
2503 $result->nodefaultresponse = true; // This will cause a redirect below
2504 } else if ($result->isessayquestion) {
2505 $result->response = get_string('defaultessayresponse', 'lesson');
2506 } else if ($result->correctanswer) {
2507 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2508 } else {
2509 $result->response = get_string('thatsthewronganswer', 'lesson');
2510 }
2511 }
2512
2513 if ($result->response) {
2514 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2515 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2516 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2517 if ($qattempts == 1) {
2518 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2519 } else {
f47c365a 2520 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
1e7f8ea2
PS
2521 }
2522 } else {
2107531f
JMV
2523 $result->feedback = '';
2524 }
2525 $class = 'response';
2526 if ($result->correctanswer) {
2527 $class .= ' correct'; // CSS over-ride this if they exist (!important).
2528 } else if (!$result->isessayquestion) {
2529 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
2530 }
2531 $options = new stdClass;
2532 $options->noclean = true;
2533 $options->para = true;
2534 $options->overflowdiv = true;
2535 $options->context = $context;
2536
2537 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
2538 'generalbox boxaligncenter');
2539 if (isset($result->studentanswerformat)) {
2540 // This is the student's answer so it should be cleaned.
2541 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
2542 array('context' => $context, 'para' => true));
2543 } else {
2544 $studentanswer = format_string($result->studentanswer);
2545 }
2546 $result->feedback .= '<div class="correctanswer generalbox"><em>'
2547 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
2548 if (isset($result->responseformat)) {
2549 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
ebf5ad4f 2550 'mod_lesson', 'page_responses', $result->answerid);
2107531f 2551 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
ebf5ad4f 2552 , $class);
2107531f
JMV
2553 } else {
2554 $result->feedback .= $OUTPUT->box($result->response, $class);
1e7f8ea2 2555 }
2107531f 2556 $result->feedback .= '</div>';
1e7f8ea2
PS
2557 }
2558 }
2559
2560 return $result;
2561 }
2562
2563 /**
2564 * Returns the string for a jump name
2565 *
2566 * @final
2567 * @param int $jumpto Jump code or page ID
2568 * @return string
2569 **/
2570 final protected function get_jump_name($jumpto) {
2571 global $DB;
2572 static $jumpnames = array();
2573
2574 if (!array_key_exists($jumpto, $jumpnames)) {
44cb7e63 2575 if ($jumpto == LESSON_THISPAGE) {
1e7f8ea2
PS
2576 $jumptitle = get_string('thispage', 'lesson');
2577 } elseif ($jumpto == LESSON_NEXTPAGE) {
2578 $jumptitle = get_string('nextpage', 'lesson');
2579 } elseif ($jumpto == LESSON_EOL) {
2580 $jumptitle = get_string('endoflesson', 'lesson');
2581 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2582 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2583 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2584 $jumptitle = get_string('previouspage', 'lesson');
2585 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2586 $jumptitle = get_string('randompageinbranch', 'lesson');
2587 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2588 $jumptitle = get_string('randombranch', 'lesson');
2589 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2590 $jumptitle = get_string('clusterjump', 'lesson');
2591 } else {
2592 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2593 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2594 }
2595 }
2596 $jumpnames[$jumpto] = format_string($jumptitle,true);
2597 }
2598
2599 return $jumpnames[$jumpto];
2600 }
2601
2602 /**
ff85f902 2603 * Constructor method
1e7f8ea2
PS
2604 * @param object $properties
2605 * @param lesson $lesson
2606 */
2607 public function __construct($properties, lesson $lesson) {
2608 parent::__construct($properties);
2609 $this->lesson = $lesson;
2610 }
2611
2612 /**
2613 * Returns the score for the attempt
ff85f902 2614 * This may be overridden by page types that require manual grading
1e7f8ea2
PS
2615 * @param array $answers
2616 * @param object $attempt
2617 * @return int
2618 */
2619 public function earned_score($answers, $attempt) {
2620 return $answers[$attempt->answerid]->score;
2621 }
2622
2623 /**
2624 * This is a callback method that can be override and gets called when ever a page
2625 * is viewed
2626 *
2627 * @param bool $canmanage True if the user has the manage cap
2628 * @return mixed
2629 */
2630 public function callback_on_view($canmanage) {
2631 return true;
2632 }
2633
0abc18cf
JMV
2634 /**
2635 * save editor answers files and update answer record
2636 *
2637 * @param object $context
2638 * @param int $maxbytes
2639 * @param object $answer
2640 * @param object $answereditor
2641 * @param object $responseeditor
2642 */
2643 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
2644 global $DB;
2645 if (isset($answereditor['itemid'])) {
2646 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
2647 $context->id, 'mod_lesson', 'page_answers', $answer->id,
2648 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2649 $answer->answer, null);
2650 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
2651 }
2652 if (isset($responseeditor['itemid'])) {
2653 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
2654 $context->id, 'mod_lesson', 'page_responses', $answer->id,
2655 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2656 $answer->response, null);
2657 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
2658 }
2659 }
2660
2661 /**
2662 * Rewrite urls in response and optionality answer of a question answer
2663 *
2664 * @param object $answer
2665 * @param bool $rewriteanswer must rewrite answer
2666 * @return object answer with rewritten urls
2667 */
2668 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
2669 global $PAGE;
2670
2671 $context = context_module::instance($PAGE->cm->id);
2672 if ($rewriteanswer) {
2673 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
2674 'mod_lesson', 'page_answers', $answer->id);
2675 }
2676 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
2677 'mod_lesson', 'page_responses', $answer->id);
2678
2679 return $answer;
2680 }
2681
1e7f8ea2
PS
2682 /**
2683 * Updates a lesson page and its answers within the database
2684 *
2685 * @param object $properties
2686 * @return bool
2687 */
2688 public function update($properties, $context = null, $maxbytes = null) {
7b30b24b 2689 global $DB, $PAGE;
1e7f8ea2
PS
2690 $answers = $this->get_answers();
2691 $properties->id = $this->properties->id;
2692 $properties->lessonid = $this->lesson->id;
2693 if (empty($properties->qoption)) {
2694 $properties->qoption = '0';
2695 }
2696 if (empty($context)) {
2697 $context = $PAGE->context;
2698 }
2699 if ($maxbytes === null) {
1812ea3e 2700 $maxbytes = get_user_max_upload_file_size($context);
1e7f8ea2 2701 }
9ac3d686 2702 $properties->timemodified = time();
1e7f8ea2
PS
2703 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2704 $DB->update_record("lesson_pages", $properties);
1cf8ca34
SB
2705
2706 // Trigger an event: page updated.
2707 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
2708
a748983a 2709 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
a1300e98 2710 // These page types have only one answer to save the jump and score.
a748983a
JMV
2711 if (count($answers) > 1) {
2712 $answer = array_shift($answers);
2713 foreach ($answers as $a) {
2714 $DB->delete_record('lesson_answers', array('id' => $a->id));
2715 }
2716 } else if (count($answers) == 1) {
2717 $answer = array_shift($answers);
2718 } else {
2719 $answer = new stdClass;
2720 $answer->lessonid = $properties->lessonid;
2721 $answer->pageid = $properties->id;
2722 $answer->timecreated = time();
1e7f8ea2 2723 }
981debb7 2724
a748983a
JMV
2725 $answer->timemodified = time();
2726 if (isset($properties->jumpto[0])) {
2727 $answer->jumpto = $properties->jumpto[0];
981debb7 2728 }
a748983a
JMV
2729 if (isset($properties->score[0])) {
2730 $answer->score = $properties->score[0];
981debb7 2731 }
a748983a
JMV
2732 if (!empty($answer->id)) {
2733 $DB->update_record("lesson_answers", $answer->properties());
2734 } else {
2735 $DB->insert_record("lesson_answers", $answer);
2736 }
2737 } else {
2738 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2739 if (!array_key_exists($i, $this->answers)) {
2740 $this->answers[$i] = new stdClass;
2741 $this->answers[$i]->lessonid = $this->lesson->id;
2742 $this->answers[$i]->pageid = $this->id;
2743 $this->answers[$i]->timecreated = $this->timecreated;
1e7f8ea2 2744 }
a748983a 2745
a1300e98
JMV
2746 if (!empty($properties->answer_editor[$i])) {
2747 if (is_array($properties->answer_editor[$i])) {
2748 // Multichoice and true/false pages have an HTML editor.
2749 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
2750 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
2751 } else {
2752 // Branch tables, shortanswer and mumerical pages have only a text field.
2753 $this->answers[$i]->answer = $properties->answer_editor[$i];
2754 $this->answers[$i]->answerformat = FORMAT_MOODLE;
2755 }
1e7f8ea2 2756 }
a1300e98 2757
a748983a
JMV
2758 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2759 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
2760 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
1e7f8ea2
PS
2761 }
2762
a748983a
JMV
2763 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
2764 if (isset($properties->jumpto[$i])) {
2765 $this->answers[$i]->jumpto = $properties->jumpto[$i];
2766 }
2767 if ($this->lesson->custom && isset($properties->score[$i])) {
2768 $this->answers[$i]->score = $properties->score[$i];
2769 }
2770 if (!isset($this->answers[$i]->id)) {
2771 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
2772 } else {
2773 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
2774 }
0abc18cf 2775
a748983a
JMV
2776 // Save files in answers and responses.
2777 if (isset($properties->response_editor[$i])) {
2778 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
2779 $properties->answer_editor[$i], $properties->response_editor[$i]);
2780 } else {
2781 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
2782 $properties->answer_editor[$i]);
2783 }
2784
2785 } else if (isset($this->answers[$i]->id)) {
2786 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
2787 unset($this->answers[$i]);
2788 }
1e7f8ea2
PS
2789 }
2790 }
2791 return true;
2792 }
2793
2794 /**
2795 * Can be set to true if the page requires a static link to create a new instance
2796 * instead of simply being included in the dropdown
2797 * @param int $previd
2798 * @return bool
2799 */
2800 public function add_page_link($previd) {
2801 return false;
2802 }
2803
2804 /**
2805 * Returns true if a page has been viewed before
2806 *
2807 * @param array|int $param Either an array of pages that have been seen or the
2808 * number of retakes a user has had
2809 * @return bool
2810 */
2811 public function is_unseen($param) {
2812 global $USER, $DB;
2813 if (is_array($param)) {
2814 $seenpages = $param;
2815 return (!array_key_exists($this->properties->id, $seenpages));
2816 } else {
2817 $nretakes = $param;
2818 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
2819 return true;
2820 }
2821 }
2822 return false;
2823 }
2824
2825 /**
2826 * Checks to see if a page has been answered previously
2827 * @param int $nretakes
2828 * @return bool
2829 */
2830 public function is_unanswered($nretakes) {
2831 global $DB, $USER;
2832 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
2833 return true;
2834 }
2835 return false;
2836 }
2837
2838 /**
2839 * Creates answers within the database for this lesson_page. Usually only ever
2840 * called when creating a new page instance
2841 * @param object $properties
2842 * @return array
2843 */
2844 public function create_answers($properties) {
0abc18cf 2845 global $DB, $PAGE;
1e7f8ea2
PS
2846 // now add the answers
2847 $newanswer = new stdClass;
2848 $newanswer->lessonid = $this->lesson->id;
2849 $newanswer->pageid = $this->properties->id;
2850 $newanswer->timecreated = $this->properties->timecreated;
2851
0abc18cf
JMV
2852 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
2853 $context = context_module::instance($cm->id);
2854
1e7f8ea2
PS
2855 $answers = array();
2856
2857 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
2858 $answer = clone($newanswer);
981debb7 2859
a1300e98
JMV
2860 if (!empty($properties->answer_editor[$i])) {
2861 if (is_array($properties->answer_editor[$i])) {
2862 // Multichoice and true/false pages have an HTML editor.
2863 $answer->answer = $properties->answer_editor[$i]['text'];
2864 $answer->answerformat = $properties->answer_editor[$i]['format'];
2865 } else {
2866 // Branch tables, shortanswer and mumerical pages have only a text field.
2867 $answer->answer = $properties->answer_editor[$i];
2868 $answer->answerformat = FORMAT_MOODLE;
2869 }
981debb7
SH
2870 }
2871 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
2872 $answer->response = $properties->response_editor[$i]['text'];
2873 $answer->responseformat = $properties->response_editor[$i]['format'];
2874 }
2875
6d84e82f 2876 if (isset($answer->answer) && $answer->answer != '') {
1e7f8ea2
PS
2877 if (isset($properties->jumpto[$i])) {
2878 $answer->jumpto = $properties->jumpto[$i];
2879 }
2880 if ($this->lesson->custom && isset($properties->score[$i])) {
2881 $answer->score = $properties->score[$i];
2882 }
2883 $answer->id = $DB->insert_record("lesson_answers", $answer);
0abc18cf
JMV
2884 if (isset($properties->response_editor[$i])) {
2885 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
2886 $properties->answer_editor[$i], $properties->response_editor[$i]);
2887 } else {
2888 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
2889 $properties->answer_editor[$i]);
2890 }
1e7f8ea2
PS
2891 $answers[$answer->id] = new lesson_page_answer($answer);
2892 } else {
2893 break;
2894 }
2895 }
2896
2897 $this->answers = $answers;
2898 return $answers;
2899 }
2900
2901 /**
ff85f902 2902 * This method MUST be overridden by all question page types, or page types that
1e7f8ea2
PS
2903 * wish to score a page.
2904 *
2905 * The structure of result should always be the same so it is a good idea when
2906 * overriding this method on a page type to call
2907 * <code>
2908 * $result = parent::check_answer();
2909 * </code>
ff85f902 2910 * before modifying it as required.
1e7f8ea2
PS
2911 *
2912 * @return stdClass
2913 */
2914 public function check_answer() {
2915 $result = new stdClass;
2916 $result->answerid = 0;
2917 $result->noanswer = false;
2918 $result->correctanswer = false;
2919 $result->isessayquestion = false; // use this to turn off review button on essay questions
2920 $result->response = '';
2921 $result->newpageid = 0; // stay on the page
2922 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
2923 $result->userresponse = null;
2924 $result->feedback = '';
2925 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
2926 return $result;
2927 }
2928
2929 /**
2930 * True if the page uses a custom option
2931 *
2932 * Should be override and set to true if the page uses a custom option.
2933 *
2934 * @return bool
2935 */
2936 public function has_option() {
2937 return false;
2938 }
2939
2940 /**
2941 * Returns the maximum number of answers for this page given the maximum number
2942 * of answers permitted by the lesson.
2943 *
2944 * @param int $default
2945 * @return int
2946 */
2947 public function max_answers($default) {
2948 return $default;
2949 }
2950
2951 /**
2952 * Returns the properties of this lesson page as an object
2953 * @return stdClass;
2954 */
2955 public function properties() {
2956 $properties = clone($this->properties);
2957 if ($this->answers === null) {
2958 $this->get_answers();
2959 }
2960 if (count($this->answers)>0) {
2961 $count = 0;
fcb88d7d 2962 $qtype = $properties->qtype;
1e7f8ea2 2963 foreach ($this->answers as $answer) {
b0ff0e9a 2964 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
58b72abc 2965 if ($qtype != LESSON_PAGE_MATCHING) {
b0ff0e9a 2966 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
58b72abc
JR
2967 } else {
2968 $properties->{'response_editor['.$count.']'} = $answer->response;
2969 }
1e7f8ea2
PS
2970 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
2971 $properties->{'score['.$count.']'} = $answer->score;
2972 $count++;
2973 }
2974 }
2975 return $properties;
2976 }
2977
2978 /**
ff85f902 2979 * Returns an array of options to display when choosing the jumpto for a page/answer
1e7f8ea2
PS
2980 * @static
2981 * @param int $pageid
2982 * @param lesson $lesson
2983 * @return array
2984 */
2985 public static function get_jumptooptions($pageid, lesson $lesson) {
2986 global $DB;
2987 $jump = array();
2988 $jump[0] = get_string("thispage", "lesson");
2989 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
2990 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
2991 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
2992
2993 if ($pageid == 0) {
2994 return $jump;
2995 }
2996
2997 $pages = $lesson->load_all_pages();
2998 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))) {
2999 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
3000 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
3001 }
3002 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
3003 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
3004 }
3005 if (!optional_param('firstpage', 0, PARAM_INT)) {
3006 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
3007 while (true) {
3008 if ($apageid) {
3009 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
3010 $jump[$apageid] = strip_tags(format_string($title,true));
3011 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
3012 } else {
3013 // last page reached
3014 break;
3015 }
3016 }
3017 }
3018 return $jump;
3019 }
3020 /**
3021 * Returns the contents field for the page properly formatted and with plugin
3022 * file url's converted
3023 * @return string
3024 */
3025 public function get_contents() {
3026 global $PAGE;
3027 if (!empty($this->properties->contents)) {
3028 if (!isset($this->properties->contentsformat)) {
3029 $this->properties->contentsformat = FORMAT_HTML;
3030 }
5918e371 3031 $context = context_module::instance($PAGE->cm->id);
3266d14b
PS
3032 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
3033 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
3034 return format_text($contents, $this->properties->contentsformat,
3035 array('context' => $context, 'noclean' => true,
3036 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
1e7f8ea2
PS
3037 } else {
3038 return '';
3039 }
3040 }
3041
3042 /**
3043 * Set to true if this page should display in the menu block
3044 * @return bool
3045 */
3046 protected function get_displayinmenublock() {
3047 return false;
3048 }
3049
3050 /**
3051 * Get the string that describes the options of this page type
3052 * @return string
3053 */
3054 public function option_description_string() {
3055 return '';
3056 }
3057
3058 /**
3059 * Updates a table with the answers for this page
3060 * @param html_table $table
3061 * @return html_table
3062 */
3063 public function display_answers(html_table $table) {
3064 $answers = $this->get_answers();
3065 $i = 1;
3066 foreach ($answers as $answer) {
3067 $cells = array();
3068 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
3069 $cells[] = $this->get_jump_name($answer->jumpto);
3070 $table->data[] = new html_table_row($cells);
3071 if ($i === 1){
3072 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
3073 }
3074 $i++;
3075 }
3076 return $table;
3077 }
3078
3079 /**
3080 * Determines if this page should be grayed out on the management/report screens
3081 * @return int 0 or 1
3082 */
3083 protected function get_grayout() {
3084 return 0;
3085 }
3086
3087 /**
3088 * Adds stats for this page to the &pagestats object. This should be defined
3089 * for all page types that grade
3090 * @param array $pagestats
3091 * @param int $tries
3092 * @return bool
3093 */
3094 public function stats(array &$pagestats, $tries) {
3095 return true;
3096 }
3097
3098 /**
3099 * Formats the answers of this page for a report
3100 *
3101 * @param object $answerpage
3102 * @param object $answerdata
3103 * @param object $useranswer
3104 * @param array $pagestats
3105 * @param int $i Count of first level answers
3106 * @param int $n Count of second level answers
3107 * @return object The answer page for this
3108 */
3109 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
3110 $answers = $this->get_answers();
3111 $formattextdefoptions = new stdClass;
3112 $formattextdefoptions->para = false; //I'll use it widely in this page
3113 foreach ($answers as $answer) {
3114 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
3115 $answerdata->answers[] = array($data, "");
3116 $answerpage->answerdata = $answerdata;
3117 }
3118 return $answerpage;
3119 }
3120
3121 /**
3122 * Gets an array of the jumps used by the answers of this page
3123 *
3124 * @return array
3125 */
3126 public function get_jumps() {
3127 global $DB;
3128 $jumps = array();
3129 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
3130 if ($answers = $this->get_answers()) {
3131 foreach ($answers as $answer) {
3132 $jumps[] = $this->get_jump_name($answer->jumpto);
3133 }
9170dea7
SH
3134 } else {
3135 $jumps[] = $this->get_jump_name($this->properties->nextpageid);
1e7f8ea2
PS
3136 }
3137 return $jumps;
3138 }
3139 /**
3140 * Informs whether this page type require manual grading or not
3141 * @return bool
3142 */
3143 public function requires_manual_grading() {
3144 return false;
3145 }
3146
3147 /**
3148 * A callback method that allows a page to override the next page a user will
3149 * see during when this page is being completed.
3150 * @return false|int
3151 */
3152 public function override_next_page() {
3153 return false;
3154 }
3155
3156 /**
3157 * This method is used to determine if this page is a valid page
3158 *
3159 * @param array $validpages
3160 * @param array $pageviews
3161 * @return int The next page id to check
3162 */
3163 public function valid_page_and_view(&$validpages, &$pageviews) {
3164 $validpages[$this->properties->id] = 1;
3165 return $this->properties->nextpageid;
3166 }
3167}
3168
3169
3170
3171/**
3172 * Class used to represent an answer to a page
3173 *
3174 * @property int $id The ID of this answer in the database
3175 * @property int $lessonid The ID of the lesson this answer belongs to
3176 * @property int $pageid The ID of the page this answer belongs to
3177 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
3178 * @property int $grade The grade this answer is worth
3179 * @property int $score The score this answer will give
3180 * @property int $flags Used to store options for the answer
3181 * @property int $timecreated A timestamp of when the answer was created
3182 * @property int $timemodified A timestamp of when the answer was modified
3183 * @property string $answer The answer itself
3184 * @property string $response The response the user sees if selecting this answer
3185 *
cc3dbaaa
PS
3186 * @copyright 2009 Sam Hemelryk
3187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
3188 */
3189class lesson_page_answer extends lesson_base {
3190
3191 /**
3192 * Loads an page answer from the DB
3193 *
3194 * @param int $id
3195 * @return lesson_page_answer
3196 */
3197 public static function load($id) {
3198 global $DB;
3199 $answer = $DB->get_record("lesson_answers", array("id" => $id));
3200 return new lesson_page_answer($answer);
3201 }
3202
3203 /**
3204 * Given an object of properties and a page created answer(s) and saves them
3205 * in the database.
3206 *
3207 * @param stdClass $properties
3208 * @param lesson_page $page
3209 * @return array
3210 */
3211 public static function create($properties, lesson_page $page) {
3212 return $page->create_answers($properties);
3213 }
3214
3215}
3216
3217/**
3218 * A management class for page types
3219 *
3220 * This class is responsible for managing the different pages. A manager object can
3221 * be retrieved by calling the following line of code:
3222 * <code>
3223 * $manager = lesson_page_type_manager::get($lesson);
3224 * </code>
3225 * The first time the page type manager is retrieved the it includes all of the
3226 * different page types located in mod/lesson/pagetypes.
3227 *
cc3dbaaa
PS
3228 * @copyright 2009 Sam Hemelryk
3229 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
3230 */
3231class lesson_page_type_manager {
3232
3233 /**
3234 * An array of different page type classes
3235 * @var array
3236 */
3237 protected $types = array();
3238
3239 /**
3240 * Retrieves the lesson page type manager object
3241 *
3242 * If the object hasn't yet been created it is created here.
3243 *
3244 * @staticvar lesson_page_type_manager $pagetypemanager
3245 * @param lesson $lesson
3246 * @return lesson_page_type_manager
3247 */
3248 public static function get(lesson $lesson) {
3249 static $pagetypemanager;
3250 if (!($pagetypemanager instanceof lesson_page_type_manager)) {
3251 $pagetypemanager = new lesson_page_type_manager();
3252 $pagetypemanager->load_lesson_types($lesson);
3253 }
3254 return $pagetypemanager;
3255 }
3256
3257 /**
3258 * Finds and loads all lesson page types in mod/lesson/pagetypes
3259 *
3260 * @param lesson $lesson
3261 */
3262 public function load_lesson_types(lesson $lesson) {
3263 global $CFG;
3264 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
3265 $dir = dir($basedir);
3266 while (false !== ($entry = $dir->read())) {
3267 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
3268 continue;
3269 }
3270 require_once($basedir.$entry);
3271 $class = 'lesson_page_type_'.strtok($entry,'.');
3272 if (class_exists($class)) {
3273 $pagetype = new $class(new stdClass, $lesson);
3274 $this->types[$pagetype->typeid] = $pagetype;
3275 }
3276 }
3277
3278 }
3279
3280 /**
3281 * Returns an array of strings to describe the loaded page types
3282 *
3283 * @param int $type Can be used to return JUST the string for the requested type
3284 * @return array
3285 */
3286 public function get_page_type_strings($type=null, $special=true) {
3287 $types = array();
3288 foreach ($this->types as $pagetype) {
3289 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
3290 $types[$pagetype->typeid] = $pagetype->typestring;
3291 }
3292 }
3293 return $types;
3294 }
3295
3296 /**
3297 * Returns the basic string used to identify a page type provided with an id
3298 *
3299 * This string can be used to instantiate or identify the page type class.
3300 * If the page type id is unknown then 'unknown' is returned
3301 *
3302 * @param int $id
3303 * @return string
3304 */
3305 public function get_page_type_idstring($id) {
3306 foreach ($this->types as $pagetype) {
3307 if ((int)$pagetype->typeid === (int)$id) {
3308 return $pagetype->idstring;
3309 }
3310 }
3311 return 'unknown';
3312 }
3313
3314 /**
3315 * Loads a page for the provided lesson given it's id
3316 *
3317 * This function loads a page from the lesson when given both the lesson it belongs
3318 * to as well as the page's id.
3319 * If the page doesn't exist an error is thrown
3320 *
3321 * @param int $pageid The id of the page to load
3322 * @param lesson $lesson The lesson the page belongs to
3323 * @return lesson_page A class that extends lesson_page
3324 */
3325 public function load_page($pageid, lesson $lesson) {
3326 global $DB;
3327 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
3328 print_error('cannotfindpages', 'lesson');
3329 }
3330 $pagetype = get_class($this->types[$page->qtype]);
3331 $page = new $pagetype($page, $lesson);
3332 return $page;
3333 }
3334
afe36b84
DW
3335 /**
3336 * This function detects errors in the ordering between 2 pages and updates the page records.
3337 *
3338 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
3339 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
3340 */
3341 protected function check_page_order($page1, $page2) {
3342 global $DB;
3343 if (empty($page1)) {
3344 if ($page2->prevpageid != 0) {
3345 debugging("***prevpageid of page " . $page2->id . " set to 0***");
3346 $page2->prevpageid = 0;
3347 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
3348 }
3349 } else if (empty($page2)) {
3350 if ($page1->nextpageid != 0) {
3351 debugging("***nextpageid of page " . $page1->id . " set to 0***");
3352 $page1->nextpageid = 0;
3353 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
3354 }
3355 } else {
3356 if ($page1->nextpageid != $page2->id) {
3357 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
3358 $page1->nextpageid = $page2->id;
3359 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
3360 }
3361 if ($page2->prevpageid != $page1->id) {
3362 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
3363 $page2->prevpageid = $page1->id;
3364 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
3365 }
3366 }
3367 }
3368
1e7f8ea2
PS
3369 /**
3370 * This function loads ALL pages that belong to the lesson.
3371 *
3372 * @param lesson $lesson
3373 * @return array An array of lesson_page_type_*
3374 */
3375 public function load_all_pages(lesson $lesson) {
3376 global $DB;
3377 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
c6ac68ee 3378 return array(); // Records returned empty.
1e7f8ea2
PS
3379 }
3380 foreach ($pages as $key=>$page) {
3381 $pagetype = get_class($this->types[$page->qtype]);
3382 $pages[$key] = new $pagetype($page, $lesson);
3383 }
3384
3385 $orderedpages = array();
3386 $lastpageid = 0;
d33d7125
DW
3387 $morepages = true;
3388 while ($morepages) {
3389 $morepages = false;
1e7f8ea2
PS
3390 foreach ($pages as $page) {
3391 if ((int)$page->prevpageid === (int)$lastpageid) {
afe36b84
DW
3392 // Check for errors in page ordering and fix them on the fly.
3393 $prevpage = null;
3394 if ($lastpageid !== 0) {
3395 $prevpage = $orderedpages[$lastpageid];
3396 }
3397 $this->check_page_order($prevpage, $page);
d33d7125 3398 $morepages = true;
1e7f8ea2
PS
3399 $orderedpages[$page->id] = $page;
3400 unset($pages[$page->id]);
3401 $lastpageid = $page->id;
3402 if ((int)$page->nextpageid===0) {
3403 break 2;
3404 } else {
3405 break 1;
3406 }
3407 }
3408 }
3409 }
3410
afe36b84 3411 // Add remaining pages and fix the nextpageid links for each page.
d33d7125 3412 foreach ($pages as $page) {
afe36b84
DW
3413 // Check for errors in page ordering and fix them on the fly.
3414 $prevpage = null;
3415 if ($lastpageid !== 0) {
3416 $prevpage = $orderedpages[$lastpageid];
3417 }
3418 $this->check_page_order($prevpage, $page);
d33d7125 3419 $orderedpages[$page->id] = $page;
afe36b84 3420 unset($pages[$page->id]);
d33d7125
DW
3421 $lastpageid = $page->id;
3422 }
3423
afe36b84
DW
3424 if ($lastpageid !== 0) {
3425 $this->check_page_order($orderedpages[$lastpageid], null);
3426 }
3427
1e7f8ea2
PS
3428 return $orderedpages;
3429 }
3430
3431 /**
ff85f902 3432 * Fetches an mform that can be used to create/edit an page
1e7f8ea2
PS
3433 *
3434 * @param int $type The id for the page type
3435 * @param array $arguments Any arguments to pass to the mform
3436 * @return lesson_add_page_form_base
3437 */
3438 public function get_page_form($type, $arguments) {
3439 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
3440 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
3441 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
3442 $class = 'lesson_add_page_form_selection';
3443 } else if ($class === 'lesson_add_page_form_unknown') {
3444 $class = 'lesson_add_page_form_selection';
3445 }
3446 return new $class(null, $arguments);
3447 }
3448
3449 /**
3450 * Returns an array of links to use as add page links
3451 * @param int $previd The id of the previous page
3452 * @return array
3453 */
3454 public function get_add_page_type_links($previd) {
3455 global $OUTPUT;
3456
3457 $links = array();
3458
3459 foreach ($this->types as $key=>$type) {
3460 if ($link = $type->add_page_link($previd)) {
3461 $links[$key] = $link;
3462 }
3463 }
3464
3465 return $links;
3466 }
3467}