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