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