MDL-61498 lesson: link to next activity in boost
[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
1186
1e7f8ea2
PS
1187/**
1188 * Abstract class that page type's MUST inherit from.
1189 *
1190 * This is the abstract class that ALL add page type forms must extend.
1191 * You will notice that all but two of the methods this class contains are final.
1192 * Essentially the only thing that extending classes can do is extend custom_definition.
1193 * OR if it has a special requirement on creation it can extend construction_override
1194 *
1195 * @abstract
cc3dbaaa
PS
1196 * @copyright 2009 Sam Hemelryk
1197 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
1198 */
1199abstract class lesson_add_page_form_base extends moodleform {
1200
1201 /**
1202 * This is the classic define that is used to identify this pagetype.
1203 * Will be one of LESSON_*
1204 * @var int
1205 */
1206 public $qtype;
1207
1208 /**
1209 * The simple string that describes the page type e.g. truefalse, multichoice
1210 * @var string
1211 */
1212 public $qtypestring;
1213
1214 /**
1215 * An array of options used in the htmleditor
1216 * @var array
1217 */
1218 protected $editoroptions = array();
1219
1220 /**
1221 * True if this is a standard page of false if it does something special.
1222 * Questions are standard pages, branch tables are not
1223 * @var bool
1224 */
1225 protected $standard = true;
1226
ceeab150
RT
1227 /**
1228 * Answer format supported by question type.
1229 */
1230 protected $answerformat = '';
1231
1232 /**
1233 * Response format supported by question type.
1234 */
1235 protected $responseformat = '';
1236
1e7f8ea2
PS
1237 /**
1238 * Each page type can and should override this to add any custom elements to
1239 * the basic form that they want
1240 */
1241 public function custom_definition() {}
1242
1243 /**
ceeab150
RT
1244 * Returns answer format used by question type.
1245 */
1246 public function get_answer_format() {
1247 return $this->answerformat;
1248 }
1249
1250 /**
1251 * Returns response format used by question type.
1252 */
1253 public function get_response_format() {
1254 return $this->responseformat;
1255 }
1256
1257 /**
1e7f8ea2
PS
1258 * Used to determine if this is a standard page or a special page
1259 * @return bool
1260 */
1261 public final function is_standard() {
1262 return (bool)$this->standard;
1263 }
1264
1265 /**
1266 * Add the required basic elements to the form.
1267 *
1268 * This method adds the basic elements to the form including title and contents
1269 * and then calls custom_definition();
1270 */
1271 public final function definition() {
1272 $mform = $this->_form;
1273 $editoroptions = $this->_customdata['editoroptions'];
1274
a06face2
JE
1275 if ($this->qtypestring != 'selectaqtype') {
1276 if ($this->_customdata['edit']) {
1277 $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring, 'lesson'));
1278 } else {
1279 $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring, 'lesson'));
1280 }
1281 }
1e7f8ea2 1282
32495414
MA
1283 if (!empty($this->_customdata['returnto'])) {
1284 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
1285 $mform->setType('returnto', PARAM_URL);
1286 }
1287
1e7f8ea2
PS
1288 $mform->addElement('hidden', 'id');
1289 $mform->setType('id', PARAM_INT);
1290
1291 $mform->addElement('hidden', 'pageid');
1292 $mform->setType('pageid', PARAM_INT);
1293
1294 if ($this->standard === true) {
1295 $mform->addElement('hidden', 'qtype');
05db3cc7 1296 $mform->setType('qtype', PARAM_INT);
1e7f8ea2 1297
3fa2f030 1298 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
1e7f8ea2 1299 $mform->setType('title', PARAM_TEXT);
3fa2f030
PS
1300 $mform->addRule('title', get_string('required'), 'required', null, 'client');
1301
1e7f8ea2 1302 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
3fa2f030
PS
1303 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
1304 $mform->setType('contents_editor', PARAM_RAW);
1305 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1e7f8ea2
PS
1306 }
1307
1308 $this->custom_definition();
1309
1310 if ($this->_customdata['edit'] === true) {
1311 $mform->addElement('hidden', 'edit', 1);
747d5b1c 1312 $mform->setType('edit', PARAM_BOOL);
3fa2f030 1313 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
272bc0a6 1314 } else if ($this->qtype === 'questiontype') {
3fa2f030 1315 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
272bc0a6
RW
1316 } else {
1317 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1e7f8ea2
PS
1318 }
1319 }
1320
1321 /**
1322 * Convenience function: Adds a jumpto select element
1323 *
1324 * @param string $name
1325 * @param string|null $label
1326 * @param int $selected The page to select by default
1327 */
1328 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
1329 $title = get_string("jump", "lesson");
1330 if ($label === null) {
1331 $label = $title;
1332 }
1333 if (is_int($name)) {
1334 $name = "jumpto[$name]";
1335 }
1336 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
1337 $this->_form->setDefault($name, $selected);
1338 $this->_form->addHelpButton($name, 'jumps', 'lesson');
1339 }
1340
1341 /**
1342 * Convenience function: Adds a score input element
1343 *
1344 * @param string $name
1345 * @param string|null $label
1346 * @param mixed $value The default value
1347 */
1348 protected final function add_score($name, $label=null, $value=null) {
1349 if ($label === null) {
1350 $label = get_string("score", "lesson");
1351 }
a015bc03 1352
1e7f8ea2
PS
1353 if (is_int($name)) {
1354 $name = "score[$name]";
1355 }
1356 $this->_form->addElement('text', $name, $label, array('size'=>5));
a015bc03 1357 $this->_form->setType($name, PARAM_INT);
1e7f8ea2
PS
1358 if ($value !== null) {
1359 $this->_form->setDefault($name, $value);
1360 }
20685b28
AG
1361 $this->_form->addHelpButton($name, 'score', 'lesson');
1362
1363 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1364 if (!$this->_customdata['lesson']->custom) {
1365 $this->_form->freeze($name);
1366 }
1e7f8ea2
PS
1367 }
1368
1369 /**
1370 * Convenience function: Adds an answer editor
1371 *
1372 * @param int $count The count of the element to add
ecea65ca 1373 * @param string $label, null means default
a675ada5 1374 * @param bool $required
a1556aaf 1375 * @param string $format
a675ada5 1376 * @return void
1e7f8ea2 1377 */
a1556aaf 1378 protected final function add_answer($count, $label = null, $required = false, $format= '') {
ecea65ca 1379 if ($label === null) {
a675ada5
PS
1380 $label = get_string('answer', 'lesson');
1381 }
0abc18cf 1382
a1556aaf 1383 if ($format == LESSON_ANSWER_HTML) {
0abc18cf
JMV
1384 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
1385 array('rows' => '4', 'columns' => '80'),
1386 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1387 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
1388 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
a1556aaf 1389 } else {
a1300e98
JMV
1390 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
1391 array('size' => '50', 'maxlength' => '200'));
1392 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
0abc18cf
JMV
1393 }
1394
a675ada5
PS
1395 if ($required) {
1396 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1397 }
1e7f8ea2
PS
1398 }
1399 /**
1400 * Convenience function: Adds an response editor
1401 *
1402 * @param int $count The count of the element to add
ecea65ca 1403 * @param string $label, null means default
a675ada5
PS
1404 * @param bool $required
1405 * @return void
1e7f8ea2 1406 */
ecea65ca
RW
1407 protected final function add_response($count, $label = null, $required = false) {
1408 if ($label === null) {
a675ada5
PS
1409 $label = get_string('response', 'lesson');
1410 }
0abc18cf
JMV
1411 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
1412 array('rows' => '4', 'columns' => '80'),
1413 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1414 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
1415 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1416
a675ada5
PS
1417 if ($required) {
1418 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1419 }
1e7f8ea2
PS
1420 }
1421
1422 /**
1423 * A function that gets called upon init of this object by the calling script.
1424 *
1425 * This can be used to process an immediate action if required. Currently it
1426 * is only used in special cases by non-standard page types.
1427 *
1428 * @return bool
1429 */
0ed6f712 1430 public function construction_override($pageid, lesson $lesson) {
1e7f8ea2
PS
1431 return true;
1432 }
1433}
1434
1435
1436
1437/**
1438 * Class representation of a lesson
1439 *
1440 * This class is used the interact with, and manage a lesson once instantiated.
1441 * If you need to fetch a lesson object you can do so by calling
1442 *
1443 * <code>
1444 * lesson::load($lessonid);
1445 * // or
1446 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1447 * $lesson = new lesson($lessonrecord);
1448 * </code>
1449 *
1450 * The class itself extends lesson_base as all classes within the lesson module should
1451 *
1452 * These properties are from the database
1453 * @property int $id The id of this lesson
1454 * @property int $course The ID of the course this lesson belongs to
1455 * @property string $name The name of this lesson
1456 * @property int $practice Flag to toggle this as a practice lesson
1457 * @property int $modattempts Toggle to allow the user to go back and review answers
1458 * @property int $usepassword Toggle the use of a password for entry
1459 * @property string $password The password to require users to enter
ff85f902 1460 * @property int $dependency ID of another lesson this lesson is dependent on
1e7f8ea2
PS
1461 * @property string $conditions Conditions of the lesson dependency
1462 * @property int $grade The maximum grade a user can achieve (%)
1463 * @property int $custom Toggle custom scoring on or off
1464 * @property int $ongoing Toggle display of an ongoing score
1465 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1466 * @property int $maxanswers The max number of answers or branches
1467 * @property int $maxattempts The maximum number of attempts a user can record
1468 * @property int $review Toggle use or wrong answer review button
1469 * @property int $nextpagedefault Override the default next page
1470 * @property int $feedback Toggles display of default feedback
1471 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1472 * @property int $maxpages Maximum number of pages this lesson can contain
1473 * @property int $retake Flag to allow users to retake a lesson
1474 * @property int $activitylink Relate this lesson to another lesson
1475 * @property string $mediafile File to pop up to or webpage to display
1476 * @property int $mediaheight Sets the height of the media file popup
1477 * @property int $mediawidth Sets the width of the media file popup
1478 * @property int $mediaclose Toggle display of a media close button
1479 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1480 * @property int $width Width of slideshow
1481 * @property int $height Height of slideshow
1482 * @property string $bgcolor Background colour of slideshow
ff85f902 1483 * @property int $displayleft Display a left menu
1e7f8ea2
PS
1484 * @property int $displayleftif Sets the condition on which the left menu is displayed
1485 * @property int $progressbar Flag to toggle display of a lesson progress bar
1e7f8ea2
PS
1486 * @property int $available Timestamp of when this lesson becomes available
1487 * @property int $deadline Timestamp of when this lesson is no longer available
1488 * @property int $timemodified Timestamp when lesson was last modified
87e472bd 1489 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1e7f8ea2
PS
1490 *
1491 * These properties are calculated
1492 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1493 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1494 *
cc3dbaaa
PS
1495 * @copyright 2009 Sam Hemelryk
1496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
1497 */
1498class lesson extends lesson_base {
1499
1500 /**
1501 * The id of the first page (where prevpageid = 0) gets set and retrieved by
1502 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1503 * @var int
1504 */
1505 protected $firstpageid = null;
1506 /**
1507 * The id of the last page (where nextpageid = 0) gets set and retrieved by
1508 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1509 * @var int
1510 */
1511 protected $lastpageid = null;
1512 /**
1513 * An array used to cache the pages associated with this lesson after the first
1514 * time they have been loaded.
1515 * A note to developers: If you are going to be working with MORE than one or
1516 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1517 * in order to save excess database queries.
1518 * @var array An array of lesson_page objects
1519 */
1520 protected $pages = array();
1521 /**
1522 * Flag that gets set to true once all of the pages associated with the lesson
1523 * have been loaded.
1524 * @var bool
1525 */
1526 protected $loadedallpages = false;
1527
4a3391b6
JL
1528 /**
1529 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1530 * @see get_cm()
1531 * @var stdClass
1532 */
1533 protected $cm = null;
1534
7d7a2a4e
JL
1535 /**
1536 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1537 * @see get_courserecord()
1538 * @var stdClass
1539 */
1540 protected $courserecord = null;
1541
4a3391b6
JL
1542 /**
1543 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1544 * @see get_context()
1545 * @var stdClass
1546 */
1547 protected $context = null;
1548
1549 /**
1550 * Constructor method
1551 *
1552 * @param object $properties
1553 * @param stdClass $cm course module object
7d7a2a4e 1554 * @param stdClass $course course object
4a3391b6
JL
1555 * @since Moodle 3.3
1556 */
7d7a2a4e 1557 public function __construct($properties, $cm = null, $course = null) {
4a3391b6
JL
1558 parent::__construct($properties);
1559 $this->cm = $cm;
7d7a2a4e 1560 $this->courserecord = $course;
4a3391b6
JL
1561 }
1562
1e7f8ea2
PS
1563 /**
1564 * Simply generates a lesson object given an array/object of properties
1565 * Overrides {@see lesson_base->create()}
1566 * @static
1567 * @param object|array $properties
1568 * @return lesson
1569 */
1570 public static function create($properties) {
1571 return new lesson($properties);
1572 }
1573
1574 /**
1575 * Generates a lesson object from the database given its id
1576 * @static
1577 * @param int $lessonid
1578 * @return lesson
1579 */
1580 public static function load($lessonid) {
3983f2dc
PS
1581 global $DB;
1582
1e7f8ea2
PS
1583 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1584 print_error('invalidcoursemodule');
1585 }
1586 return new lesson($lesson);
1587 }
1588
1589 /**
1590 * Deletes this lesson from the database
1591 */
1592 public function delete() {
1593 global $CFG, $DB;
1594 require_once($CFG->libdir.'/gradelib.php');
1595 require_once($CFG->dirroot.'/calendar/lib.php');
1596
582ba677
FM
1597 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1598 $context = context_module::instance($cm->id);
1599
e0e1a83e
JMV
1600 $this->delete_all_overrides();
1601
0e35ba6f 1602 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1e7f8ea2
PS
1603 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1604 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1605 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1606 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1607 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1608 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1e7f8ea2 1609 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
70b62308 1610 $coursecontext = context_course::instance($cm->course);
1e7f8ea2 1611 foreach($events as $event) {
70b62308 1612 $event->context = $coursecontext;
e1cd93ce 1613 $event = calendar_event::load($event);
1e7f8ea2
PS
1614 $event->delete();
1615 }
1616 }
1617
582ba677
FM
1618 // Delete files associated with this module.
1619 $fs = get_file_storage();
1620 $fs->delete_area_files($context->id);
1621
ecea65ca 1622 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1e7f8ea2
PS
1623 return true;
1624 }
1625
e0e1a83e
JMV
1626 /**
1627 * Deletes a lesson override from the database and clears any corresponding calendar events
1628 *
1629 * @param int $overrideid The id of the override being deleted
1630 * @return bool true on success
1631 */
1632 public function delete_override($overrideid) {
1633 global $CFG, $DB;
1634
1635 require_once($CFG->dirroot . '/calendar/lib.php');
1636
1637 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1638
1639 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1640
1641 // Delete the events.
1642 $conds = array('modulename' => 'lesson',
1643 'instance' => $this->properties->id);
1644 if (isset($override->userid)) {
1645 $conds['userid'] = $override->userid;
1646 } else {
1647 $conds['groupid'] = $override->groupid;
1648 }
1649 $events = $DB->get_records('event', $conds);
1650 foreach ($events as $event) {
e1cd93ce 1651 $eventold = calendar_event::load($event);
e0e1a83e
JMV
1652 $eventold->delete();
1653 }
1654
1655 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1656
1657 // Set the common parameters for one of the events we will be triggering.
1658 $params = array(
1659 'objectid' => $override->id,
1660 'context' => context_module::instance($cm->id),
1661 'other' => array(
1662 'lessonid' => $override->lessonid
1663 )
1664 );
1665 // Determine which override deleted event to fire.
1666 if (!empty($override->userid)) {
1667 $params['relateduserid'] = $override->userid;
1668 $event = \mod_lesson\event\user_override_deleted::create($params);
1669 } else {
1670 $params['other']['groupid'] = $override->groupid;
1671 $event = \mod_lesson\event\group_override_deleted::create($params);
1672 }
1673
1674 // Trigger the override deleted event.
1675 $event->add_record_snapshot('lesson_overrides', $override);
1676 $event->trigger();
1677
1678 return true;
1679 }
1680
1681 /**
1682 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1683 */
1684 public function delete_all_overrides() {
1685 global $DB;
1686
1687 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1688 foreach ($overrides as $override) {
1689 $this->delete_override($override->id);
1690 }
1691 }
1692
1693 /**
1694 * Updates the lesson properties with override information for a user.
1695 *
1696 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1697 * then use that otherwise, if there are group-specific overrides, return the most
1698 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1699 *
1700 * Special case: if there is more than one password that applies to the user, then
1701 * lesson->extrapasswords will contain an array of strings giving the remaining
1702 * passwords.
1703 *
1704 * @param int $userid The userid.
1705 */
1706 public function update_effective_access($userid) {
1707 global $DB;
1708
1709 // Check for user override.
1710 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1711
1712 if (!$override) {
1713 $override = new stdClass();
1714 $override->available = null;
1715 $override->deadline = null;
1716 $override->timelimit = null;
1717 $override->review = null;
1718 $override->maxattempts = null;
1719 $override->retake = null;
1720 $override->password = null;
1721 }
1722
1723 // Check for group overrides.
1724 $groupings = groups_get_user_groups($this->properties->course, $userid);
1725
1726 if (!empty($groupings[0])) {
1727 // Select all overrides that apply to the User's groups.
1728 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1729 $sql = "SELECT * FROM {lesson_overrides}
1730 WHERE groupid $extra AND lessonid = ?";
1731 $params[] = $this->properties->id;
1732 $records = $DB->get_records_sql($sql, $params);
1733
1734 // Combine the overrides.
1735 $availables = array();
1736 $deadlines = array();
1737 $timelimits = array();
1738 $reviews = array();
1739 $attempts = array();
1740 $retakes = array();
1741 $passwords = array();
1742
1743 foreach ($records as $gpoverride) {
1744 if (isset($gpoverride->available)) {
1745 $availables[] = $gpoverride->available;
1746 }
1747 if (isset($gpoverride->deadline)) {
1748 $deadlines[] = $gpoverride->deadline;
1749 }
1750 if (isset($gpoverride->timelimit)) {
1751 $timelimits[] = $gpoverride->timelimit;
1752 }
1753 if (isset($gpoverride->review)) {
1754 $reviews[] = $gpoverride->review;
1755 }
1756 if (isset($gpoverride->maxattempts)) {
1757 $attempts[] = $gpoverride->maxattempts;
1758 }
1759 if (isset($gpoverride->retake)) {
1760 $retakes[] = $gpoverride->retake;
1761 }
1762 if (isset($gpoverride->password)) {
1763 $passwords[] = $gpoverride->password;
1764 }
1765 }
1766 // If there is a user override for a setting, ignore the group override.
1767 if (is_null($override->available) && count($availables)) {
1768 $override->available = min($availables);
1769 }
1770 if (is_null($override->deadline) && count($deadlines)) {
1771 if (in_array(0, $deadlines)) {
1772 $override->deadline = 0;
1773 } else {
1774 $override->deadline = max($deadlines);
1775 }
1776 }
1777 if (is_null($override->timelimit) && count($timelimits)) {
1778 if (in_array(0, $timelimits)) {
1779 $override->timelimit = 0;
1780 } else {
1781 $override->timelimit = max($timelimits);
1782 }
1783 }
1784 if (is_null($override->review) && count($reviews)) {
1785 $override->review = max($reviews);
1786 }
1787 if (is_null($override->maxattempts) && count($attempts)) {
1788 $override->maxattempts = max($attempts);
1789 }
1790 if (is_null($override->retake) && count($retakes)) {
1791 $override->retake = max($retakes);
1792 }
1793 if (is_null($override->password) && count($passwords)) {
1794 $override->password = array_shift($passwords);
1795 if (count($passwords)) {
1796 $override->extrapasswords = $passwords;
1797 }
1798 }
1799
1800 }
1801
1802 // Merge with lesson defaults.
1803 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1804 foreach ($keys as $key) {
1805 if (isset($override->{$key})) {
1806 $this->properties->{$key} = $override->{$key};
1807 }
1808 }
1809
1810 // Special handling of lesson usepassword and password.
1811 if (isset($override->password)) {
1812 if ($override->password == '') {
1813 $this->properties->usepassword = 0;
1814 } else {
1815 $this->properties->usepassword = 1;
1816 $this->properties->password = $override->password;
1817 if (isset($override->extrapasswords)) {
1818 $this->properties->extrapasswords = $override->extrapasswords;
1819 }
1820 }
1821 }
1822 }
1823
1e7f8ea2
PS
1824 /**
1825 * Fetches messages from the session that may have been set in previous page
1826 * actions.
1827 *
1828 * <code>
1829 * // Do not call this method directly instead use
1830 * $lesson->messages;
1831 * </code>
1832 *
1833 * @return array
1834 */
1835 protected function get_messages() {
1836 global $SESSION;
1837
1838 $messages = array();
1839 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1840 $messages = $SESSION->lesson_messages[$this->properties->id];
1841 unset($SESSION->lesson_messages[$this->properties->id]);
1842 }
1843
1844 return $messages;
1845 }
1846
1847 /**
1848 * Get all of the attempts for the current user.
1849 *
1850 * @param int $retries
1851 * @param bool $correct Optional: only fetch correct attempts
1852 * @param int $pageid Optional: only fetch attempts at the given page
1853 * @param int $userid Optional: defaults to the current user if not set
1854 * @return array|false
1855 */
1856 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1857 global $USER, $DB;
1858 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1859 if ($correct) {
1860 $params['correct'] = 1;
1861 }
1862 if ($pageid !== null) {
1863 $params['pageid'] = $pageid;
1864 }
1865 if ($userid === null) {
1866 $params['userid'] = $USER->id;
1867 }
ef4ba975 1868 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1e7f8ea2
PS
1869 }
1870
b584c49d
JL
1871
1872 /**
1873 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1874 *
1875 * @param int $lessonattempt the lesson attempt number (also known as retries)
1876 * @param int $userid the user id to retrieve the data from
1877 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter)
1878 * @param string $fields a comma separated list of fields to return
1879 * @return array of pages
1880 * @since Moodle 3.3
1881 */
1882 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1883 global $USER, $DB;
1884
1885 if ($userid === null) {
1886 $userid = $USER->id;
1887 }
1888 $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
1889 return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1890 }
1891
1e7f8ea2
PS
1892 /**
1893 * Returns the first page for the lesson or false if there isn't one.
1894 *
1895 * This method should be called via the magic method __get();
1896 * <code>
1897 * $firstpage = $lesson->firstpage;
1898 * </code>
1899 *
1900 * @return lesson_page|bool Returns the lesson_page specialised object or false
1901 */
1902 protected function get_firstpage() {
1903 $pages = $this->load_all_pages();
1904 if (count($pages) > 0) {
1905 foreach ($pages as $page) {
1906 if ((int)$page->prevpageid === 0) {
1907 return $page;
1908 }
1909 }
1910 }
1911 return false;
1912 }
1913
1914 /**
1915 * Returns the last page for the lesson or false if there isn't one.
1916 *
1917 * This method should be called via the magic method __get();
1918 * <code>
1919 * $lastpage = $lesson->lastpage;
1920 * </code>
1921 *
1922 * @return lesson_page|bool Returns the lesson_page specialised object or false
1923 */
1924 protected function get_lastpage() {
1925 $pages = $this->load_all_pages();
1926 if (count($pages) > 0) {
1927 foreach ($pages as $page) {
1928 if ((int)$page->nextpageid === 0) {
1929 return $page;
1930 }
1931 }
1932 }
1933 return false;
1934 }
1935
1936 /**
1937 * Returns the id of the first page of this lesson. (prevpageid = 0)
1938 * @return int
1939 */
1940 protected function get_firstpageid() {
1941 global $DB;
1942 if ($this->firstpageid == null) {
1943 if (!$this->loadedallpages) {
1944 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1945 if (!$firstpageid) {
1946 print_error('cannotfindfirstpage', 'lesson');
1947 }
1948 $this->firstpageid = $firstpageid;
1949 } else {
1950 $firstpage = $this->get_firstpage();
1951 $this->firstpageid = $firstpage->id;
1952 }
1953 }
1954 return $this->firstpageid;
1955 }
1956
1957 /**
1958 * Returns the id of the last page of this lesson. (nextpageid = 0)
1959 * @return int
1960 */
1961 public function get_lastpageid() {
1962 global $DB;
1963 if ($this->lastpageid == null) {
1964 if (!$this->loadedallpages) {
1965 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1966 if (!$lastpageid) {
1967 print_error('cannotfindlastpage', 'lesson');
1968 }
1969 $this->lastpageid = $lastpageid;
1970 } else {
1971 $lastpageid = $this->get_lastpage();
1972 $this->lastpageid = $lastpageid->id;
1973 }
1974 }
1975
1976 return $this->lastpageid;
1977 }
1978
1979 /**
0343553f 1980 * Gets the next page id to display after the one that is provided.
1e7f8ea2
PS
1981 * @param int $nextpageid
1982 * @return bool
1983 */
1984 public function get_next_page($nextpageid) {
3983f2dc 1985 global $USER, $DB;
1e7f8ea2
PS
1986 $allpages = $this->load_all_pages();
1987 if ($this->properties->nextpagedefault) {
1988 // in Flash Card mode...first get number of retakes
0343553f 1989 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1e7f8ea2
PS
1990 shuffle($allpages);
1991 $found = false;
1992 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1993 foreach ($allpages as $nextpage) {
0343553f 1994 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1e7f8ea2
PS
1995 $found = true;
1996 break;
1997 }
1998 }
1999 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
2000 foreach ($allpages as $nextpage) {
0343553f 2001 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1e7f8ea2
PS
2002 $found = true;
2003 break;
2004 }
2005 }
2006 }
2007 if ($found) {
2008 if ($this->properties->maxpages) {
2009 // check number of pages viewed (in the lesson)
0343553f
RW
2010 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
2011 return LESSON_EOL;
1e7f8ea2
PS
2012 }
2013 }
0343553f 2014 return $nextpage->id;
1e7f8ea2
PS
2015 }
2016 }
2017 // In a normal lesson mode
2018 foreach ($allpages as $nextpage) {
0343553f
RW
2019 if ((int)$nextpage->id === (int)$nextpageid) {
2020 return $nextpage->id;
1e7f8ea2
PS
2021 }
2022 }
0343553f 2023 return LESSON_EOL;
1e7f8ea2
PS
2024 }
2025
2026 /**
2027 * Sets a message against the session for this lesson that will displayed next
2028 * time the lesson processes messages
2029 *
2030 * @param string $message
2031 * @param string $class
2032 * @param string $align
2033 * @return bool
2034 */
2035 public function add_message($message, $class="notifyproblem", $align='center') {
2036 global $SESSION;
2037
2038 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
2039 $SESSION->lesson_messages = array();
2040 $SESSION->lesson_messages[$this->properties->id] = array();
2041 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
2042 $SESSION->lesson_messages[$this->properties->id] = array();
2043 }
2044
2045 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
2046
2047 return true;
2048 }
2049
2050 /**
2051 * Check if the lesson is accessible at the present time
2052 * @return bool True if the lesson is accessible, false otherwise
2053 */
2054 public function is_accessible() {
2055 $available = $this->properties->available;
2056 $deadline = $this->properties->deadline;
2057 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
2058 }
2059
2060 /**
2061 * Starts the lesson time for the current user
2062 * @return bool Returns true
2063 */
2064 public function start_timer() {
2065 global $USER, $DB;
9c192d81
MN
2066
2067 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2068 false, MUST_EXIST);
2069
2070 // Trigger lesson started event.
2071 $event = \mod_lesson\event\lesson_started::create(array(
2072 'objectid' => $this->properties()->id,
2073 'context' => context_module::instance($cm->id),
2074 'courseid' => $this->properties()->course
2075 ));
2076 $event->trigger();
2077
1e7f8ea2 2078 $USER->startlesson[$this->properties->id] = true;
87e472bd
JL
2079
2080 $timenow = time();
1e7f8ea2
PS
2081 $startlesson = new stdClass;
2082 $startlesson->lessonid = $this->properties->id;
2083 $startlesson->userid = $USER->id;
87e472bd
JL
2084 $startlesson->starttime = $timenow;
2085 $startlesson->lessontime = $timenow;
2086 if (WS_SERVER) {
2087 $startlesson->timemodifiedoffline = $timenow;
2088 }
1e7f8ea2 2089 $DB->insert_record('lesson_timer', $startlesson);
a1acc001
JMV
2090 if ($this->properties->timelimit) {
2091 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
1e7f8ea2
PS
2092 }
2093 return true;
2094 }
2095
2096 /**
2097 * Updates the timer to the current time and returns the new timer object
2098 * @param bool $restart If set to true the timer is restarted
2099 * @param bool $continue If set to true AND $restart=true then the timer
2100 * will continue from a previous attempt
2101 * @return stdClass The new timer
2102 */
25345cb4 2103 public function update_timer($restart=false, $continue=false, $endreached =false) {
1e7f8ea2 2104 global $USER, $DB;
e0f7b963
SB
2105
2106 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2107
1e7f8ea2
PS
2108 // clock code
2109 // get time information for this user
592c94f3 2110 if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
5ca2e765 2111 $this->start_timer();
592c94f3 2112 $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
1e7f8ea2 2113 }
5ca2e765 2114 $timer = current($timer); // This will get the latest start time record.
1e7f8ea2
PS
2115
2116 if ($restart) {
2117 if ($continue) {
2118 // continue a previous test, need to update the clock (think this option is disabled atm)
2119 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
e0f7b963
SB
2120
2121 // Trigger lesson resumed event.
2122 $event = \mod_lesson\event\lesson_resumed::create(array(
2123 'objectid' => $this->properties->id,
2124 'context' => context_module::instance($cm->id),
2125 'courseid' => $this->properties->course
2126 ));
2127 $event->trigger();
2128
1e7f8ea2
PS
2129 } else {
2130 // starting over, so reset the clock
2131 $timer->starttime = time();
e0f7b963
SB
2132
2133 // Trigger lesson restarted event.
2134 $event = \mod_lesson\event\lesson_restarted::create(array(
2135 'objectid' => $this->properties->id,
2136 'context' => context_module::instance($cm->id),
2137 'courseid' => $this->properties->course
2138 ));
2139 $event->trigger();
2140
1e7f8ea2
PS
2141 }
2142 }
2143
87e472bd
JL
2144 $timenow = time();
2145 $timer->lessontime = $timenow;
2146 if (WS_SERVER) {
2147 $timer->timemodifiedoffline = $timenow;
2148 }
25345cb4 2149 $timer->completed = $endreached;
1e7f8ea2 2150 $DB->update_record('lesson_timer', $timer);
4b570f71
JMV
2151
2152 // Update completion state.
2153 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2154 false, MUST_EXIST);
2155 $course = get_course($cm->course);
2156 $completion = new completion_info($course);
2157 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
2158 $completion->update_state($cm, COMPLETION_COMPLETE);
2159 }
1e7f8ea2
PS
2160 return $timer;
2161 }
2162
2163 /**
2164 * Updates the timer to the current time then stops it by unsetting the user var
2165 * @return bool Returns true
2166 */
2167 public function stop_timer() {
2168 global $USER, $DB;
2169 unset($USER->startlesson[$this->properties->id]);
00c027c7
MN
2170
2171 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2172 false, MUST_EXIST);
2173
2174 // Trigger lesson ended event.
2175 $event = \mod_lesson\event\lesson_ended::create(array(
2176 'objectid' => $this->properties()->id,
2177 'context' => context_module::instance($cm->id),
2178 'courseid' => $this->properties()->course
2179 ));
2180 $event->trigger();
2181
25345cb4 2182 return $this->update_timer(false, false, true);
1e7f8ea2
PS
2183 }
2184
2185 /**
2186 * Checks to see if the lesson has pages
2187 */
2188 public function has_pages() {
2189 global $DB;
2190 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
2191 return ($pagecount>0);
2192 }
2193
2194 /**
2195 * Returns the link for the related activity
457b3ed1 2196 * @return string
1e7f8ea2
PS
2197 */
2198 public function link_for_activitylink() {
2199 global $DB;
2200 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
2201 if ($module) {
2202 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
2203 if ($modname) {
2204 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
2205 if ($instancename) {
457b3ed1
LB
2206 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php',
2207 array('id' => $this->properties->activitylink)), get_string('activitylinkname',
2208 'lesson', $instancename), array('class' => 'centerpadded lessonbutton standardbutton p-r-1'));
1e7f8ea2
PS
2209 }
2210 }
2211 }
2212 return '';
2213 }
2214
2215 /**
2216 * Loads the requested page.
2217 *
2218 * This function will return the requested page id as either a specialised
2219 * lesson_page object OR as a generic lesson_page.
2220 * If the page has been loaded previously it will be returned from the pages
2221 * array, otherwise it will be loaded from the database first
2222 *
2223 * @param int $pageid
2224 * @return lesson_page A lesson_page object or an object that extends it
2225 */
2226 public function load_page($pageid) {
2227 if (!array_key_exists($pageid, $this->pages)) {
2228 $manager = lesson_page_type_manager::get($this);
2229 $this->pages[$pageid] = $manager->load_page($pageid, $this);
2230 }
2231 return $this->pages[$pageid];
2232 }
2233
2234 /**
2235 * Loads ALL of the pages for this lesson
2236 *
2237 * @return array An array containing all pages from this lesson
2238 */
2239 public function load_all_pages() {
2240 if (!$this->loadedallpages) {
2241 $manager = lesson_page_type_manager::get($this);
2242 $this->pages = $manager->load_all_pages($this);
2243 $this->loadedallpages = true;
2244 }
2245 return $this->pages;
2246 }
2247
9f937c3b
AG
2248 /**
2249 * Duplicate the lesson page.
2250 *
2251 * @param int $pageid Page ID of the page to duplicate.
2252 * @return void.
2253 */
2254 public function duplicate_page($pageid) {
2255 global $PAGE;
2256 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2257 $context = context_module::instance($cm->id);
2258 // Load the page.
2259 $page = $this->load_page($pageid);
2260 $properties = $page->properties();
2261 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2262 if (!$properties->qoption) {
2263 unset($properties->qoption);
2264 }
2265 if (!$properties->layout) {
2266 unset($properties->layout);
2267 }
2268 if (!$properties->display) {
2269 unset($properties->display);
2270 }
2271
2272 $properties->pageid = $pageid;
2273 // Add text and format into the format required to create a new page.
2274 $properties->contents_editor = array(
2275 'text' => $properties->contents,
2276 'format' => $properties->contentsformat
2277 );
2278 $answers = $page->get_answers();
2279 // Answers need to be added to $properties.
2280 $i = 0;
2281 $answerids = array();
2282 foreach ($answers as $answer) {
2283 // Needs to be rearranged to work with the create function.
2284 $properties->answer_editor[$i] = array(
2285 'text' => $answer->answer,
2286 'format' => $answer->answerformat
2287 );
2288
2289 $properties->response_editor[$i] = array(
2290 'text' => $answer->response,
2291 'format' => $answer->responseformat
2292 );
2293 $answerids[] = $answer->id;
2294
2295 $properties->jumpto[$i] = $answer->jumpto;
2296 $properties->score[$i] = $answer->score;
2297
2298 $i++;
2299 }
2300 // Create the duplicate page.
2301 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
2302 $newanswers = $newlessonpage->get_answers();
2303 // Copy over the file areas as well.
2304 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
2305 $j = 0;
2306 foreach ($newanswers as $answer) {
f4eef5fb 2307 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
9f937c3b
AG
2308 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
2309 }
f4eef5fb 2310 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
9f937c3b
AG
2311 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
2312 }
2313 $j++;
2314 }
2315 }
2316
2317 /**
2318 * Copy the files from one page to another.
2319 *
2320 * @param string $filearea Area that the files are stored.
2321 * @param int $itemid Item ID.
2322 * @param int $newitemid The item ID for the new page.
2323 * @param int $contextid Context ID for this page.
2324 * @return void.
2325 */
2326 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2327 $fs = get_file_storage();
2328 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2329 foreach ($files as $file) {
2330 $fieldupdates = array('itemid' => $newitemid);
2331 $fs->create_file_from_storedfile($fieldupdates, $file);
2332 }
2333 }
2334
1e7f8ea2 2335 /**
ff85f902 2336 * Determines if a jumpto value is correct or not.
1e7f8ea2
PS
2337 *
2338 * returns true if jumpto page is (logically) after the pageid page or
2339 * if the jumpto value is a special value. Returns false in all other cases.
2340 *
2341 * @param int $pageid Id of the page from which you are jumping from.
2342 * @param int $jumpto The jumpto number.
2343 * @return boolean True or false after a series of tests.
2344 **/
2345 public function jumpto_is_correct($pageid, $jumpto) {
2346 global $DB;
2347
2348 // first test the special values
2349 if (!$jumpto) {
2350 // same page
2351 return false;
2352 } elseif ($jumpto == LESSON_NEXTPAGE) {
2353 return true;
2354 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2355 return true;
2356 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2357 return true;
2358 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2359 return true;
2360 } elseif ($jumpto == LESSON_EOL) {
2361 return true;
2362 }
2363
2364 $pages = $this->load_all_pages();
2365 $apageid = $pages[$pageid]->nextpageid;
2366 while ($apageid != 0) {
2367 if ($jumpto == $apageid) {
2368 return true;
2369 }
2370 $apageid = $pages[$apageid]->nextpageid;
2371 }
2372 return false;
2373 }
2374
2375 /**
2376 * Returns the time a user has remaining on this lesson
2377 * @param int $starttime Starttime timestamp
2378 * @return string
2379 */
2380 public function time_remaining($starttime) {
e0e1a83e 2381 $timeleft = $starttime + $this->properties->timelimit - time();
1e7f8ea2
PS
2382 $hours = floor($timeleft/3600);
2383 $timeleft = $timeleft - ($hours * 3600);
2384 $minutes = floor($timeleft/60);
2385 $secs = $timeleft - ($minutes * 60);
2386
2387 if ($minutes < 10) {
2388 $minutes = "0$minutes";
2389 }
2390 if ($secs < 10) {
2391 $secs = "0$secs";
2392 }
2393 $output = array();
2394 $output[] = $hours;
2395 $output[] = $minutes;
2396 $output[] = $secs;
2397 $output = implode(':', $output);
2398 return $output;
2399 }
2400
2401 /**
2402 * Interprets LESSON_CLUSTERJUMP jumpto value.
2403 *
2404 * This will select a page randomly
ff85f902 2405 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1e7f8ea2
PS
2406 * and the page selected will be a page that has not been viewed already
2407 * and if any pages are within a branch table or end of branch then only 1 page within
2408 * the branch table or end of branch will be randomly selected (sub clustering).
2409 *
2410 * @param int $pageid Id of the current page from which we are jumping from.
2411 * @param int $userid Id of the user.
2412 * @return int The id of the next page.
2413 **/
2414 public function cluster_jump($pageid, $userid=null) {
2415 global $DB, $USER;
2416
2417 if ($userid===null) {
2418 $userid = $USER->id;
2419 }
2420 // get the number of retakes
2421 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
2422 $retakes = 0;
2423 }
2424 // get all the lesson_attempts aka what the user has seen
2425 $seenpages = array();
2426 if ($attempts = $this->get_attempts($retakes)) {
2427 foreach ($attempts as $attempt) {
2428 $seenpages[$attempt->pageid] = $attempt->pageid;
2429 }
2430
2431 }
2432
2433 // get the lesson pages
2434 $lessonpages = $this->load_all_pages();
2435 // find the start of the cluster
2436 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2437 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
2438 break;
2439 }
2440 $pageid = $lessonpages[$pageid]->prevpageid;
2441 }
2442
2443 $clusterpages = array();
2444 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
2445 $unseen = array();
2446 foreach ($clusterpages as $key=>$cluster) {
fc16a1ac
JMV
2447 // Remove the page if it is in a branch table or is an endofbranch.
2448 if ($this->is_sub_page_of_type($cluster->id,
2449 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
2450 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1e7f8ea2 2451 unset($clusterpages[$key]);
fc16a1ac
JMV
2452 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
2453 // If branchtable, check to see if any pages inside have been viewed.
2454 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2455 $flag = true;
2456 foreach ($branchpages as $branchpage) {
2457 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
2458 $flag = false;
2459 }
2460 }
2461 if ($flag && count($branchpages) > 0) {
2462 // Add branch table.
2463 $unseen[] = $cluster;
2464 }
1e7f8ea2
PS
2465 } elseif ($cluster->is_unseen($seenpages)) {
2466 $unseen[] = $cluster;
2467 }
2468 }
2469
2470 if (count($unseen) > 0) {
2471 // it does not contain elements, then use exitjump, otherwise find out next page/branch
2472 $nextpage = $unseen[rand(0, count($unseen)-1)];
2473 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
2474 // if branch table, then pick a random page inside of it
2475 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2476 return $branchpages[rand(0, count($branchpages)-1)]->id;
2477 } else { // otherwise, return the page's id
2478 return $nextpage->id;
2479 }
2480 } else {
2481 // seen all there is to see, leave the cluster
2482 if (end($clusterpages)->nextpageid == 0) {
2483 return LESSON_EOL;
2484 } else {
2485 $clusterendid = $pageid;
a30e935a
JMV
2486 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2487 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1e7f8ea2
PS
2488 break;
2489 }
a30e935a 2490 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1e7f8ea2
PS
2491 }
2492 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
2493 if ($exitjump == LESSON_NEXTPAGE) {
a30e935a 2494 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1e7f8ea2
PS
2495 }
2496 if ($exitjump == 0) {
2497 return LESSON_EOL;
2498 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
2499 return $exitjump;
2500 } else {
2501 if (!array_key_exists($exitjump, $lessonpages)) {
2502 $found = false;
2503 foreach ($lessonpages as $page) {
2504 if ($page->id === $clusterendid) {
2505 $found = true;
2506 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2507 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
0d4705c7
JMV
2508 if ($exitjump == LESSON_NEXTPAGE) {
2509 $exitjump = $lessonpages[$page->id]->nextpageid;
2510 }
1e7f8ea2
PS
2511 break;
2512 }
2513 }
2514 }
2515 if (!array_key_exists($exitjump, $lessonpages)) {
2516 return LESSON_EOL;
2517 }
2518 return $exitjump;
2519 }
2520 }
2521 }
2522 }
2523
2524 /**
2525 * Finds all pages that appear to be a subtype of the provided pageid until
2526 * an end point specified within $ends is encountered or no more pages exist
2527 *
2528 * @param int $pageid
2529 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2530 * the subtype
2531 * @return array An array of specialised lesson_page objects
2532 */
2533 public function get_sub_pages_of($pageid, array $ends) {
2534 $lessonpages = $this->load_all_pages();
2535 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
2536 $pages = array();
2537
2538 while (true) {
2539 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2540 break;
2541 }
2542 $pages[] = $lessonpages[$pageid];
2543 $pageid = $lessonpages[$pageid]->nextpageid;
2544 }
2545
2546 return $pages;
2547 }
2548
2549 /**
2550 * Checks to see if the specified page[id] is a subpage of a type specified in
2551 * the $types array, until either there are no more pages of we find a type
ff85f902 2552 * corresponding to that of a type specified in $ends
1e7f8ea2
PS
2553 *
2554 * @param int $pageid The id of the page to check
2555 * @param array $types An array of types that would signify this page was a subpage
2556 * @param array $ends An array of types that mean this is not a subpage
2557 * @return bool
2558 */
2559 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2560 $pages = $this->load_all_pages();
2561 $pageid = $pages[$pageid]->prevpageid; // move up one
2562
2563 array_unshift($ends, 0);
2564 // go up the pages till branch table
2565 while (true) {
2566 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2567 return false;
2568 } else if (in_array($pages[$pageid]->qtype, $types)) {
2569 return true;
2570 }
2571 $pageid = $pages[$pageid]->prevpageid;
2572 }
2573 }
b7bfbfee
DM
2574
2575 /**
2576 * Move a page resorting all other pages.
2577 *
2578 * @param int $pageid
2579 * @param int $after
2580 * @return void
2581 */
2582 public function resort_pages($pageid, $after) {
2583 global $CFG;
2584
2585 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2586 $context = context_module::instance($cm->id);
2587
2588 $pages = $this->load_all_pages();
2589
2590 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2591 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2592 }
2593
2594 $pagetomove = clone($pages[$pageid]);
2595 unset($pages[$pageid]);
2596
2597 $pageids = array();
2598 if ($after === 0) {
2599 $pageids['p0'] = $pageid;
2600 }
2601 foreach ($pages as $page) {
2602 $pageids[] = $page->id;
2603 if ($page->id == $after) {
2604 $pageids[] = $pageid;
2605 }
2606 }
2607
2608 $pageidsref = $pageids;
2609 reset($pageidsref);
2610 $prev = 0;
2611 $next = next($pageidsref);
2612 foreach ($pageids as $pid) {
2613 if ($pid === $pageid) {
2614 $page = $pagetomove;
2615 } else {
2616 $page = $pages[$pid];
2617 }
2618 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2619 $page->move($next, $prev);
2620
2621 if ($pid === $pageid) {
2622 // We will trigger an event.
2623 $pageupdated = array('next' => $next, 'prev' => $prev);
2624 }
2625 }
2626
2627 $prev = $page->id;
2628 $next = next($pageidsref);
2629 if (!$next) {
2630 $next = 0;
2631 }
2632 }
2633
2634 // Trigger an event: page moved.
2635 if (!empty($pageupdated)) {
2636 $eventparams = array(
2637 'context' => $context,
2638 'objectid' => $pageid,
2639 'other' => array(
2640 'pagetype' => $page->get_typestring(),
2641 'prevpageid' => $pageupdated['prev'],
2642 'nextpageid' => $pageupdated['next']
2643 )
2644 );
2645 $event = \mod_lesson\event\page_moved::create($eventparams);
2646 $event->trigger();
2647 }
2648
2649 }
4a3391b6
JL
2650
2651 /**
2652 * Return the lesson context object.
2653 *
2654 * @return stdClass context
2655 * @since Moodle 3.3
2656 */
2657 public function get_context() {
2658 if ($this->context == null) {
2659 $this->context = context_module::instance($this->get_cm()->id);
2660 }
2661 return $this->context;
2662 }
2663
2664 /**
2665 * Set the lesson course module object.
2666 *
2667 * @param stdClass $cm course module objct
2668 * @since Moodle 3.3
2669 */
2670 private function set_cm($cm) {
2671 $this->cm = $cm;
2672 }
2673
2674 /**
2675 * Return the lesson course module object.
2676 *
2677 * @return stdClass course module
2678 * @since Moodle 3.3
2679 */
2680 public function get_cm() {
2681 if ($this->cm == null) {
2682 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2683 }
2684 return $this->cm;
2685 }
2686
7d7a2a4e
JL
2687 /**
2688 * Set the lesson course object.
2689 *
2690 * @param stdClass $course course objct
2691 * @since Moodle 3.3
2692 */
2693 private function set_courserecord($course) {
2694 $this->courserecord = $course;
2695 }
2696
2697 /**
2698 * Return the lesson course object.
2699 *
2700 * @return stdClass course
2701 * @since Moodle 3.3
2702 */
2703 public function get_courserecord() {
2704 global $DB;
2705
2706 if ($this->courserecord == null) {
2707 $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2708 }
2709 return $this->courserecord;
2710 }
2711
4a3391b6
JL
2712 /**
2713 * Check if the user can manage the lesson activity.
2714 *
2715 * @return bool true if the user can manage the lesson
2716 * @since Moodle 3.3
2717 */
2718 public function can_manage() {
2719 return has_capability('mod/lesson:manage', $this->get_context());
2720 }
2721
2722 /**
2723 * Check if time restriction is applied.
2724 *
2725 * @return mixed false if there aren't restrictions or an object with the restriction information
2726 * @since Moodle 3.3
2727 */
2728 public function get_time_restriction_status() {
2729 if ($this->can_manage()) {
2730 return false;
2731 }
2732
2733 if (!$this->is_accessible()) {
2734 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2735 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2736 } else {
2737 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2738 }
2739 return (object) $status;
2740 }
2741 return false;
2742 }
2743
2744 /**
2745 * Check if password restriction is applied.
2746 *
2747 * @param string $userpassword the user password to check (if the restriction is set)
2748 * @return mixed false if there aren't restrictions or an object with the restriction information
2749 * @since Moodle 3.3
2750 */
2751 public function get_password_restriction_status($userpassword) {
2752 global $USER;
2753 if ($this->can_manage()) {
2754 return false;
2755 }
2756
2757 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2758 $correctpass = false;
2759 if (!empty($userpassword) &&
2760 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2761 // With or without md5 for backward compatibility (MDL-11090).
2762 $correctpass = true;
2763 $USER->lessonloggedin[$this->id] = true;
2764 } else if (isset($this->properties->extrapasswords)) {
2765 // Group overrides may have additional passwords.
2766 foreach ($this->properties->extrapasswords as $password) {
2767 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2768 $correctpass = true;
2769 $USER->lessonloggedin[$this->id] = true;
2770 }
2771 }
2772 }
2773 return !$correctpass;
2774 }
2775 return false;
2776 }
2777
2778 /**
2779 * Check if dependencies restrictions are applied.
2780 *
2781 * @return mixed false if there aren't restrictions or an object with the restriction information
2782 * @since Moodle 3.3
2783 */
2784 public function get_dependencies_restriction_status() {
2785 global $DB, $USER;
2786 if ($this->can_manage()) {
2787 return false;
2788 }
2789
2790 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2791 // Lesson exists, so we can proceed.
2792 $conditions = unserialize($this->properties->conditions);
2793 // Assume false for all.
2794 $errors = array();
2795 // Check for the timespent condition.
2796 if ($conditions->timespent) {
2797 $timespent = false;
2798 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2799 // Go through all the times and test to see if any of them satisfy the condition.
2800 foreach ($attempttimes as $attempttime) {
2801 $duration = $attempttime->lessontime - $attempttime->starttime;
2802 if ($conditions->timespent < $duration / 60) {
2803 $timespent = true;
2804 }
2805 }
2806 }
2807 if (!$timespent) {
2808 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2809 }
2810 }
2811 // Check for the gradebetterthan condition.
2812 if ($conditions->gradebetterthan) {
2813 $gradebetterthan = false;
2814 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2815 // Go through all the grades and test to see if any of them satisfy the condition.
2816 foreach ($studentgrades as $studentgrade) {
2817 if ($studentgrade->grade >= $conditions->gradebetterthan) {
2818 $gradebetterthan = true;
2819 }
2820 }
2821 }
2822 if (!$gradebetterthan) {
2823 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2824 }
2825 }
2826 // Check for the completed condition.
2827 if ($conditions->completed) {
2828 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2829 $errors[] = get_string('completederror', 'lesson');
2830 }
2831 }
2832 if (!empty($errors)) {
2833 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2834 }
2835 }
2836 return false;
2837 }
37029e46
JL
2838
2839 /**
2840 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2841 *
2842 * @return bool true if is in review mode
2843 * @since Moodle 3.3
2844 */
2845 public function is_in_review_mode() {
2846 global $DB, $USER;
2847
2848 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2849 if ($userhasgrade && !$this->properties->retake) {
2850 return true;
2851 }
2852 return false;
2853 }
2854
2855 /**
2856 * Return the last page the current user saw.
2857 *
2858 * @param int $retriescount the number of retries for the lesson (the last retry number).
2859 * @return mixed false if the user didn't see the lesson or the last page id
2860 */
2861 public function get_last_page_seen($retriescount) {
2862 global $DB, $USER;
2863
2864 $lastpageseen = false;
2865 $allattempts = $this->get_attempts($retriescount);
2866 if (!empty($allattempts)) {
2867 $attempt = end($allattempts);
2868 $attemptpage = $this->load_page($attempt->pageid);
2869 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2870 // Convert the jumpto to a proper page id.
2871 if ($jumpto == 0) {
2872 // Check if a question has been incorrectly answered AND no more attempts at it are left.
2873 $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2874 if (count($nattempts) >= $this->properties->maxattempts) {
2875 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2876 } else {
2877 $lastpageseen = $attempt->pageid;
2878 }
2879 } else if ($jumpto == LESSON_NEXTPAGE) {
2880 $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2881 } else if ($jumpto == LESSON_CLUSTERJUMP) {
2882 $lastpageseen = $this->cluster_jump($attempt->pageid);
2883 } else {
2884 $lastpageseen = $jumpto;
2885 }
2886 }
2887
b584c49d 2888 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
37029e46
JL
2889 // In here, user has viewed a branch table.
2890 $lastbranchtable = current($branchtables);
2891 if (count($allattempts) > 0) {
2892 if ($lastbranchtable->timeseen > $attempt->timeseen) {
2893 // This branch table was viewed more recently than the question page.
2894 if (!empty($lastbranchtable->nextpageid)) {
2895 $lastpageseen = $lastbranchtable->nextpageid;
2896 } else {
2897 // Next page ID did not exist prior to MDL-34006.
2898 $lastpageseen = $lastbranchtable->pageid;
2899 }
2900 }
2901 } else {
2902 // Has not answered any questions but has viewed a branch table.
2903 if (!empty($lastbranchtable->nextpageid)) {
2904 $lastpageseen = $lastbranchtable->nextpageid;
2905 } else {
2906 // Next page ID did not exist prior to MDL-34006.
2907 $lastpageseen = $lastbranchtable->pageid;
2908 }
2909 }
2910 }
2911 return $lastpageseen;
2912 }
2913
2914 /**
2915 * Return the number of retries in a lesson for a given user.
2916 *
2917 * @param int $userid the user id
2918 * @return int the retries count
2919 * @since Moodle 3.3
2920 */
2921 public function count_user_retries($userid) {
2922 global $DB;
2923
2924 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
2925 }
2926
2927 /**
2928 * Check if a user left a timed session.
2929 *
2930 * @param int $retriescount the number of retries for the lesson (the last retry number).
2931 * @return true if the user left the timed session
7d7a2a4e 2932 * @since Moodle 3.3
37029e46
JL
2933 */
2934 public function left_during_timed_session($retriescount) {
2935 global $DB, $USER;
2936
2937 $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
2938 return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
2939 }
7d7a2a4e
JL
2940
2941 /**
2942 * Trigger module viewed event and set the module viewed for completion.
2943 *
2944 * @since Moodle 3.3
2945 */
2946 public function set_module_viewed() {
2947 global $CFG;
2948 require_once($CFG->libdir . '/completionlib.php');
2949
2950 // Trigger module viewed event.
2951 $event = \mod_lesson\event\course_module_viewed::create(array(
2952 'objectid' => $this->properties->id,
2953 'context' => $this->get_context()
2954 ));
2955 $event->add_record_snapshot('course_modules', $this->get_cm());
2956 $event->add_record_snapshot('course', $this->get_courserecord());
2957 $event->trigger();
2958
2959 // Mark as viewed.
2960 $completion = new completion_info($this->get_courserecord());
2961 $completion->set_module_viewed($this->get_cm());
2962 }
592c94f3
JL
2963
2964 /**
2965 * Return the timers in the current lesson for the given user.
2966 *
2967 * @param int $userid the user id
2968 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
2969 * @param string $fields a comma separated list of fields to return
2970 * @param int $limitfrom return a subset of records, starting at this point (optional).
2971 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
2972 * @return array list of timers for the given user in the lesson
2973 * @since Moodle 3.3
2974 */
2975 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
2976 global $DB, $USER;
2977
2978 if ($userid === null) {
2979 $userid = $USER->id;
2980 }
2981
2982 $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
2983 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
2984 }
dbba944e
JL
2985
2986 /**
2987 * Check if the user is out of time in a timed lesson.
2988 *
2989 * @param stdClass $timer timer object
2990 * @return bool True if the user is on time, false is the user ran out of time
2991 * @since Moodle 3.3
2992 */
2993 public function check_time($timer) {
2994 if ($this->properties->timelimit) {
2995 $timeleft = $timer->starttime + $this->properties->timelimit - time();
2996 if ($timeleft <= 0) {
2997 // Out of time.
2998 $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
2999 return false;
3000 } else if ($timeleft < 60) {
3001 // One minute warning.
3002 $this->add_message(get_string('studentoneminwarning', 'lesson'));
3003 }
3004 }
3005 return true;
3006 }
3007
3008 /**
3009 * Add different informative messages to the given page.
3010 *
3011 * @param lesson_page $page page object
3012 * @param reviewmode $bool whether we are in review mode or not
3013 * @since Moodle 3.3
3014 */
3015 public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
3016 global $DB, $USER;
3017
3018 if (!$this->can_manage()) {
3019 if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
3020 // Tell student how many questions they have seen, how many are required and their grade.
3021 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3022 $gradeinfo = lesson_grade($this, $ntries);
3023 if ($gradeinfo->attempts) {
3024 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3025 $a = new stdClass;
3026 $a->nquestions = $gradeinfo->nquestions;
3027 $a->minquestions = $this->properties->minquestions;
3028 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3029 }
3030
2034f57f 3031 if (!$reviewmode && $this->properties->ongoing) {
dbba944e
JL
3032 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
3033 if ($this->properties->grade != GRADE_TYPE_NONE) {
3034 $a = new stdClass;
3035 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3036 $a->total = $this->properties->grade;
3037 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3038 }
3039 }
3040 }
3041 }
3042 } else {
3043 if ($this->properties->timelimit) {
3044 $this->add_message(get_string('teachertimerwarning', 'lesson'));
3045 }
3046 if (lesson_display_teacher_warning($this)) {
3047 // This is the warning msg for teachers to inform them that cluster
3048 // and unseen does not work while logged in as a teacher.
3049 $warningvars = new stdClass();
3050 $warningvars->cluster = get_string('clusterjump', 'lesson');
3051 $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
3052 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3053 }
3054 }
3055 }
66cd7b8e
JL
3056
3057 /**
3058 * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3059 *
3060 * @return str the ongoing score message
3061 * @since Moodle 3.3
3062 */
3063 public function get_ongoing_score_message() {
3064 global $USER, $DB;
3065
3066 $context = $this->get_context();
3067
3068 if (has_capability('mod/lesson:manage', $context)) {
3069 return get_string('teacherongoingwarning', 'lesson');
3070 } else {
3071 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3072 if (isset($USER->modattempts[$this->properties->id])) {
3073 $ntries--;
3074 }
3075 $gradeinfo = lesson_grade($this, $ntries);
3076 $a = new stdClass;
3077 if ($this->properties->custom) {
3078 $a->score = $gradeinfo->earned;
3079 $a->currenthigh = $gradeinfo->total;
3080 return get_string("ongoingcustom", "lesson", $a);
3081 } else {
3082 $a->correct = $gradeinfo->earned;
3083 $a->viewed = $gradeinfo->attempts;
3084 return get_string("ongoingnormal", "lesson", $a);
3085 }
3086 }
3087 }
3088
3089 /**
3090 * Calculate the progress of the current user in the lesson.
3091 *
3092 * @return int the progress (scale 0-100)
3093 * @since Moodle 3.3
3094 */
3095 public function calculate_progress() {
3096 global $USER, $DB;
3097
3098 // Check if the user is reviewing the attempt.
3099 if (isset($USER->modattempts[$this->properties->id])) {
3100 return 100;
3101 }
3102
3103 // All of the lesson pages.
3104 $pages = $this->load_all_pages();
3105 foreach ($pages as $page) {
3106 if ($page->prevpageid == 0) {
3107 $pageid = $page->id; // Find the first page id.
3108 break;
3109 }
3110 }
3111
3112 // Current attempt number.
3113 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
3114 $ntries = 0; // May not be necessary.
3115 }
3116
3117 $viewedpageids = array();
3118 if ($attempts = $this->get_attempts($ntries, false)) {
3119 foreach ($attempts as $attempt) {
3120 $viewedpageids[$attempt->pageid] = $attempt;
3121 }
3122 }
3123
3124 $viewedbranches = array();
3125 // Collect all of the branch tables viewed.
3126 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
3127 foreach ($branches as $branch) {
3128 $viewedbranches[$branch->pageid] = $branch;
3129 }
3130 $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3131 }
3132
3133 // Filter out the following pages:
3134 // - End of Cluster
3135 // - End of Branch
3136 // - Pages found inside of Clusters
3137 // Do not filter out Cluster Page(s) because we count a cluster as one.
3138 // By keeping the cluster page, we get our 1.
3139 $validpages = array();
3140 while ($pageid != 0) {
3141 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3142 }
3143
3144 // Progress calculation as a percent.
16ca026c
JL
3145 $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3146 return (int) $progress;
66cd7b8e
JL
3147 }
3148
3149 /**
3150 * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3151 *
3152 * @param int $pageid the given page id
3153 * @param mod_lesson_renderer $lessonoutput the lesson output rendered
3154 * @param bool $reviewmode whether we are in review mode or not
0259109f 3155 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect.
66cd7b8e
JL
3156 * @return array the page object and contents
3157 * @throws moodle_exception
3158 * @since Moodle 3.3
3159 */
0259109f 3160 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
66cd7b8e
JL
3161 global $USER, $CFG;
3162
3163 $page = $this->load_page($pageid);
3164 // Check if the page is of a special type and if so take any nessecary action.
0259109f
JL
3165 $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3166
3167 // Avoid redirections returning the jump to special page id.
3168 if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3169 return array($newpageid, null, null);
3170 }
3171
66cd7b8e
JL
3172 if (is_numeric($newpageid)) {
3173 $page = $this->load_page($newpageid);
3174 }
3175
3176 // Add different informative messages to the given page.
3177 $this->add_messages_on_page_view($page, $reviewmode);
3178
3179 if (is_array($page->answers) && count($page->answers) > 0) {
3180 // This is for modattempts option. Find the users previous answer to this page,
3181 // and then display it below in answer processing.
3182 if (isset($USER->modattempts[$this->properties->id])) {
3183 $retries = $this->count_user_retries($USER->id);
3184 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
3185 throw new moodle_exception('cannotfindpreattempt', 'lesson');
3186 }
3187 $attempt = end($attempts);
3188 $USER->modattempts[$this->properties->id] = $attempt;
3189 } else {
3190 $attempt = false;
3191 }
3192 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3193 } else {
3194 require_once($CFG->dirroot . '/mod/lesson/view_form.php');
3195 $data = new stdClass;
3196 $data->id = $this->get_cm()->id;
3197 $data->pageid = $page->id;
3198 $data->newpageid = $this->get_next_page($page->nextpageid);
3199
3200 $customdata = array(
3201 'title' => $page->title,
3202 'contents' => $page->get_contents()
3203 );
3204 $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
3205 $mform->set_data($data);
3206 ob_start();
3207 $mform->display();
3208 $lessoncontent = ob_get_contents();
3209 ob_end_clean();
3210 }
3211
0259109f 3212 return array($page->id, $page, $lessoncontent);
66cd7b8e 3213 }
61b51764
JL
3214
3215 /**
707d50d1 3216 * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
61b51764 3217 *
707d50d1
JL
3218 * @param lesson_page $page lesson page
3219 * @param int $newpageid the new page id
3220 * @return int the real page to jump to (or end of lesson)
61b51764
JL
3221 * @since Moodle 3.3
3222 */
707d50d1 3223 public function calculate_new_page_on_jump(lesson_page $page, $newpageid) {
61b51764
JL
3224 global $USER, $DB;
3225
3226 $canmanage = $this->can_manage();
61b51764 3227
707d50d1 3228 if (isset($USER->modattempts[$this->properties->id])) {
61b51764 3229 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
e1f88fe7 3230 if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) {
61b51764 3231 // Remember, this session variable holds the pageid of the last page that the user saw.
707d50d1 3232 $newpageid = LESSON_EOL;
61b51764 3233 } else {
e1f88fe7 3234 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
61b51764 3235 $nretakes--; // Make sure we are looking at the right try.
e1f88fe7 3236 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
61b51764
JL
3237 $found = false;
3238 $temppageid = 0;
3239 // Make sure that the newpageid always defaults to something valid.
707d50d1 3240 $newpageid = LESSON_EOL;
61b51764
JL
3241 foreach ($attempts as $attempt) {
3242 if ($found && $temppageid != $attempt->pageid) {
3243 // Now try to find the next page, make sure next few attempts do no belong to current page.
707d50d1 3244 $newpageid = $attempt->pageid;
61b51764
JL
3245 break;
3246 }
3247 if ($attempt->pageid == $page->id) {
3248 $found = true; // If found current page.
3249 $temppageid = $attempt->pageid;
3250 }
3251 }
3252 }
707d50d1 3253 } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) {
61b51764
JL
3254 // Going to check to see if the page that the user is going to view next, is a cluster page.
3255 // If so, dont display, go into the cluster.
707d50d1
JL
3256 // The $newpageid > 0 is used to filter out all of the negative code jumps.
3257 $newpage = $this->load_page($newpageid);
3258 if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3259 $newpageid = $overridenewpageid;
61b51764 3260 }
707d50d1 3261 } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) {
61b51764
JL
3262 if ($canmanage) {
3263 if ($page->nextpageid == 0) {
707d50d1 3264 $newpageid = LESSON_EOL;
61b51764 3265 } else {
707d50d1 3266 $newpageid = $page->nextpageid;
61b51764
JL
3267 }
3268 } else {
707d50d1 3269 $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id);
61b51764 3270 }
707d50d1
JL
3271 } else if ($newpageid == LESSON_PREVIOUSPAGE) {
3272 $newpageid = $page->prevpageid;
3273 } else if ($newpageid == LESSON_RANDOMPAGE) {
3274 $newpageid = lesson_random_question_jump($this, $page->id);
3275 } else if ($newpageid == LESSON_CLUSTERJUMP) {
61b51764
JL
3276 if ($canmanage) {
3277 if ($page->nextpageid == 0) { // If teacher, go to next page.
707d50d1 3278 $newpageid = LESSON_EOL;
61b51764 3279 } else {
707d50d1 3280 $newpageid = $page->nextpageid;
61b51764
JL
3281 }
3282 } else {
707d50d1 3283 $newpageid = $this->cluster_jump($page->id);
61b51764 3284 }
707d50d1
JL
3285 } else if ($newpageid == 0) {
3286 $newpageid = $page->id;
3287 } else if ($newpageid == LESSON_NEXTPAGE) {
3288 $newpageid = $this->get_next_page($page->nextpageid);
61b51764 3289 }
707d50d1
JL
3290
3291 return $newpageid;
3292 }
3293
3294 /**
3295 * Process page responses.
3296 *
3297 * @param lesson_page $page page object
3298 * @since Moodle 3.3
3299 */
3300 public function process_page_responses(lesson_page $page) {
3301 $context = $this->get_context();
3302
3303 // Check the page has answers [MDL-25632].
3304 if (count($page->answers) > 0) {
3305 $result = $page->record_attempt($context);
3306 } else {
3307 // The page has no answers so we will just progress to the next page in the
3308 // sequence (as set by newpageid).
3309 $result = new stdClass;
3310 $result->newpageid = optional_param('newpageid', $page->nextpageid, PARAM_INT);
3311 $result->nodefaultresponse = true;
e7a11c20 3312 $result->inmediatejump = false;
707d50d1
JL
3313 }
3314
3315 if ($result->inmediatejump) {
3316 return $result;
3317 }
3318
3319 $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);
3320
61b51764
JL
3321 return $result;
3322 }
3323
3324 /**
3325 * Add different informative messages to the given page.
3326 *
3327 * @param lesson_page $page page object
3328 * @param stdClass $result the page processing result object
3329 * @param bool $reviewmode whether we are in review mode or not
3330 * @since Moodle 3.3
3331 */
3332 public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
3333
3334 if ($this->can_manage()) {
3335 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3336 if (lesson_display_teacher_warning($this)) {
3337 $warningvars = new stdClass();
3338 $warningvars->cluster = get_string("clusterjump", "lesson");
3339 $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
3340 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3341 }
3342 // Inform teacher that s/he will not see the timer.
3343 if ($this->properties->timelimit) {
d96d7295 3344 $this->add_message(get_string("teachertimerwarning", "lesson"));
61b51764
JL
3345 }
3346 }
3347 // Report attempts remaining.
3348 if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
3349 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
3350 }
3351 }
dfcabd3b
JL
3352
3353 /**
3354 * Process and return all the information for the end of lesson page.
3355 *
3356 * @param string $outoftime used to check to see if the student ran out of time
3357 * @return stdclass an object with all the page data ready for rendering
3358 * @since Moodle 3.3
3359 */
3360 public function process_eol_page($outoftime) {
3361 global $DB, $USER;
3362
3363 $course = $this->get_courserecord();
3364 $cm = $this->get_cm();
3365 $canmanage = $this->can_manage();
3366
3367 // Init all the possible fields and values.
3368 $data = (object) array(
3369 'gradelesson' => true,
3370 'notenoughtimespent' => false,
3371 'numberofpagesviewed' => false,
3372 'youshouldview' => false,
3373 'numberofcorrectanswers' => false,
3374 'displayscorewithessays' => false,
3375 'displayscorewithoutessays' => false,
3376 'yourcurrentgradeisoutof' => false,
3377 'eolstudentoutoftimenoanswers' => false,
3378 'welldone' => false,
3379 'progressbar' => false,
3380 'displayofgrade' => false,
3381 'reviewlesson' => false,
3382 'modattemptsnoteacher' => false,
3383 'activitylink' => false,
f3d9512d 3384 'progresscompleted' => false,
dfcabd3b
JL
3385 );
3386
3387 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3388 if (isset($USER->modattempts[$this->properties->id])) {
3389 $ntries--; // Need to look at the old attempts :).
3390 }
3391
3392 $gradeinfo = lesson_grade($this, $ntries);
3393 $data->gradeinfo = $gradeinfo;
3394 if ($this->properties->custom && !$canmanage) {
3395 // Before we calculate the custom score make sure they answered the minimum
3396 // number of questions. We only need to do this for custom scoring as we can
3397 // not get the miniumum score the user should achieve. If we are not using
3398 // custom scoring (so all questions are valued as 1) then we simply check if
3399 // they answered more than the minimum questions, if not, we mark it out of the
3400 // number specified in the minimum questions setting - which is done in lesson_grade().
3401 // Get the number of answers given.
3402 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3403 $data->gradelesson = false;
3404 $a = new stdClass;
3405 $a->nquestions = $gradeinfo->nquestions;
3406 $a->minquestions = $this->properties->minquestions;
3407 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3408 }
3409 }
3410
3411 if (!$canmanage) {
3412 if ($data->gradelesson) {
3413 // Store this now before any modifications to pages viewed.
3414 $progresscompleted = $this->calculate_progress();
3415
3416 // Update the clock / get time information for this user.
3417 $this->stop_timer();
3418
3419 // Update completion state.
3420 $completion = new completion_info($course);
3421 if ($completion->is_enabled($cm) && $this->properties->completionendreached) {
3422 $completion->update_state($cm, COMPLETION_COMPLETE);
3423 }
3424
3425 if ($this->properties->completiontimespent > 0) {
3426 $duration = $DB->get_field_sql(
3427 "SELECT SUM(lessontime - starttime)
3428 FROM {lesson_timer}
3429 WHERE lessonid = :lessonid
3430 AND userid = :userid",
3431 array('userid' => $USER->id, 'lessonid' => $this->properties->id));
3432 if (!$duration) {
3433 $duration = 0;
3434 }
3435
3436 // If student has not spend enough time in the lesson, display a message.
3437 if ($duration < $this->properties->completiontimespent) {
3438 $a = new stdClass;
3439 $a->timespentraw = $duration;
3440 $a->timespent = format_time($duration);
3441 $a->timerequiredraw = $this->properties->completiontimespent;
3442 $a->timerequired = format_time($this->properties->completiontimespent);
3443 $data->notenoughtimespent = $a;
3444 }
3445 }
3446
3447 if ($gradeinfo->attempts) {
3448 if (!$this->properties->custom) {
3449 $data->numberofpagesviewed = $gradeinfo->nquestions;
3450 if ($this->properties->minquestions) {
3451 if ($gradeinfo->nquestions < $this->properties->minquestions) {
3452 $data->youshouldview = $this->properties->minquestions;
3453 }
3454 }
3455 $data->numberofcorrectanswers = $gradeinfo->earned;
3456 }
3457 $a = new stdClass;
3458 $a->score = $gradeinfo->earned;
3459 $a->grade = $gradeinfo->total;
3460 if ($gradeinfo->nmanual) {
3461 $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
3462 $a->essayquestions = $gradeinfo->nmanual;
3463 $data->displayscorewithessays = $a;
3464 } else {
3465 $data->displayscorewithoutessays = $a;
3466 }
3467 if ($this->properties->grade != GRADE_TYPE_NONE) {
3468 $a = new stdClass;
3469 $a->grade = number_format($gradeinfo->grade * $this->properties->grade / 100, 1);
3470 $a->total = $this->properties->grade;
3471 $data->yourcurrentgradeisoutof = $a;
3472 }
3473
3474 $grade = new stdClass();
3475 $grade->lessonid = $this->properties->id;
3476 $grade->userid = $USER->id;
3477 $grade->grade = $gradeinfo->grade;
3478 $grade->completed = time();
3479 if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record.
3480 if (!$grades = $DB->get_records("lesson_grades",
3481 array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
3482 throw new moodle_exception('cannotfindgrade', 'lesson');
3483 }
3484 $oldgrade = array_shift($grades);
3485 $grade->id = $oldgrade->id;
3486 $DB->update_record("lesson_grades", $grade);
3487 } else {
3488 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3489 }
3490 } else {
3491 if ($this->properties->timelimit) {
3492 if ($outoftime == 'normal') {
3493 $grade = new stdClass();
3494 $grade->lessonid = $this->properties->id;
3495 $grade->userid = $USER->id;
3496 $grade->grade = 0;
3497 $grade->completed = time();
3498 $newgradeid = $DB->insert_record("lesson_grades", $grade);
3499 $data->eolstudentoutoftimenoanswers = true;
3500 }
3501 } else {
3502 $data->welldone = true;
3503 }
3504 }
3505
3506 // Update central gradebook.
3507 lesson_update_grades($this, $USER->id);
3508 $data->progresscompleted = $progresscompleted;
3509 }
3510 } else {
3511 // Display for teacher.
3512 if ($this->properties->grade != GRADE_TYPE_NONE) {
3513 $data->displayofgrade = true;
3514 }
3515 }
3516
3517 if ($this->properties->modattempts && !$canmanage) {
3518 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3519 // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3520 // to pass to view again. This is slick cause it wont call the empty($pageid) code
3521 // $ntries is decremented above.
3522 if (!$attempts = $this->get_attempts($ntries)) {
3523 $attempts = array();
3524 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id));
3525 } else {
3526 $firstattempt = current($attempts);
3527 $pageid = $firstattempt->pageid;
3528 // If the student wishes to review, need to know the last question page that the student answered.
3529 // This will help to make sure that the student can leave the lesson via pushing the continue button.
3530 $lastattempt = end($attempts);
3531 $USER->modattempts[$this->properties->id] = $lastattempt->pageid;
3532
3533 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid));
3534 }
0fc1f24b 3535 $data->reviewlesson = $url->out(false);
dfcabd3b
JL
3536 } else if ($this->properties->modattempts && $canmanage) {
3537 $data->modattemptsnoteacher = true;
3538 }
3539
3540 if ($this->properties->activitylink) {
3541 $data->activitylink = $this->link_for_activitylink();
3542 }
3543 return $data;
3544 }
1e7f8ea2
PS
3545}
3546
3547
3548/**
3549 * Abstract class to provide a core functions to the all lesson classes
3550 *
3551 * This class should be abstracted by ALL classes with the lesson module to ensure
3552 * that all classes within this module can be interacted with in the same way.
3553 *
3554 * This class provides the user with a basic properties array that can be fetched
ff85f902 3555 * or set via magic methods, or alternatively by defining methods get_blah() or
1e7f8ea2
PS
3556 * set_blah() within the extending object.
3557 *
cc3dbaaa
PS
3558 * @copyright 2009 Sam Hemelryk
3559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1e7f8ea2
PS
3560 */
3561abstract class lesson_base {
3562
3563 /**
3564 * An object containing properties
3565 * @var stdClass
3566 */
3567 protected $properties;
3568
3569 /**
3570 * The constructor
3571 * @param stdClass $properties
3572 */
3573 public function __construct($properties) {
3574 $this->properties = (object)$properties;
3575 }
3576
3577 /**
3578 * Magic property method
3579 *
3580 * Attempts to call a set_$key method if one exists otherwise falls back
3581 * to simply set the property
3582 *
3583 * @param string $key
3584 * @param mixed $value
3585 */
3586 public function __set($key, $value) {
3587 if (method_exists($this, 'set_'.$key)) {
3588 $this->{'set_'.$key}($value);
3589 }
3590 $this->properties->{$key} = $value;
3591 }
3592
3593 /**
3594 * Magic get method
3595 *
3596 * Attempts to call a get_$key method to return the property and ralls over
3597 * to return the raw property
3598 *
3599 * @param str $key
3600 * @return mixed
3601 */
3602 public function __get($key) {
3603 if (method_exists($this, 'get_'.$key)) {
3604 return $this->{'get_'.$key}();
3605 }
3606 return $this->properties->{$key};
3607 }
3608
3609 /**
3610 * Stupid PHP needs an isset magic method if you use the get magic method and
3611 * still want empty calls to work.... blah ~!
3612 *
3613 * @param string $key
3614 * @return bool
3615 */
3616 public function __isset($key) {
3617 if (method_exists($this, 'get_'.$key)) {
3618 $val = $this->{'get_'.$key}();
3619 return !empty($val);
3620 }
3621 return !empty($this->properties->{$key});