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