Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
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
 
18
/**
19
 * Local library file for Lesson.  These are non-standard functions that are used
20
 * only by Lesson.
21
 *
22
 * @package mod_lesson
23
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
25
 **/
26
 
27
/** Make sure this isn't being directly accessed */
28
defined('MOODLE_INTERNAL') || die();
29
 
30
/** Include the files that are required by this module */
31
require_once($CFG->dirroot.'/course/moodleform_mod.php');
32
require_once($CFG->dirroot . '/mod/lesson/lib.php');
33
require_once($CFG->libdir . '/filelib.php');
34
 
35
/** This page */
36
define('LESSON_THISPAGE', 0);
37
/** Next page -> any page not seen before */
38
define("LESSON_UNSEENPAGE", 1);
39
/** Next page -> any page not answered correctly */
40
define("LESSON_UNANSWEREDPAGE", 2);
41
/** Jump to Next Page */
42
define("LESSON_NEXTPAGE", -1);
43
/** End of Lesson */
44
define("LESSON_EOL", -9);
45
/** Jump to an unseen page within a branch and end of branch or end of lesson */
46
define("LESSON_UNSEENBRANCHPAGE", -50);
47
/** Jump to Previous Page */
48
define("LESSON_PREVIOUSPAGE", -40);
49
/** Jump to a random page within a branch and end of branch or end of lesson */
50
define("LESSON_RANDOMPAGE", -60);
51
/** Jump to a random Branch */
52
define("LESSON_RANDOMBRANCH", -70);
53
/** Cluster Jump */
54
define("LESSON_CLUSTERJUMP", -80);
55
/** Undefined */
56
define("LESSON_UNDEFINED", -99);
57
 
58
/** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59
define("LESSON_MAX_EVENT_LENGTH", "432000");
60
 
61
/** Answer format is HTML */
62
define("LESSON_ANSWER_HTML", "HTML");
63
 
64
/** Placeholder answer for all other answers. */
65
define("LESSON_OTHER_ANSWERS", "@#wronganswer#@");
66
 
67
//////////////////////////////////////////////////////////////////////////////////////
68
/// Any other lesson functions go here.  Each of them must have a name that
69
/// starts with lesson_
70
 
71
/**
72
 * Checks to see if a LESSON_CLUSTERJUMP or
73
 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
74
 *
75
 * This function is only executed when a teacher is
76
 * checking the navigation for a lesson.
77
 *
78
 * @param stdClass $lesson Id of the lesson that is to be checked.
79
 * @return boolean True or false.
80
 **/
81
function lesson_display_teacher_warning($lesson) {
82
    global $DB;
83
 
84
    // get all of the lesson answers
85
    $params = array ("lessonid" => $lesson->id);
86
    if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
87
        // no answers, then not using cluster or unseen
88
        return false;
89
    }
90
    // just check for the first one that fulfills the requirements
91
    foreach ($lessonanswers as $lessonanswer) {
92
        if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
93
            return true;
94
        }
95
    }
96
 
97
    // if no answers use either of the two jumps
98
    return false;
99
}
100
 
101
/**
102
 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
103
 *
104
 * will return the pageid of a random unseen page that is within a branch
105
 *
106
 * @param lesson $lesson
107
 * @param int $userid Id of the user.
108
 * @param int $pageid Id of the page from which we are jumping.
109
 * @return int Id of the next page.
110
 **/
111
function lesson_unseen_question_jump($lesson, $user, $pageid) {
112
    global $DB;
113
 
114
    // get the number of retakes
115
    if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
116
        $retakes = 0;
117
    }
118
 
119
    // get all the lesson_attempts aka what the user has seen
120
    if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
121
        foreach($viewedpages as $viewed) {
122
            $seenpages[] = $viewed->pageid;
123
        }
124
    } else {
125
        $seenpages = array();
126
    }
127
 
128
    // get the lesson pages
129
    $lessonpages = $lesson->load_all_pages();
130
 
131
    if ($pageid == LESSON_UNSEENBRANCHPAGE) {  // this only happens when a student leaves in the middle of an unseen question within a branch series
132
        $pageid = $seenpages[0];  // just change the pageid to the last page viewed inside the branch table
133
    }
134
 
135
    // go up the pages till branch table
136
    while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
137
        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
138
            break;
139
        }
140
        $pageid = $lessonpages[$pageid]->prevpageid;
141
    }
142
 
143
    $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
144
 
145
    // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
146
    $unseen = array();
147
    foreach($pagesinbranch as $page) {
148
        if (!in_array($page->id, $seenpages)) {
149
            $unseen[] = $page->id;
150
        }
151
    }
152
 
153
    if(count($unseen) == 0) {
154
        if(isset($pagesinbranch)) {
155
            $temp = end($pagesinbranch);
156
            $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
157
        } else {
158
            // there are no pages inside the branch, so return the next page
159
            $nextpage = $lessonpages[$pageid]->nextpageid;
160
        }
161
        if ($nextpage == 0) {
162
            return LESSON_EOL;
163
        } else {
164
            return $nextpage;
165
        }
166
    } else {
167
        return $unseen[rand(0, count($unseen)-1)];  // returns a random page id for the next page
168
    }
169
}
170
 
171
/**
172
 * Handles the unseen branch table jump.
173
 *
174
 * @param lesson $lesson
175
 * @param int $userid User id.
176
 * @return int Will return the page id of a branch table or end of lesson
177
 **/
178
function lesson_unseen_branch_jump($lesson, $userid) {
179
    global $DB;
180
 
181
    if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
182
        $retakes = 0;
183
    }
184
 
185
    if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
186
        throw new \moodle_exception('cannotfindrecords', 'lesson');
187
    }
188
 
189
    // get the lesson pages
190
    $lessonpages = $lesson->load_all_pages();
191
 
192
    // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
193
    // which is the branch table that starts the unseenbranch function
194
    $seen = array();
195
    foreach ($seenbranches as $seenbranch) {
196
        if (!$seenbranch->flag) {
197
            $seen[$seenbranch->pageid] = $seenbranch->pageid;
198
        } else {
199
            $start = $seenbranch->pageid;
200
            break;
201
        }
202
    }
203
    // this function searches through the lesson pages to find all the branch tables
204
    // that follow the flagged branch table
205
    $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
206
    $branchtables = array();
207
    while ($pageid != 0) {  // grab all of the branch table till eol
208
        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
209
            $branchtables[] = $lessonpages[$pageid]->id;
210
        }
211
        $pageid = $lessonpages[$pageid]->nextpageid;
212
    }
213
    $unseen = array();
214
    foreach ($branchtables as $branchtable) {
215
        // load all of the unseen branch tables into unseen
216
        if (!array_key_exists($branchtable, $seen)) {
217
            $unseen[] = $branchtable;
218
        }
219
    }
220
    if (count($unseen) > 0) {
221
        return $unseen[rand(0, count($unseen)-1)];  // returns a random page id for the next page
222
    } else {
223
        return LESSON_EOL;  // has viewed all of the branch tables
224
    }
225
}
226
 
227
/**
228
 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
229
 *
230
 * @param lesson $lesson
231
 * @param int $pageid The id of the page that we are jumping from (?)
232
 * @return int The pageid of a random page that is within a branch table
233
 **/
234
function lesson_random_question_jump($lesson, $pageid) {
235
    global $DB;
236
 
237
    // get the lesson pages
238
    $params = array ("lessonid" => $lesson->id);
239
    if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
240
        throw new \moodle_exception('cannotfindpages', 'lesson');
241
    }
242
 
243
    // go up the pages till branch table
244
    while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
245
 
246
        if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
247
            break;
248
        }
249
        $pageid = $lessonpages[$pageid]->prevpageid;
250
    }
251
 
252
    // get the pages within the branch
253
    $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
254
 
255
    if(count($pagesinbranch) == 0) {
256
        // there are no pages inside the branch, so return the next page
257
        return $lessonpages[$pageid]->nextpageid;
258
    } else {
259
        return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id;  // returns a random page id for the next page
260
    }
261
}
262
 
263
/**
264
 * Calculates a user's grade for a lesson.
265
 *
266
 * @param object $lesson The lesson that the user is taking.
267
 * @param int $retries The attempt number.
268
 * @param int $userid Id of the user (optional, default current user).
269
 * @return object { nquestions => number of questions answered
270
                    attempts => number of question attempts
271
                    total => max points possible
272
                    earned => points earned by student
273
                    grade => calculated percentage grade
274
                    nmanual => number of manually graded questions
275
                    manualpoints => point value for manually graded questions }
276
 */
277
function lesson_grade($lesson, $ntries, $userid = 0) {
278
    global $USER, $DB;
279
 
280
    if (empty($userid)) {
281
        $userid = $USER->id;
282
    }
283
 
284
    // Zero out everything
285
    $ncorrect     = 0;
286
    $nviewed      = 0;
287
    $score        = 0;
288
    $nmanual      = 0;
289
    $manualpoints = 0;
290
    $thegrade     = 0;
291
    $nquestions   = 0;
292
    $total        = 0;
293
    $earned       = 0;
294
 
295
    $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
296
    if ($useranswers = $DB->get_records_select("lesson_attempts",  "lessonid = :lessonid AND
297
            userid = :userid AND retry = :retry", $params, "timeseen")) {
298
        // group each try with its page
299
        $attemptset = array();
300
        foreach ($useranswers as $useranswer) {
301
            $attemptset[$useranswer->pageid][] = $useranswer;
302
        }
303
 
304
        if (!empty($lesson->maxattempts)) {
305
            // Drop all attempts that go beyond max attempts for the lesson.
306
            foreach ($attemptset as $key => $set) {
307
                $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
308
            }
309
        }
310
 
311
        // get only the pages and their answers that the user answered
312
        list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
313
        array_unshift($parameters, $lesson->id);
314
        $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
315
        $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
316
 
317
        // Number of pages answered
318
        $nquestions = count($pages);
319
 
320
        foreach ($attemptset as $attempts) {
321
            $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
322
            if ($lesson->custom) {
323
                $attempt = end($attempts);
324
                // If essay question, handle it, otherwise add to score
325
                if ($page->requires_manual_grading()) {
326
                    $useranswerobj = unserialize_object($attempt->useranswer);
327
                    if (isset($useranswerobj->score)) {
328
                        $earned += $useranswerobj->score;
329
                    }
330
                    $nmanual++;
331
                    $manualpoints += $answers[$attempt->answerid]->score;
332
                } else if (!empty($attempt->answerid)) {
333
                    $earned += $page->earned_score($answers, $attempt);
334
                }
335
            } else {
336
                foreach ($attempts as $attempt) {
337
                    $earned += $attempt->correct;
338
                }
339
                $attempt = end($attempts); // doesn't matter which one
340
                // If essay question, increase numbers
341
                if ($page->requires_manual_grading()) {
342
                    $nmanual++;
343
                    $manualpoints++;
344
                }
345
            }
346
            // Number of times answered
347
            $nviewed += count($attempts);
348
        }
349
 
350
        if ($lesson->custom) {
351
            $bestscores = array();
352
            // Find the highest possible score per page to get our total
353
            foreach ($answers as $answer) {
354
                if(!isset($bestscores[$answer->pageid])) {
355
                    $bestscores[$answer->pageid] = $answer->score;
356
                } else if ($bestscores[$answer->pageid] < $answer->score) {
357
                    $bestscores[$answer->pageid] = $answer->score;
358
                }
359
            }
360
            $total = array_sum($bestscores);
361
        } else {
362
            // Check to make sure the student has answered the minimum questions
363
            if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
364
                // Nope, increase number viewed by the amount of unanswered questions
365
                $total =  $nviewed + ($lesson->minquestions - $nquestions);
366
            } else {
367
                $total = $nviewed;
368
            }
369
        }
370
    }
371
 
372
    if ($total) { // not zero
373
        $thegrade = round(100 * $earned / $total, 5);
374
    }
375
 
376
    // Build the grade information object
377
    $gradeinfo               = new stdClass;
378
    $gradeinfo->nquestions   = $nquestions;
379
    $gradeinfo->attempts     = $nviewed;
380
    $gradeinfo->total        = $total;
381
    $gradeinfo->earned       = $earned;
382
    $gradeinfo->grade        = $thegrade;
383
    $gradeinfo->nmanual      = $nmanual;
384
    $gradeinfo->manualpoints = $manualpoints;
385
 
386
    return $gradeinfo;
387
}
388
 
389
/**
390
 * Determines if a user can view the left menu.  The determining factor
391
 * is whether a user has a grade greater than or equal to the lesson setting
392
 * of displayleftif
393
 *
394
 * @param object $lesson Lesson object of the current lesson
395
 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
396
 **/
397
function lesson_displayleftif($lesson) {
398
    global $CFG, $USER, $DB;
399
 
400
    if (!empty($lesson->displayleftif)) {
401
        // get the current user's max grade for this lesson
402
        $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
403
        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)) {
404
            if ($maxgrade->maxgrade < $lesson->displayleftif) {
405
                return 0;  // turn off the displayleft
406
            }
407
        } else {
408
            return 0; // no grades
409
        }
410
    }
411
 
412
    // if we get to here, keep the original state of displayleft lesson setting
413
    return $lesson->displayleft;
414
}
415
 
416
/**
417
 *
418
 * @param $cm
419
 * @param $lesson
420
 * @param $page
421
 * @return unknown_type
422
 */
423
function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
424
    $bc = lesson_menu_block_contents($cm->id, $lesson);
425
    if (!empty($bc)) {
426
        $regions = $page->blocks->get_regions();
427
        $firstregion = reset($regions);
428
        $page->blocks->add_fake_block($bc, $firstregion);
429
    }
430
 
431
    $bc = lesson_mediafile_block_contents($cm->id, $lesson);
432
    if (!empty($bc)) {
433
        $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
434
    }
435
 
436
    if (!empty($timer)) {
437
        $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
438
        if (!empty($bc)) {
439
            $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
440
        }
441
    }
442
}
443
 
444
/**
445
 * If there is a media file associated with this
446
 * lesson, return a block_contents that displays it.
447
 *
448
 * @param int $cmid Course Module ID for this lesson
449
 * @param object $lesson Full lesson record object
450
 * @return block_contents
451
 **/
452
function lesson_mediafile_block_contents($cmid, $lesson) {
453
    global $OUTPUT;
454
    if (empty($lesson->mediafile)) {
455
        return null;
456
    }
457
 
458
    $options = array();
459
    $options['menubar'] = 0;
460
    $options['location'] = 0;
461
    $options['left'] = 5;
462
    $options['top'] = 5;
463
    $options['scrollbars'] = 1;
464
    $options['resizable'] = 1;
465
    $options['width'] = $lesson->mediawidth;
466
    $options['height'] = $lesson->mediaheight;
467
 
468
    $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
469
    $action = new popup_action('click', $link, 'lessonmediafile', $options);
470
    $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
471
 
472
    $bc = new block_contents();
473
    $bc->title = get_string('linkedmedia', 'lesson');
474
    $bc->attributes['class'] = 'mediafile block';
475
    $bc->content = $content;
476
 
477
    return $bc;
478
}
479
 
480
/**
481
 * If a timed lesson and not a teacher, then
482
 * return a block_contents containing the clock.
483
 *
484
 * @param int $cmid Course Module ID for this lesson
485
 * @param object $lesson Full lesson record object
486
 * @param object $timer Full timer record object
487
 * @return block_contents
488
 **/
489
function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
490
    // Display for timed lessons and for students only
491
    $context = context_module::instance($cmid);
492
    if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
493
        return null;
494
    }
495
 
496
    $content = '<div id="lesson-timer">';
497
    $content .=  $lesson->time_remaining($timer->starttime);
498
    $content .= '</div>';
499
 
500
    $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
501
    $page->requires->data_for_js('clocksettings', $clocksettings, true);
502
    $page->requires->strings_for_js(array('timeisup'), 'lesson');
503
    $page->requires->js('/mod/lesson/timer.js');
504
    $page->requires->js_init_call('show_clock');
505
 
506
    $bc = new block_contents();
507
    $bc->title = get_string('timeremaining', 'lesson');
508
    $bc->attributes['class'] = 'clock block';
509
    $bc->content = $content;
510
 
511
    return $bc;
512
}
513
 
514
/**
515
 * If left menu is turned on, then this will
516
 * print the menu in a block
517
 *
518
 * @param int $cmid Course Module ID for this lesson
519
 * @param lesson $lesson Full lesson record object
520
 * @return void
521
 **/
522
function lesson_menu_block_contents($cmid, $lesson) {
523
    global $CFG, $DB;
524
 
525
    if (!$lesson->displayleft) {
526
        return null;
527
    }
528
 
529
    $pages = $lesson->load_all_pages();
530
    foreach ($pages as $page) {
531
        if ((int)$page->prevpageid === 0) {
532
            $pageid = $page->id;
533
            break;
534
        }
535
    }
536
    $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
537
 
538
    if (!$pageid || !$pages) {
539
        return null;
540
    }
541
 
542
    $content = '<a href="#maincontent" class="accesshide">' .
543
        get_string('skip', 'lesson') .
544
        "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
545
 
546
    while ($pageid != 0) {
547
        $page = $pages[$pageid];
548
 
549
        // Only process branch tables with display turned on
550
        if ($page->displayinmenublock && $page->display) {
551
            if ($page->id == $currentpageid) {
552
                $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
553
            } else {
554
                $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";
555
            }
556
 
557
        }
558
        $pageid = $page->nextpageid;
559
    }
560
    $content .= "</ul>\n</div>\n";
561
 
562
    $bc = new block_contents();
563
    $bc->title = get_string('lessonmenu', 'lesson');
564
    $bc->attributes['class'] = 'menu block';
565
    $bc->content = $content;
566
 
567
    return $bc;
568
}
569
 
570
/**
571
 * This is a function used to detect media types and generate html code.
572
 *
573
 * @global object $CFG
574
 * @global object $PAGE
575
 * @param object $lesson
576
 * @param object $context
577
 * @return string $code the html code of media
578
 */
579
function lesson_get_media_html($lesson, $context) {
580
    global $CFG, $PAGE, $OUTPUT;
581
    require_once("$CFG->libdir/resourcelib.php");
582
 
583
    // get the media file link
584
    if (strpos($lesson->mediafile, '://') !== false) {
585
        $url = new moodle_url($lesson->mediafile);
586
    } else {
587
        // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
588
        $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
589
    }
590
    $title = $lesson->mediafile;
591
 
592
    $clicktoopen = html_writer::link($url, get_string('download'));
593
 
594
    $mimetype = resourcelib_guess_url_mimetype($url);
595
 
596
    $extension = resourcelib_get_extension($url->out(false));
597
 
598
    $mediamanager = core_media_manager::instance($PAGE);
599
    $embedoptions = array(
600
        core_media_manager::OPTION_TRUSTED => true,
601
        core_media_manager::OPTION_BLOCK => true
602
    );
603
 
604
    // find the correct type and print it out
605
    if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) {  // It's an image
606
        $code = resourcelib_embed_image($url, $title);
607
 
608
    } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
609
        // Media (audio/video) file.
610
        $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
611
 
612
    } else {
613
        // anything else - just try object tag enlarged as much as possible
614
        $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
615
    }
616
 
617
    return $code;
618
}
619
 
620
/**
621
 * Logic to happen when a/some group(s) has/have been deleted in a course.
622
 *
623
 * @param int $courseid The course ID.
624
 * @param int $groupid The group id if it is known
625
 * @return void
626
 */
627
function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
628
    global $DB;
629
 
630
    $params = array('courseid' => $courseid);
631
    if ($groupid) {
632
        $params['groupid'] = $groupid;
633
        // We just update the group that was deleted.
634
        $sql = "SELECT o.id, o.lessonid, o.groupid
635
                  FROM {lesson_overrides} o
636
                  JOIN {lesson} lesson ON lesson.id = o.lessonid
637
                 WHERE lesson.course = :courseid
638
                   AND o.groupid = :groupid";
639
    } else {
640
        // No groupid, we update all orphaned group overrides for all lessons in course.
641
        $sql = "SELECT o.id, o.lessonid, o.groupid
642
                  FROM {lesson_overrides} o
643
                  JOIN {lesson} lesson ON lesson.id = o.lessonid
644
             LEFT JOIN {groups} grp ON grp.id = o.groupid
645
                 WHERE lesson.course = :courseid
646
                   AND o.groupid IS NOT NULL
647
                   AND grp.id IS NULL";
648
    }
649
    $records = $DB->get_records_sql($sql, $params);
650
    if (!$records) {
651
        return; // Nothing to do.
652
    }
653
    $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
654
    $cache = cache::make('mod_lesson', 'overrides');
655
    foreach ($records as $record) {
656
        $cache->delete("{$record->lessonid}_g_{$record->groupid}");
657
    }
658
}
659
 
660
/**
661
 * Return the overview report table and data.
662
 *
663
 * @param  lesson $lesson       lesson instance
664
 * @param  mixed $currentgroup  false if not group used, 0 for all groups, group id (int) to filter by that groups
665
 * @return mixed false if there is no information otherwise html_table and stdClass with the table and data
666
 * @since  Moodle 3.3
667
 */
668
function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) {
669
    global $DB, $CFG, $OUTPUT;
670
    require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
671
 
672
    $context = $lesson->context;
673
    $cm = $lesson->cm;
674
    // Count the number of branch and question pages in this lesson.
675
    $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE));
676
    $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount);
677
 
678
    // Only load students if there attempts for this lesson.
679
    $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id));
680
    $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id));
681
    $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id));
682
    if ($attempts or $branches or $timer) {
683
        list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
684
        list($sort, $sortparams) = users_order_by_sql('u');
685
 
686
        // TODO Does not support custom user profile fields (MDL-70456).
687
        $userfieldsapi = \core_user\fields::for_identity($context, false)->with_userpic();
688
        $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
689
        $extrafields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
690
 
691
        $params['a1lessonid'] = $lesson->id;
692
        $params['b1lessonid'] = $lesson->id;
693
        $params['c1lessonid'] = $lesson->id;
694
        $sql = "SELECT DISTINCT $ufields
695
                FROM {user} u
696
                JOIN (
697
                    SELECT userid, lessonid FROM {lesson_attempts} a1
698
                    WHERE a1.lessonid = :a1lessonid
699
                        UNION
700
                    SELECT userid, lessonid FROM {lesson_branch} b1
701
                    WHERE b1.lessonid = :b1lessonid
702
                        UNION
703
                    SELECT userid, lessonid FROM {lesson_timer} c1
704
                    WHERE c1.lessonid = :c1lessonid
705
                    ) a ON u.id = a.userid
706
                JOIN ($esql) ue ON ue.id = a.userid
707
                ORDER BY $sort";
708
 
709
        $students = $DB->get_recordset_sql($sql, $params);
710
        if (!$students->valid()) {
711
            $students->close();
712
            return array(false, false);
713
        }
714
    } else {
715
        return array(false, false);
716
    }
717
 
718
    if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) {
719
        $grades = array();
720
    }
721
 
722
    if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) {
723
        $times = array();
724
    }
725
 
726
    // Build an array for output.
727
    $studentdata = array();
728
 
729
    $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen');
730
    foreach ($attempts as $attempt) {
731
        // 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.
732
        if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) {
733
            // restore/setup defaults
734
            $n = 0;
735
            $timestart = 0;
736
            $timeend = 0;
737
            $usergrade = null;
738
            $eol = 0;
739
 
740
            // search for the grade record for this try. if not there, the nulls defined above will be used.
741
            foreach($grades as $grade) {
742
                // check to see if the grade matches the correct user
743
                if ($grade->userid == $attempt->userid) {
744
                    // see if n is = to the retry
745
                    if ($n == $attempt->retry) {
746
                        // get grade info
747
                        $usergrade = round($grade->grade, 2); // round it here so we only have to do it once
748
                        break;
749
                    }
750
                    $n++; // if not equal, then increment n
751
                }
752
            }
753
            $n = 0;
754
            // search for the time record for this try. if not there, the nulls defined above will be used.
755
            foreach($times as $time) {
756
                // check to see if the grade matches the correct user
757
                if ($time->userid == $attempt->userid) {
758
                    // see if n is = to the retry
759
                    if ($n == $attempt->retry) {
760
                        // get grade info
761
                        $timeend = $time->lessontime;
762
                        $timestart = $time->starttime;
763
                        $eol = $time->completed;
764
                        break;
765
                    }
766
                    $n++; // if not equal, then increment n
767
                }
768
            }
769
 
770
            // build up the array.
771
            // this array represents each student and all of their tries at the lesson
772
            $studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart,
773
                                                                    "timeend" => $timeend,
774
                                                                    "grade" => $usergrade,
775
                                                                    "end" => $eol,
776
                                                                    "try" => $attempt->retry,
777
                                                                    "userid" => $attempt->userid);
778
        }
779
    }
780
    $attempts->close();
781
 
782
    $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen');
783
    foreach ($branches as $branch) {
784
        // 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.
785
        if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) {
786
            // Restore/setup defaults.
787
            $n = 0;
788
            $timestart = 0;
789
            $timeend = 0;
790
            $usergrade = null;
791
            $eol = 0;
792
            // Search for the time record for this try. if not there, the nulls defined above will be used.
793
            foreach ($times as $time) {
794
                // Check to see if the grade matches the correct user.
795
                if ($time->userid == $branch->userid) {
796
                    // See if n is = to the retry.
797
                    if ($n == $branch->retry) {
798
                        // Get grade info.
799
                        $timeend = $time->lessontime;
800
                        $timestart = $time->starttime;
801
                        $eol = $time->completed;
802
                        break;
803
                    }
804
                    $n++; // If not equal, then increment n.
805
                }
806
            }
807
 
808
            // Build up the array.
809
            // This array represents each student and all of their tries at the lesson.
810
            $studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart,
811
                                                                    "timeend" => $timeend,
812
                                                                    "grade" => $usergrade,
813
                                                                    "end" => $eol,
814
                                                                    "try" => $branch->retry,
815
                                                                    "userid" => $branch->userid);
816
        }
817
    }
818
    $branches->close();
819
 
820
    // Need the same thing for timed entries that were not completed.
821
    foreach ($times as $time) {
822
        $endoflesson = $time->completed;
823
        // If the time start is the same with another record then we shouldn't be adding another item to this array.
824
        if (isset($studentdata[$time->userid])) {
825
            $foundmatch = false;
826
            $n = 0;
827
            foreach ($studentdata[$time->userid] as $key => $value) {
828
                if ($value['timestart'] == $time->starttime) {
829
                    // Don't add this to the array.
830
                    $foundmatch = true;
831
                    break;
832
                }
833
            }
834
            $n = count($studentdata[$time->userid]) + 1;
835
            if (!$foundmatch) {
836
                // Add a record.
837
                $studentdata[$time->userid][] = array(
838
                                "timestart" => $time->starttime,
839
                                "timeend" => $time->lessontime,
840
                                "grade" => null,
841
                                "end" => $endoflesson,
842
                                "try" => $n,
843
                                "userid" => $time->userid
844
                            );
845
            }
846
        } else {
847
            $studentdata[$time->userid][] = array(
848
                                "timestart" => $time->starttime,
849
                                "timeend" => $time->lessontime,
850
                                "grade" => null,
851
                                "end" => $endoflesson,
852
                                "try" => 0,
853
                                "userid" => $time->userid
854
                            );
855
        }
856
    }
857
 
858
    // To store all the data to be returned by the function.
859
    $data = new stdClass();
860
 
861
    // Determine if lesson should have a score.
862
    if ($branchcount > 0 AND $questioncount == 0) {
863
        // This lesson only contains content pages and is not graded.
864
        $data->lessonscored = false;
865
    } else {
866
        // This lesson is graded.
867
        $data->lessonscored = true;
868
    }
869
    // set all the stats variables
870
    $data->numofattempts = 0;
871
    $data->avescore      = 0;
872
    $data->avetime       = 0;
873
    $data->highscore     = null;
874
    $data->lowscore      = null;
875
    $data->hightime      = null;
876
    $data->lowtime       = null;
877
    $data->students      = array();
878
 
879
    $table = new html_table();
880
 
881
    $headers = [get_string('name')];
882
 
883
    foreach ($extrafields as $field) {
884
        $headers[] = \core_user\fields::get_display_name($field);
885
    }
886
 
887
    $caneditlesson = has_capability('mod/lesson:edit', $context);
888
    $attemptsheader = get_string('attempts', 'lesson');
889
    if ($caneditlesson) {
890
        $selectall = get_string('selectallattempts', 'lesson');
891
        $deselectall = get_string('deselectallattempts', 'lesson');
892
        // Build the select/deselect all control.
893
        $selectallid = 'selectall-attempts';
894
        $mastercheckbox = new \core\output\checkbox_toggleall('lesson-attempts', true, [
895
            'id' => $selectallid,
896
            'name' => $selectallid,
897
            'value' => 1,
898
            'label' => $selectall,
899
            'selectall' => $selectall,
900
            'deselectall' => $deselectall,
901
            'labelclasses' => 'form-check-label'
902
        ]);
903
        $attemptsheader = $OUTPUT->render($mastercheckbox);
904
    }
905
    $headers [] = $attemptsheader;
906
 
907
    // Set up the table object.
908
    if ($data->lessonscored) {
909
        $headers [] = get_string('highscore', 'lesson');
910
    }
911
 
912
    $colcount = count($headers);
913
 
914
    $table->head = $headers;
915
 
916
    $table->align = [];
917
    $table->align = array_pad($table->align, $colcount, 'center');
918
    $table->align[$colcount - 1] = 'left';
919
 
920
    if ($data->lessonscored) {
921
        $table->align[$colcount - 2] = 'left';
922
    }
923
 
924
    $table->attributes['class'] = 'table table-striped';
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
 
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
                $attempturlparams = [
947
                    'id' => $cm->id,
948
                    'action' => 'reportdetail',
949
                    'userid' => $try['userid'],
950
                    'try' => $try['try'],
951
                ];
952
 
953
                if ($try["grade"] !== null) { // if null then not done yet
954
                    // this is what the link does when the user has completed the try
955
                    $timetotake = $try["timeend"] - $try["timestart"];
956
 
957
                    if ($try["grade"] > $bestgrade) {
958
                        $bestgrade = $try["grade"];
959
                    }
960
 
961
                    $attemptdata = (object)[
962
                        'grade' => $try["grade"],
963
                        'timestart' => userdate($try["timestart"]),
964
                        'duration' => format_time($timetotake),
965
                    ];
966
                    $attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata);
967
 
968
                } else {
969
                    if ($try["end"]) {
970
                        // User finished the lesson but has no grade. (Happens when there are only content pages).
971
                        $timetotake = $try["timeend"] - $try["timestart"];
972
                        $attemptdata = (object)[
973
                            'timestart' => userdate($try["timestart"]),
974
                            'duration' => format_time($timetotake),
975
                        ];
976
                        $attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata);
977
                    } else {
978
                        // This is what the link does/looks like when the user has not completed the attempt.
979
                        if ($try['timestart'] !== 0) {
980
                            // Teacher previews do not track time spent.
981
                            $attemptlinkcontents = get_string("notcompletedwithdate", "lesson", userdate($try["timestart"]));
982
                        } else {
983
                            $attemptlinkcontents = get_string("notcompleted", "lesson");
984
                        }
985
                        $timetotake = null;
986
                    }
987
                }
988
                $attempturl = new moodle_url('/mod/lesson/report.php', $attempturlparams);
989
                $attemptlink = html_writer::link($attempturl, $attemptlinkcontents, ['class' => 'lesson-attempt-link']);
990
 
991
                if ($caneditlesson) {
992
                    $attemptid = 'attempt-' . $try['userid'] . '-' . $try['try'];
993
                    $attemptname = 'attempts[' . $try['userid'] . '][' . $try['try'] . ']';
994
 
995
                    $checkbox = new \core\output\checkbox_toggleall('lesson-attempts', false, [
996
                        'id' => $attemptid,
997
                        'name' => $attemptname,
998
                        'label' => $attemptlink
999
                    ]);
1000
                    $attemptlink = $OUTPUT->render($checkbox);
1001
                }
1002
 
1003
                // build up the attempts array
1004
                $attempts[] = $attemptlink;
1005
 
1006
                // Run these lines for the stats only if the user finnished the lesson.
1007
                if ($try["end"]) {
1008
                    // User has completed the lesson.
1009
                    $data->numofattempts++;
1010
                    $data->avetime += $timetotake;
1011
                    if ($timetotake > $data->hightime || $data->hightime == null) {
1012
                        $data->hightime = $timetotake;
1013
                    }
1014
                    if ($timetotake < $data->lowtime || $data->lowtime == null) {
1015
                        $data->lowtime = $timetotake;
1016
                    }
1017
                    if ($try["grade"] !== null) {
1018
                        // The lesson was scored.
1019
                        $data->avescore += $try["grade"];
1020
                        if ($try["grade"] > $data->highscore || $data->highscore === null) {
1021
                            $data->highscore = $try["grade"];
1022
                        }
1023
                        if ($try["grade"] < $data->lowscore || $data->lowscore === null) {
1024
                            $data->lowscore = $try["grade"];
1025
                        }
1026
 
1027
                    }
1028
                }
1029
            }
1030
            // get line breaks in after each attempt
1031
            $attempts = implode("<br />\n", $attempts);
1032
            $row = [$studentname];
1033
 
1034
            foreach ($extrafields as $field) {
1035
                $row[] = s($student->$field);
1036
            }
1037
 
1038
            $row[] = $attempts;
1039
 
1040
            if ($data->lessonscored) {
1041
                // Add the grade if the lesson is graded.
1042
                $row[] = $bestgrade."%";
1043
            }
1044
 
1045
            $table->data[] = $row;
1046
 
1047
            // Add the student data.
1048
            $dataforstudent->id = $student->id;
1049
            $dataforstudent->fullname = $studentname;
1050
            $dataforstudent->bestgrade = $bestgrade;
1051
            $data->students[] = $dataforstudent;
1052
        }
1053
    }
1054
    $students->close();
1055
    if ($data->numofattempts > 0) {
1056
        $data->avescore = $data->avescore / $data->numofattempts;
1057
    }
1058
 
1059
    return array($table, $data);
1060
}
1061
 
1062
/**
1063
 * Return information about one user attempt (including answers)
1064
 * @param  lesson $lesson  lesson instance
1065
 * @param  int $userid     the user id
1066
 * @param  int $attempt    the attempt number
1067
 * @return array the user answers (array) and user data stats (object)
1068
 * @since  Moodle 3.3
1069
 */
1070
function lesson_get_user_detailed_report_data(lesson $lesson, $userid, $attempt) {
1071
    global $DB;
1072
 
1073
    $context = $lesson->context;
1074
    if (!empty($userid)) {
1075
        // Apply overrides.
1076
        $lesson->update_effective_access($userid);
1077
    }
1078
 
1079
    $pageid = 0;
1080
    $lessonpages = $lesson->load_all_pages();
1081
    foreach ($lessonpages as $lessonpage) {
1082
        if ($lessonpage->prevpageid == 0) {
1083
            $pageid = $lessonpage->id;
1084
        }
1085
    }
1086
 
1087
    // now gather the stats into an object
1088
    $firstpageid = $pageid;
1089
    $pagestats = array();
1090
    while ($pageid != 0) { // EOL
1091
        $page = $lessonpages[$pageid];
1092
        $params = array ("lessonid" => $lesson->id, "pageid" => $page->id);
1093
        if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) {
1094
            // get them ready for processing
1095
            $orderedanswers = array();
1096
            foreach ($allanswers as $singleanswer) {
1097
                // ordering them like this, will help to find the single attempt record that we want to keep.
1098
                $orderedanswers[$singleanswer->userid][$singleanswer->retry][] = $singleanswer;
1099
            }
1100
            // this is foreach user and for each try for that user, keep one attempt record
1101
            foreach ($orderedanswers as $orderedanswer) {
1102
                foreach($orderedanswer as $tries) {
1103
                    $page->stats($pagestats, $tries);
1104
                }
1105
            }
1106
        } else {
1107
            // no one answered yet...
1108
        }
1109
        //unset($orderedanswers);  initialized above now
1110
        $pageid = $page->nextpageid;
1111
    }
1112
 
1113
    $manager = lesson_page_type_manager::get($lesson);
1114
    $qtypes = $manager->get_page_type_strings();
1115
 
1116
    $answerpages = array();
1117
    $answerpage = "";
1118
    $pageid = $firstpageid;
1119
    // cycle through all the pages
1120
    //  foreach page, add to the $answerpages[] array all the data that is needed
1121
    //  from the question, the users attempt, and the statistics
1122
    // grayout pages that the user did not answer and Branch, end of branch, cluster
1123
    // and end of cluster pages
1124
    while ($pageid != 0) { // EOL
1125
        $page = $lessonpages[$pageid];
1126
        $answerpage = new stdClass;
1127
        // Keep the original page object.
1128
        $answerpage->page = $page;
1129
        $data ='';
1130
 
1131
        $answerdata = new stdClass;
1132
        // Set some defaults for the answer data.
1133
        $answerdata->score = null;
1134
        $answerdata->response = null;
1135
        $answerdata->responseformat = FORMAT_PLAIN;
1136
 
1137
        $answerpage->title = format_string($page->title);
1138
 
1139
        $options = new stdClass;
1140
        $options->noclean = true;
1141
        $options->overflowdiv = true;
1142
        $options->context = $context;
1143
        $answerpage->contents = format_text($page->contents, $page->contentsformat, $options);
1144
 
1145
        $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string();
1146
        $answerpage->grayout = $page->grayout;
1147
        $answerpage->context = $context;
1148
 
1149
        if (empty($userid)) {
1150
            // there is no userid, so set these vars and display stats.
1151
            $answerpage->grayout = 0;
1152
            $useranswer = null;
1153
        } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) {
1154
            // get the user's answer for this page
1155
            // need to find the right one
1156
            $i = 0;
1157
            foreach ($useranswers as $userattempt) {
1158
                $useranswer = $userattempt;
1159
                $i++;
1160
                if ($lesson->maxattempts == $i) {
1161
                    break; // reached maxattempts, break out
1162
                }
1163
            }
1164
        } else {
1165
            // user did not answer this page, gray it out and set some nulls
1166
            $answerpage->grayout = 1;
1167
            $useranswer = null;
1168
        }
1169
        $i = 0;
1170
        $n = 0;
1171
        $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
1172
        $pageid = $page->nextpageid;
1173
    }
1174
 
1175
    $userstats = new stdClass;
1176
    if (!empty($userid)) {
1177
        $params = array("lessonid"=>$lesson->id, "userid"=>$userid);
1178
 
1179
        $alreadycompleted = true;
1180
 
1181
        if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
1182
            $userstats->grade = -1;
1183
            $userstats->completed = -1;
1184
            $alreadycompleted = false;
1185
        } else {
1186
            $userstats->grade = current($grades);
1187
            $userstats->completed = $userstats->grade->completed;
1188
            $userstats->grade = round($userstats->grade->grade, 2);
1189
        }
1190
 
1191
        if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
1192
            $userstats->timetotake = -1;
1193
            $alreadycompleted = false;
1194
        } else {
1195
            $userstats->timetotake = current($times);
1196
            $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime;
1197
        }
1198
 
1199
        if ($alreadycompleted) {
1200
            $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid);
1201
        }
1202
    }
1203
 
1204
    return array($answerpages, $userstats);
1205
}
1206
 
1207
/**
1208
 * Return user's deadline for all lessons in a course, hereby taking into account group and user overrides.
1209
 *
1210
 * @param int $courseid the course id.
1211
 * @return object An object with of all lessonsids and close unixdates in this course,
1212
 * taking into account the most lenient overrides, if existing and 0 if no close date is set.
1213
 */
1214
function lesson_get_user_deadline($courseid) {
1215
    global $DB, $USER;
1216
 
1217
    // For teacher and manager/admins return lesson's deadline.
1218
    if (has_capability('moodle/course:update', context_course::instance($courseid))) {
1219
        $sql = "SELECT lesson.id, lesson.deadline AS userdeadline
1220
                  FROM {lesson} lesson
1221
                 WHERE lesson.course = :courseid";
1222
 
1223
        $results = $DB->get_records_sql($sql, array('courseid' => $courseid));
1224
        return $results;
1225
    }
1226
 
1227
    $sql = "SELECT a.id,
1228
                   COALESCE(v.userclose, v.groupclose, a.deadline, 0) AS userdeadline
1229
              FROM (
1230
                      SELECT lesson.id as lessonid,
1231
                             MAX(leo.deadline) AS userclose, MAX(qgo.deadline) AS groupclose
1232
                        FROM {lesson} lesson
1233
                   LEFT JOIN {lesson_overrides} leo on lesson.id = leo.lessonid AND leo.userid = :userid
1234
                   LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
1235
                   LEFT JOIN {lesson_overrides} qgo on lesson.id = qgo.lessonid AND qgo.groupid = gm.groupid
1236
                       WHERE lesson.course = :courseid
1237
                    GROUP BY lesson.id
1238
                   ) v
1239
              JOIN {lesson} a ON a.id = v.lessonid";
1240
 
1241
    $results = $DB->get_records_sql($sql, array('userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid));
1242
    return $results;
1243
 
1244
}
1245
 
1246
/**
1247
 * Abstract class that page type's MUST inherit from.
1248
 *
1249
 * This is the abstract class that ALL add page type forms must extend.
1250
 * You will notice that all but two of the methods this class contains are final.
1251
 * Essentially the only thing that extending classes can do is extend custom_definition.
1252
 * OR if it has a special requirement on creation it can extend construction_override
1253
 *
1254
 * @abstract
1255
 * @copyright  2009 Sam Hemelryk
1256
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1257
 */
1258
abstract class lesson_add_page_form_base extends moodleform {
1259
 
1260
    /**
1261
     * This is the classic define that is used to identify this pagetype.
1262
     * Will be one of LESSON_*
1263
     * @var int
1264
     */
1265
    public $qtype;
1266
 
1267
    /**
1268
     * The simple string that describes the page type e.g. truefalse, multichoice
1269
     * @var string
1270
     */
1271
    public $qtypestring;
1272
 
1273
    /**
1274
     * An array of options used in the htmleditor
1275
     * @var array
1276
     */
1277
    protected $editoroptions = array();
1278
 
1279
    /**
1280
     * True if this is a standard page of false if it does something special.
1281
     * Questions are standard pages, branch tables are not
1282
     * @var bool
1283
     */
1284
    protected $standard = true;
1285
 
1286
    /**
1287
     * Answer format supported by question type.
1288
     */
1289
    protected $answerformat = '';
1290
 
1291
    /**
1292
     * Response format supported by question type.
1293
     */
1294
    protected $responseformat = '';
1295
 
1296
    /**
1297
     * Each page type can and should override this to add any custom elements to
1298
     * the basic form that they want
1299
     */
1300
    public function custom_definition() {}
1301
 
1302
    /**
1303
     * Returns answer format used by question type.
1304
     */
1305
    public function get_answer_format() {
1306
        return $this->answerformat;
1307
    }
1308
 
1309
    /**
1310
     * Returns response format used by question type.
1311
     */
1312
    public function get_response_format() {
1313
        return $this->responseformat;
1314
    }
1315
 
1316
    /**
1317
     * Used to determine if this is a standard page or a special page
1318
     * @return bool
1319
     */
1320
    final public function is_standard() {
1321
        return (bool)$this->standard;
1322
    }
1323
 
1324
    /**
1325
     * Add the required basic elements to the form.
1326
     *
1327
     * This method adds the basic elements to the form including title and contents
1328
     * and then calls custom_definition();
1329
     */
1330
    final public function definition() {
1331
        global $CFG;
1332
        $mform = $this->_form;
1333
        $editoroptions = $this->_customdata['editoroptions'];
1334
 
1335
        if ($this->qtypestring != 'selectaqtype') {
1336
            if ($this->_customdata['edit']) {
1337
                $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring, 'lesson'));
1338
            } else {
1339
                $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring, 'lesson'));
1340
            }
1341
        }
1342
 
1343
        if (!empty($this->_customdata['returnto'])) {
1344
            $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
1345
            $mform->setType('returnto', PARAM_LOCALURL);
1346
        }
1347
 
1348
        $mform->addElement('hidden', 'id');
1349
        $mform->setType('id', PARAM_INT);
1350
 
1351
        $mform->addElement('hidden', 'pageid');
1352
        $mform->setType('pageid', PARAM_INT);
1353
 
1354
        if ($this->standard === true) {
1355
            $mform->addElement('hidden', 'qtype');
1356
            $mform->setType('qtype', PARAM_INT);
1357
 
1358
            $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), ['size' => 70, 'maxlength' => 255]);
1359
            $mform->addRule('title', get_string('required'), 'required', null, 'client');
1360
            $mform->addRule('title', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
1361
            if (!empty($CFG->formatstringstriptags)) {
1362
                $mform->setType('title', PARAM_TEXT);
1363
            } else {
1364
                $mform->setType('title', PARAM_CLEANHTML);
1365
            }
1366
 
1367
            $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
1368
            $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
1369
            $mform->setType('contents_editor', PARAM_RAW);
1370
            $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
1371
        }
1372
 
1373
        $this->custom_definition();
1374
 
1375
        if ($this->_customdata['edit'] === true) {
1376
            $mform->addElement('hidden', 'edit', 1);
1377
            $mform->setType('edit', PARAM_BOOL);
1378
            $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1379
        } else if ($this->qtype === 'questiontype') {
1380
            $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
1381
        } else {
1382
            $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
1383
        }
1384
    }
1385
 
1386
    /**
1387
     * Convenience function: Adds a jumpto select element
1388
     *
1389
     * @param string $name
1390
     * @param string|null $label
1391
     * @param int $selected The page to select by default
1392
     */
1393
    final protected function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
1394
        $title = get_string("jump", "lesson");
1395
        if ($label === null) {
1396
            $label = $title;
1397
        }
1398
        if (is_int($name)) {
1399
            $name = "jumpto[$name]";
1400
        }
1401
        $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
1402
        $this->_form->setDefault($name, $selected);
1403
        $this->_form->addHelpButton($name, 'jumps', 'lesson');
1404
    }
1405
 
1406
    /**
1407
     * Convenience function: Adds a score input element
1408
     *
1409
     * @param string $name
1410
     * @param string|null $label
1411
     * @param mixed $value The default value
1412
     */
1413
    final protected function add_score($name, $label=null, $value=null) {
1414
        if ($label === null) {
1415
            $label = get_string("score", "lesson");
1416
        }
1417
 
1418
        if (is_int($name)) {
1419
            $name = "score[$name]";
1420
        }
1421
        $this->_form->addElement('text', $name, $label, array('size'=>5));
1422
        $this->_form->setType($name, PARAM_INT);
1423
        if ($value !== null) {
1424
            $this->_form->setDefault($name, $value);
1425
        }
1426
        $this->_form->addHelpButton($name, 'score', 'lesson');
1427
 
1428
        // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
1429
        if (!$this->_customdata['lesson']->custom) {
1430
            $this->_form->freeze($name);
1431
        }
1432
    }
1433
 
1434
    /**
1435
     * Convenience function: Adds an answer editor
1436
     *
1437
     * @param int $count The count of the element to add
1438
     * @param string $label, null means default
1439
     * @param bool $required
1440
     * @param string $format
1441
     * @param array $help Add help text via the addHelpButton. Must be an array which contains the string identifier and
1442
     *                      component as it's elements
1443
     * @return void
1444
     */
1445
    final protected function add_answer($count, $label = null, $required = false, $format= '', array $help = []) {
1446
        if ($label === null) {
1447
            $label = get_string('answer', 'lesson');
1448
        }
1449
 
1450
        if ($format == LESSON_ANSWER_HTML) {
1451
            $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
1452
                    array('rows' => '4', 'columns' => '80'),
1453
                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1454
            $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
1455
            $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1456
        } else {
1457
            $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
1458
                array('size' => '50', 'maxlength' => '200'));
1459
            $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
1460
        }
1461
 
1462
        if ($required) {
1463
            $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
1464
        }
1465
 
1466
        if ($help) {
1467
            $this->_form->addHelpButton("answer_editor[$count]", $help['identifier'], $help['component']);
1468
        }
1469
    }
1470
    /**
1471
     * Convenience function: Adds an response editor
1472
     *
1473
     * @param int $count The count of the element to add
1474
     * @param string $label, null means default
1475
     * @param bool $required
1476
     * @return void
1477
     */
1478
    final protected function add_response($count, $label = null, $required = false) {
1479
        if ($label === null) {
1480
            $label = get_string('response', 'lesson');
1481
        }
1482
        $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
1483
                 array('rows' => '4', 'columns' => '80'),
1484
                 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
1485
        $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
1486
        $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
1487
 
1488
        if ($required) {
1489
            $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
1490
        }
1491
    }
1492
 
1493
    /**
1494
     * A function that gets called upon init of this object by the calling script.
1495
     *
1496
     * This can be used to process an immediate action if required. Currently it
1497
     * is only used in special cases by non-standard page types.
1498
     *
1499
     * @return bool
1500
     */
1501
    public function construction_override($pageid, lesson $lesson) {
1502
        return true;
1503
    }
1504
}
1505
 
1506
 
1507
 
1508
/**
1509
 * Class representation of a lesson
1510
 *
1511
 * This class is used the interact with, and manage a lesson once instantiated.
1512
 * If you need to fetch a lesson object you can do so by calling
1513
 *
1514
 * <code>
1515
 * lesson::load($lessonid);
1516
 * // or
1517
 * $lessonrecord = $DB->get_record('lesson', $lessonid);
1518
 * $lesson = new lesson($lessonrecord);
1519
 * </code>
1520
 *
1521
 * The class itself extends lesson_base as all classes within the lesson module should
1522
 *
1523
 * These properties are from the database
1524
 * @property int $id The id of this lesson
1525
 * @property int $course The ID of the course this lesson belongs to
1526
 * @property string $name The name of this lesson
1527
 * @property int $practice Flag to toggle this as a practice lesson
1528
 * @property int $modattempts Toggle to allow the user to go back and review answers
1529
 * @property int $usepassword Toggle the use of a password for entry
1530
 * @property string $password The password to require users to enter
1531
 * @property int $dependency ID of another lesson this lesson is dependent on
1532
 * @property string $conditions Conditions of the lesson dependency
1533
 * @property int $grade The maximum grade a user can achieve (%)
1534
 * @property int $custom Toggle custom scoring on or off
1535
 * @property int $ongoing Toggle display of an ongoing score
1536
 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
1537
 * @property int $maxanswers The max number of answers or branches
1538
 * @property int $maxattempts The maximum number of attempts a user can record
1539
 * @property int $review Toggle use or wrong answer review button
1540
 * @property int $nextpagedefault Override the default next page
1541
 * @property int $feedback Toggles display of default feedback
1542
 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
1543
 * @property int $maxpages Maximum number of pages this lesson can contain
1544
 * @property int $retake Flag to allow users to retake a lesson
1545
 * @property int $activitylink Relate this lesson to another lesson
1546
 * @property string $mediafile File to pop up to or webpage to display
1547
 * @property int $mediaheight Sets the height of the media file popup
1548
 * @property int $mediawidth Sets the width of the media file popup
1549
 * @property int $mediaclose Toggle display of a media close button
1550
 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
1551
 * @property int $width Width of slideshow
1552
 * @property int $height Height of slideshow
1553
 * @property string $bgcolor Background colour of slideshow
1554
 * @property int $displayleft Display a left menu
1555
 * @property int $displayleftif Sets the condition on which the left menu is displayed
1556
 * @property int $progressbar Flag to toggle display of a lesson progress bar
1557
 * @property int $available Timestamp of when this lesson becomes available
1558
 * @property int $deadline Timestamp of when this lesson is no longer available
1559
 * @property int $timemodified Timestamp when lesson was last modified
1560
 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app
1561
 *
1562
 * These properties are calculated
1563
 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
1564
 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
1565
 *
1566
 * @copyright  2009 Sam Hemelryk
1567
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1568
 */
1569
class lesson extends lesson_base {
1570
 
1571
    /**
1572
     * The id of the first page (where prevpageid = 0) gets set and retrieved by
1573
     * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
1574
     * @var int
1575
     */
1576
    protected $firstpageid = null;
1577
    /**
1578
     * The id of the last page (where nextpageid = 0) gets set and retrieved by
1579
     * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
1580
     * @var int
1581
     */
1582
    protected $lastpageid = null;
1583
    /**
1584
     * An array used to cache the pages associated with this lesson after the first
1585
     * time they have been loaded.
1586
     * A note to developers: If you are going to be working with MORE than one or
1587
     * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1588
     * in order to save excess database queries.
1589
     * @var array An array of lesson_page objects
1590
     */
1591
    protected $pages = array();
1592
    /**
1593
     * Flag that gets set to true once all of the pages associated with the lesson
1594
     * have been loaded.
1595
     * @var bool
1596
     */
1597
    protected $loadedallpages = false;
1598
 
1599
    /**
1600
     * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1601
     * @see get_cm()
1602
     * @var stdClass
1603
     */
1604
    protected $cm = null;
1605
 
1606
    /**
1607
     * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code>
1608
     * @see get_courserecord()
1609
     * @var stdClass
1610
     */
1611
    protected $courserecord = null;
1612
 
1613
    /**
1614
     * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1615
     * @see get_context()
1616
     * @var stdClass
1617
     */
1618
    protected $context = null;
1619
 
1620
    /**
1621
     * Constructor method
1622
     *
1623
     * @param object $properties
1624
     * @param stdClass $cm course module object
1625
     * @param stdClass $course course object
1626
     * @since Moodle 3.3
1627
     */
1628
    public function __construct($properties, $cm = null, $course = null) {
1629
        parent::__construct($properties);
1630
        $this->cm = $cm;
1631
        $this->courserecord = $course;
1632
    }
1633
 
1634
    /**
1635
     * Simply generates a lesson object given an array/object of properties
1636
     * Overrides {@see lesson_base->create()}
1637
     * @static
1638
     * @param object|array $properties
1639
     * @return lesson
1640
     */
1641
    public static function create($properties) {
1642
        return new lesson($properties);
1643
    }
1644
 
1645
    /**
1646
     * Generates a lesson object from the database given its id
1647
     * @static
1648
     * @param int $lessonid
1649
     * @return lesson
1650
     */
1651
    public static function load($lessonid) {
1652
        global $DB;
1653
 
1654
        if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1655
            throw new \moodle_exception('invalidcoursemodule');
1656
        }
1657
        return new lesson($lesson);
1658
    }
1659
 
1660
    /**
1661
     * Deletes this lesson from the database
1662
     */
1663
    public function delete() {
1664
        global $CFG, $DB;
1665
        require_once($CFG->libdir.'/gradelib.php');
1666
        require_once($CFG->dirroot.'/calendar/lib.php');
1667
 
1668
        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1669
        $context = context_module::instance($cm->id);
1670
 
1671
        $this->delete_all_overrides();
1672
 
1673
        grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1674
 
1675
        // We must delete the module record after we delete the grade item.
1676
        $DB->delete_records("lesson", array("id"=>$this->properties->id));
1677
        $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1678
        $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1679
        $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1680
        $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1681
        $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1682
        $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1683
        if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1684
            $coursecontext = context_course::instance($cm->course);
1685
            foreach($events as $event) {
1686
                $event->context = $coursecontext;
1687
                $event = calendar_event::load($event);
1688
                $event->delete();
1689
            }
1690
        }
1691
 
1692
        // Delete files associated with this module.
1693
        $fs = get_file_storage();
1694
        $fs->delete_area_files($context->id);
1695
 
1696
        return true;
1697
    }
1698
 
1699
    /**
1700
     * Deletes a lesson override from the database and clears any corresponding calendar events
1701
     *
1702
     * @param int $overrideid The id of the override being deleted
1703
     * @return bool true on success
1704
     */
1705
    public function delete_override($overrideid) {
1706
        global $CFG, $DB;
1707
 
1708
        require_once($CFG->dirroot . '/calendar/lib.php');
1709
 
1710
        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1711
 
1712
        $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1713
 
1714
        // Delete the events.
1715
        $conds = array('modulename' => 'lesson',
1716
                'instance' => $this->properties->id);
1717
        if (isset($override->userid)) {
1718
            $conds['userid'] = $override->userid;
1719
            $cachekey = "{$cm->instance}_u_{$override->userid}";
1720
        } else {
1721
            $conds['groupid'] = $override->groupid;
1722
            $cachekey = "{$cm->instance}_g_{$override->groupid}";
1723
        }
1724
        $events = $DB->get_records('event', $conds);
1725
        foreach ($events as $event) {
1726
            $eventold = calendar_event::load($event);
1727
            $eventold->delete();
1728
        }
1729
 
1730
        $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1731
        cache::make('mod_lesson', 'overrides')->delete($cachekey);
1732
 
1733
        // Set the common parameters for one of the events we will be triggering.
1734
        $params = array(
1735
            'objectid' => $override->id,
1736
            'context' => context_module::instance($cm->id),
1737
            'other' => array(
1738
                'lessonid' => $override->lessonid
1739
            )
1740
        );
1741
        // Determine which override deleted event to fire.
1742
        if (!empty($override->userid)) {
1743
            $params['relateduserid'] = $override->userid;
1744
            $event = \mod_lesson\event\user_override_deleted::create($params);
1745
        } else {
1746
            $params['other']['groupid'] = $override->groupid;
1747
            $event = \mod_lesson\event\group_override_deleted::create($params);
1748
        }
1749
 
1750
        // Trigger the override deleted event.
1751
        $event->add_record_snapshot('lesson_overrides', $override);
1752
        $event->trigger();
1753
 
1754
        return true;
1755
    }
1756
 
1757
    /**
1758
     * Deletes all lesson overrides from the database and clears any corresponding calendar events
1759
     */
1760
    public function delete_all_overrides() {
1761
        global $DB;
1762
 
1763
        $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1764
        foreach ($overrides as $override) {
1765
            $this->delete_override($override->id);
1766
        }
1767
    }
1768
 
1769
    /**
1770
     * Checks user enrollment in the current course.
1771
     *
1772
     * @param int $userid
1773
     * @return null|stdClass user record
1774
     */
1775
    public function is_participant($userid) {
1776
        return is_enrolled($this->get_context(), $userid, 'mod/lesson:view', $this->show_only_active_users());
1777
    }
1778
 
1779
    /**
1780
     * Check is only active users in course should be shown.
1781
     *
1782
     * @return bool true if only active users should be shown.
1783
     */
1784
    public function show_only_active_users() {
1785
        return !has_capability('moodle/course:viewsuspendedusers', $this->get_context());
1786
    }
1787
 
1788
    /**
1789
     * Updates the lesson properties with override information for a user.
1790
     *
1791
     * Algorithm:  For each lesson setting, if there is a matching user-specific override,
1792
     *   then use that otherwise, if there are group-specific overrides, return the most
1793
     *   lenient combination of them.  If neither applies, leave the quiz setting unchanged.
1794
     *
1795
     *   Special case: if there is more than one password that applies to the user, then
1796
     *   lesson->extrapasswords will contain an array of strings giving the remaining
1797
     *   passwords.
1798
     *
1799
     * @param int $userid The userid.
1800
     */
1801
    public function update_effective_access($userid) {
1802
        global $DB;
1803
 
1804
        // Check for user override.
1805
        $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1806
 
1807
        if (!$override) {
1808
            $override = new stdClass();
1809
            $override->available = null;
1810
            $override->deadline = null;
1811
            $override->timelimit = null;
1812
            $override->review = null;
1813
            $override->maxattempts = null;
1814
            $override->retake = null;
1815
            $override->password = null;
1816
        }
1817
 
1818
        // Check for group overrides.
1819
        $groupings = groups_get_user_groups($this->properties->course, $userid);
1820
 
1821
        if (!empty($groupings[0])) {
1822
            // Select all overrides that apply to the User's groups.
1823
            list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1824
            $sql = "SELECT * FROM {lesson_overrides}
1825
                    WHERE groupid $extra AND lessonid = ?";
1826
            $params[] = $this->properties->id;
1827
            $records = $DB->get_records_sql($sql, $params);
1828
 
1829
            // Combine the overrides.
1830
            $availables = array();
1831
            $deadlines = array();
1832
            $timelimits = array();
1833
            $reviews = array();
1834
            $attempts = array();
1835
            $retakes = array();
1836
            $passwords = array();
1837
 
1838
            foreach ($records as $gpoverride) {
1839
                if (isset($gpoverride->available)) {
1840
                    $availables[] = $gpoverride->available;
1841
                }
1842
                if (isset($gpoverride->deadline)) {
1843
                    $deadlines[] = $gpoverride->deadline;
1844
                }
1845
                if (isset($gpoverride->timelimit)) {
1846
                    $timelimits[] = $gpoverride->timelimit;
1847
                }
1848
                if (isset($gpoverride->review)) {
1849
                    $reviews[] = $gpoverride->review;
1850
                }
1851
                if (isset($gpoverride->maxattempts)) {
1852
                    $attempts[] = $gpoverride->maxattempts;
1853
                }
1854
                if (isset($gpoverride->retake)) {
1855
                    $retakes[] = $gpoverride->retake;
1856
                }
1857
                if (isset($gpoverride->password)) {
1858
                    $passwords[] = $gpoverride->password;
1859
                }
1860
            }
1861
            // If there is a user override for a setting, ignore the group override.
1862
            if (is_null($override->available) && count($availables)) {
1863
                $override->available = min($availables);
1864
            }
1865
            if (is_null($override->deadline) && count($deadlines)) {
1866
                if (in_array(0, $deadlines)) {
1867
                    $override->deadline = 0;
1868
                } else {
1869
                    $override->deadline = max($deadlines);
1870
                }
1871
            }
1872
            if (is_null($override->timelimit) && count($timelimits)) {
1873
                if (in_array(0, $timelimits)) {
1874
                    $override->timelimit = 0;
1875
                } else {
1876
                    $override->timelimit = max($timelimits);
1877
                }
1878
            }
1879
            if (is_null($override->review) && count($reviews)) {
1880
                $override->review = max($reviews);
1881
            }
1882
            if (is_null($override->maxattempts) && count($attempts)) {
1883
                $override->maxattempts = max($attempts);
1884
            }
1885
            if (is_null($override->retake) && count($retakes)) {
1886
                $override->retake = max($retakes);
1887
            }
1888
            if (is_null($override->password) && count($passwords)) {
1889
                $override->password = array_shift($passwords);
1890
                if (count($passwords)) {
1891
                    $override->extrapasswords = $passwords;
1892
                }
1893
            }
1894
 
1895
        }
1896
 
1897
        // Merge with lesson defaults.
1898
        $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1899
        foreach ($keys as $key) {
1900
            if (isset($override->{$key})) {
1901
                $this->properties->{$key} = $override->{$key};
1902
            }
1903
        }
1904
 
1905
        // Special handling of lesson usepassword and password.
1906
        if (isset($override->password)) {
1907
            if ($override->password == '') {
1908
                $this->properties->usepassword = 0;
1909
            } else {
1910
                $this->properties->usepassword = 1;
1911
                $this->properties->password = $override->password;
1912
                if (isset($override->extrapasswords)) {
1913
                    $this->properties->extrapasswords = $override->extrapasswords;
1914
                }
1915
            }
1916
        }
1917
    }
1918
 
1919
    /**
1920
     * Fetches messages from the session that may have been set in previous page
1921
     * actions.
1922
     *
1923
     * <code>
1924
     * // Do not call this method directly instead use
1925
     * $lesson->messages;
1926
     * </code>
1927
     *
1928
     * @return array
1929
     */
1930
    protected function get_messages() {
1931
        global $SESSION;
1932
 
1933
        $messages = array();
1934
        if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1935
            $messages = $SESSION->lesson_messages[$this->properties->id];
1936
            unset($SESSION->lesson_messages[$this->properties->id]);
1937
        }
1938
 
1939
        return $messages;
1940
    }
1941
 
1942
    /**
1943
     * Get all of the attempts for the current user.
1944
     *
1945
     * @param int $retries
1946
     * @param bool $correct Optional: only fetch correct attempts
1947
     * @param int $pageid Optional: only fetch attempts at the given page
1948
     * @param int $userid Optional: defaults to the current user if not set
1949
     * @return array|false
1950
     */
1951
    public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1952
        global $USER, $DB;
1953
        $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1954
        if ($correct) {
1955
            $params['correct'] = 1;
1956
        }
1957
        if ($pageid !== null) {
1958
            $params['pageid'] = $pageid;
1959
        }
1960
        if ($userid === null) {
1961
            $params['userid'] = $USER->id;
1962
        }
1963
        return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1964
    }
1965
 
1966
 
1967
    /**
1968
     * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt.
1969
     *
1970
     * @param  int $lessonattempt the lesson attempt number (also known as retries)
1971
     * @param  int $userid        the user id to retrieve the data from
1972
     * @param  string $sort          an order to sort the results in (a valid SQL ORDER BY parameter)
1973
     * @param  string $fields        a comma separated list of fields to return
1974
     * @return array of pages
1975
     * @since  Moodle 3.3
1976
     */
1977
    public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') {
1978
        global $USER, $DB;
1979
 
1980
        if ($userid === null) {
1981
            $userid = $USER->id;
1982
        }
1983
        $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt);
1984
        return $DB->get_records('lesson_branch', $conditions, $sort, $fields);
1985
    }
1986
 
1987
    /**
1988
     * Returns the first page for the lesson or false if there isn't one.
1989
     *
1990
     * This method should be called via the magic method __get();
1991
     * <code>
1992
     * $firstpage = $lesson->firstpage;
1993
     * </code>
1994
     *
1995
     * @return lesson_page|bool Returns the lesson_page specialised object or false
1996
     */
1997
    protected function get_firstpage() {
1998
        $pages = $this->load_all_pages();
1999
        if (count($pages) > 0) {
2000
            foreach ($pages as $page) {
2001
                if ((int)$page->prevpageid === 0) {
2002
                    return $page;
2003
                }
2004
            }
2005
        }
2006
        return false;
2007
    }
2008
 
2009
    /**
2010
     * Returns the last page for the lesson or false if there isn't one.
2011
     *
2012
     * This method should be called via the magic method __get();
2013
     * <code>
2014
     * $lastpage = $lesson->lastpage;
2015
     * </code>
2016
     *
2017
     * @return lesson_page|bool Returns the lesson_page specialised object or false
2018
     */
2019
    protected function get_lastpage() {
2020
        $pages = $this->load_all_pages();
2021
        if (count($pages) > 0) {
2022
            foreach ($pages as $page) {
2023
                if ((int)$page->nextpageid === 0) {
2024
                    return $page;
2025
                }
2026
            }
2027
        }
2028
        return false;
2029
    }
2030
 
2031
    /**
2032
     * Returns the id of the first page of this lesson. (prevpageid = 0)
2033
     * @return int
2034
     */
2035
    protected function get_firstpageid() {
2036
        global $DB;
2037
        if ($this->firstpageid == null) {
2038
            if (!$this->loadedallpages) {
2039
                $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
2040
                if (!$firstpageid) {
2041
                    throw new \moodle_exception('cannotfindfirstpage', 'lesson');
2042
                }
2043
                $this->firstpageid = $firstpageid;
2044
            } else {
2045
                $firstpage = $this->get_firstpage();
2046
                $this->firstpageid = $firstpage->id;
2047
            }
2048
        }
2049
        return $this->firstpageid;
2050
    }
2051
 
2052
    /**
2053
     * Returns the id of the last page of this lesson. (nextpageid = 0)
2054
     * @return int
2055
     */
2056
    public function get_lastpageid() {
2057
        global $DB;
2058
        if ($this->lastpageid == null) {
2059
            if (!$this->loadedallpages) {
2060
                $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
2061
                if (!$lastpageid) {
2062
                    throw new \moodle_exception('cannotfindlastpage', 'lesson');
2063
                }
2064
                $this->lastpageid = $lastpageid;
2065
            } else {
2066
                $lastpageid = $this->get_lastpage();
2067
                $this->lastpageid = $lastpageid->id;
2068
            }
2069
        }
2070
 
2071
        return $this->lastpageid;
2072
    }
2073
 
2074
     /**
2075
     * Gets the next page id to display after the one that is provided.
2076
     * @param int $nextpageid
2077
     * @return bool
2078
     */
2079
    public function get_next_page($nextpageid) {
2080
        global $USER, $DB;
2081
        $allpages = $this->load_all_pages();
2082
        if ($this->properties->nextpagedefault) {
2083
            // in Flash Card mode...first get number of retakes
2084
            $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2085
            shuffle($allpages);
2086
            $found = false;
2087
            if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
2088
                foreach ($allpages as $nextpage) {
2089
                    if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
2090
                        $found = true;
2091
                        break;
2092
                    }
2093
                }
2094
            } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
2095
                foreach ($allpages as $nextpage) {
2096
                    if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
2097
                        $found = true;
2098
                        break;
2099
                    }
2100
                }
2101
            }
2102
            if ($found) {
2103
                if ($this->properties->maxpages) {
2104
                    // check number of pages viewed (in the lesson)
2105
                    if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
2106
                        return LESSON_EOL;
2107
                    }
2108
                }
2109
                return $nextpage->id;
2110
            }
2111
        }
2112
        // In a normal lesson mode
2113
        foreach ($allpages as $nextpage) {
2114
            if ((int)$nextpage->id === (int)$nextpageid) {
2115
                return $nextpage->id;
2116
            }
2117
        }
2118
        return LESSON_EOL;
2119
    }
2120
 
2121
    /**
2122
     * Sets a message against the session for this lesson that will displayed next
2123
     * time the lesson processes messages
2124
     *
2125
     * @param string $message
2126
     * @param string $class
2127
     * @param string $align
2128
     * @return bool
2129
     */
2130
    public function add_message($message, $class="notifyproblem", $align='center') {
2131
        global $SESSION;
2132
 
2133
        if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
2134
            $SESSION->lesson_messages = array();
2135
            $SESSION->lesson_messages[$this->properties->id] = array();
2136
        } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
2137
            $SESSION->lesson_messages[$this->properties->id] = array();
2138
        }
2139
 
2140
        $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
2141
 
2142
        return true;
2143
    }
2144
 
2145
    /**
2146
     * Check if the lesson is accessible at the present time
2147
     * @return bool True if the lesson is accessible, false otherwise
2148
     */
2149
    public function is_accessible() {
2150
        $available = $this->properties->available;
2151
        $deadline = $this->properties->deadline;
2152
        return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
2153
    }
2154
 
2155
    /**
2156
     * Starts the lesson time for the current user
2157
     * @return bool Returns true
2158
     */
2159
    public function start_timer() {
2160
        global $USER, $DB;
2161
 
2162
        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2163
            false, MUST_EXIST);
2164
 
2165
        // Trigger lesson started event.
2166
        $event = \mod_lesson\event\lesson_started::create(array(
2167
            'objectid' => $this->properties()->id,
2168
            'context' => context_module::instance($cm->id),
2169
            'courseid' => $this->properties()->course
2170
        ));
2171
        $event->trigger();
2172
 
2173
        $USER->startlesson[$this->properties->id] = true;
2174
 
2175
        $timenow = time();
2176
        $startlesson = new stdClass;
2177
        $startlesson->lessonid = $this->properties->id;
2178
        $startlesson->userid = $USER->id;
2179
        $startlesson->starttime = $timenow;
2180
        $startlesson->lessontime = $timenow;
2181
        if (WS_SERVER) {
2182
            $startlesson->timemodifiedoffline = $timenow;
2183
        }
2184
        $DB->insert_record('lesson_timer', $startlesson);
2185
        if ($this->properties->timelimit) {
2186
            $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
2187
        }
2188
        return true;
2189
    }
2190
 
2191
    /**
2192
     * Updates the timer to the current time and returns the new timer object
2193
     * @param bool $restart If set to true the timer is restarted
2194
     * @param bool $continue If set to true AND $restart=true then the timer
2195
     *                        will continue from a previous attempt
2196
     * @return stdClass The new timer
2197
     */
2198
    public function update_timer($restart=false, $continue=false, $endreached =false) {
2199
        global $USER, $DB;
2200
 
2201
        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2202
 
2203
        // clock code
2204
        // get time information for this user
2205
        if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) {
2206
            $this->start_timer();
2207
            $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1);
2208
        }
2209
        $timer = current($timer); // This will get the latest start time record.
2210
 
2211
        if ($restart) {
2212
            if ($continue) {
2213
                // continue a previous test, need to update the clock  (think this option is disabled atm)
2214
                $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
2215
 
2216
                // Trigger lesson resumed event.
2217
                $event = \mod_lesson\event\lesson_resumed::create(array(
2218
                    'objectid' => $this->properties->id,
2219
                    'context' => context_module::instance($cm->id),
2220
                    'courseid' => $this->properties->course
2221
                ));
2222
                $event->trigger();
2223
 
2224
            } else {
2225
                // starting over, so reset the clock
2226
                $timer->starttime = time();
2227
 
2228
                // Trigger lesson restarted event.
2229
                $event = \mod_lesson\event\lesson_restarted::create(array(
2230
                    'objectid' => $this->properties->id,
2231
                    'context' => context_module::instance($cm->id),
2232
                    'courseid' => $this->properties->course
2233
                ));
2234
                $event->trigger();
2235
 
2236
            }
2237
        }
2238
 
2239
        $timenow = time();
2240
        $timer->lessontime = $timenow;
2241
        if (WS_SERVER) {
2242
            $timer->timemodifiedoffline = $timenow;
2243
        }
2244
        $timer->completed = $endreached;
2245
        $DB->update_record('lesson_timer', $timer);
2246
 
2247
        // Update completion state.
2248
        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2249
            false, MUST_EXIST);
2250
        $course = get_course($cm->course);
2251
        $completion = new completion_info($course);
2252
        if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
2253
            $completion->update_state($cm, COMPLETION_COMPLETE);
2254
        }
2255
        return $timer;
2256
    }
2257
 
2258
    /**
2259
     * Updates the timer to the current time then stops it by unsetting the user var
2260
     * @return bool Returns true
2261
     */
2262
    public function stop_timer() {
2263
        global $USER, $DB;
2264
        unset($USER->startlesson[$this->properties->id]);
2265
 
2266
        $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
2267
            false, MUST_EXIST);
2268
 
2269
        // Trigger lesson ended event.
2270
        $event = \mod_lesson\event\lesson_ended::create(array(
2271
            'objectid' => $this->properties()->id,
2272
            'context' => context_module::instance($cm->id),
2273
            'courseid' => $this->properties()->course
2274
        ));
2275
        $event->trigger();
2276
 
2277
        return $this->update_timer(false, false, true);
2278
    }
2279
 
2280
    /**
2281
     * Checks to see if the lesson has pages
2282
     */
2283
    public function has_pages() {
2284
        global $DB;
2285
        $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
2286
        return ($pagecount>0);
2287
    }
2288
 
2289
    /**
2290
     * Returns the link for the related activity
2291
     * @return string
2292
     */
2293
    public function link_for_activitylink() {
2294
        global $DB;
2295
        $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
2296
        if ($module) {
2297
            $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
2298
            if ($modname) {
2299
                $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
2300
                if ($instancename) {
2301
                    return html_writer::link(
2302
                        new moodle_url('/mod/'.$modname.'/view.php', [
2303
                            'id' => $this->properties->activitylink,
2304
                        ]),
2305
                        get_string(
2306
                            'activitylinkname',
2307
                            'lesson',
2308
                            format_string($instancename, true, ['context' => $this->get_context()]),
2309
                        ),
2310
                        ['class' => 'centerpadded lessonbutton standardbutton pr-3'],
2311
                    );
2312
                }
2313
            }
2314
        }
2315
        return '';
2316
    }
2317
 
2318
    /**
2319
     * Loads the requested page.
2320
     *
2321
     * This function will return the requested page id as either a specialised
2322
     * lesson_page object OR as a generic lesson_page.
2323
     * If the page has been loaded previously it will be returned from the pages
2324
     * array, otherwise it will be loaded from the database first
2325
     *
2326
     * @param int $pageid
2327
     * @return lesson_page A lesson_page object or an object that extends it
2328
     */
2329
    public function load_page($pageid) {
2330
        if (!array_key_exists($pageid, $this->pages)) {
2331
            $manager = lesson_page_type_manager::get($this);
2332
            $this->pages[$pageid] = $manager->load_page($pageid, $this);
2333
        }
2334
        return $this->pages[$pageid];
2335
    }
2336
 
2337
    /**
2338
     * Loads ALL of the pages for this lesson
2339
     *
2340
     * @return array An array containing all pages from this lesson
2341
     */
2342
    public function load_all_pages() {
2343
        if (!$this->loadedallpages) {
2344
            $manager = lesson_page_type_manager::get($this);
2345
            $this->pages = $manager->load_all_pages($this);
2346
            $this->loadedallpages = true;
2347
        }
2348
        return $this->pages;
2349
    }
2350
 
2351
    /**
2352
     * Duplicate the lesson page.
2353
     *
2354
     * @param  int $pageid Page ID of the page to duplicate.
2355
     * @return void.
2356
     */
2357
    public function duplicate_page($pageid) {
2358
        global $PAGE;
2359
        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2360
        $context = context_module::instance($cm->id);
2361
        // Load the page.
2362
        $page = $this->load_page($pageid);
2363
        $properties = $page->properties();
2364
        // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
2365
        if (!$properties->qoption) {
2366
            unset($properties->qoption);
2367
        }
2368
        if (!$properties->layout) {
2369
            unset($properties->layout);
2370
        }
2371
        if (!$properties->display) {
2372
            unset($properties->display);
2373
        }
2374
 
2375
        $properties->pageid = $pageid;
2376
        // Add text and format into the format required to create a new page.
2377
        $properties->contents_editor = array(
2378
            'text' => $properties->contents,
2379
            'format' => $properties->contentsformat
2380
        );
2381
        $answers = $page->get_answers();
2382
        // Answers need to be added to $properties.
2383
        $i = 0;
2384
        $answerids = array();
2385
        foreach ($answers as $answer) {
2386
            // Needs to be rearranged to work with the create function.
2387
            $properties->answer_editor[$i] = array(
2388
                'text' => $answer->answer,
2389
                'format' => $answer->answerformat
2390
            );
2391
 
2392
            $properties->response_editor[$i] = array(
2393
              'text' => $answer->response,
2394
              'format' => $answer->responseformat
2395
            );
2396
            $answerids[] = $answer->id;
2397
 
2398
            $properties->jumpto[$i] = $answer->jumpto;
2399
            $properties->score[$i] = $answer->score;
2400
 
2401
            $i++;
2402
        }
2403
        // Create the duplicate page.
2404
        $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
2405
        $newanswers = $newlessonpage->get_answers();
2406
        // Copy over the file areas as well.
2407
        $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
2408
        $j = 0;
2409
        foreach ($newanswers as $answer) {
2410
            if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
2411
                $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
2412
            }
2413
            if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
2414
                $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
2415
            }
2416
            $j++;
2417
        }
2418
    }
2419
 
2420
    /**
2421
     * Copy the files from one page to another.
2422
     *
2423
     * @param  string $filearea Area that the files are stored.
2424
     * @param  int $itemid Item ID.
2425
     * @param  int $newitemid The item ID for the new page.
2426
     * @param  int $contextid Context ID for this page.
2427
     * @return void.
2428
     */
2429
    protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
2430
        $fs = get_file_storage();
2431
        $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
2432
        foreach ($files as $file) {
2433
            $fieldupdates = array('itemid' => $newitemid);
2434
            $fs->create_file_from_storedfile($fieldupdates, $file);
2435
        }
2436
    }
2437
 
2438
    /**
2439
     * Determines if a jumpto value is correct or not.
2440
     *
2441
     * returns true if jumpto page is (logically) after the pageid page or
2442
     * if the jumpto value is a special value.  Returns false in all other cases.
2443
     *
2444
     * @param int $pageid Id of the page from which you are jumping from.
2445
     * @param int $jumpto The jumpto number.
2446
     * @return boolean True or false after a series of tests.
2447
     **/
2448
    public function jumpto_is_correct($pageid, $jumpto) {
2449
        global $DB;
2450
 
2451
        // first test the special values
2452
        if (!$jumpto) {
2453
            // same page
2454
            return false;
2455
        } elseif ($jumpto == LESSON_NEXTPAGE) {
2456
            return true;
2457
        } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2458
            return true;
2459
        } elseif ($jumpto == LESSON_RANDOMPAGE) {
2460
            return true;
2461
        } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2462
            return true;
2463
        } elseif ($jumpto == LESSON_EOL) {
2464
            return true;
2465
        }
2466
 
2467
        $pages = $this->load_all_pages();
2468
        $apageid = $pages[$pageid]->nextpageid;
2469
        while ($apageid != 0) {
2470
            if ($jumpto == $apageid) {
2471
                return true;
2472
            }
2473
            $apageid = $pages[$apageid]->nextpageid;
2474
        }
2475
        return false;
2476
    }
2477
 
2478
    /**
2479
     * Returns the time a user has remaining on this lesson
2480
     * @param int $starttime Starttime timestamp
2481
     * @return string
2482
     */
2483
    public function time_remaining($starttime) {
2484
        $timeleft = $starttime + $this->properties->timelimit - time();
2485
        $hours = floor($timeleft/3600);
2486
        $timeleft = $timeleft - ($hours * 3600);
2487
        $minutes = floor($timeleft/60);
2488
        $secs = $timeleft - ($minutes * 60);
2489
 
2490
        if ($minutes < 10) {
2491
            $minutes = "0$minutes";
2492
        }
2493
        if ($secs < 10) {
2494
            $secs = "0$secs";
2495
        }
2496
        $output   = array();
2497
        $output[] = $hours;
2498
        $output[] = $minutes;
2499
        $output[] = $secs;
2500
        $output = implode(':', $output);
2501
        return $output;
2502
    }
2503
 
2504
    /**
2505
     * Interprets LESSON_CLUSTERJUMP jumpto value.
2506
     *
2507
     * This will select a page randomly
2508
     * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
2509
     * and the page selected will be a page that has not been viewed already
2510
     * and if any pages are within a branch table or end of branch then only 1 page within
2511
     * the branch table or end of branch will be randomly selected (sub clustering).
2512
     *
2513
     * @param int $pageid Id of the current page from which we are jumping from.
2514
     * @param int $userid Id of the user.
2515
     * @return int The id of the next page.
2516
     **/
2517
    public function cluster_jump($pageid, $userid=null) {
2518
        global $DB, $USER;
2519
 
2520
        if ($userid===null) {
2521
            $userid = $USER->id;
2522
        }
2523
        // get the number of retakes
2524
        if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
2525
            $retakes = 0;
2526
        }
2527
        // get all the lesson_attempts aka what the user has seen
2528
        $seenpages = array();
2529
        if ($attempts = $this->get_attempts($retakes)) {
2530
            foreach ($attempts as $attempt) {
2531
                $seenpages[$attempt->pageid] = $attempt->pageid;
2532
            }
2533
 
2534
        }
2535
 
2536
        // get the lesson pages
2537
        $lessonpages = $this->load_all_pages();
2538
        // find the start of the cluster
2539
        while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
2540
            if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
2541
                break;
2542
            }
2543
            $pageid = $lessonpages[$pageid]->prevpageid;
2544
        }
2545
 
2546
        $clusterpages = array();
2547
        $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
2548
        $unseen = array();
2549
        foreach ($clusterpages as $key=>$cluster) {
2550
            // Remove the page if  it is in a branch table or is an endofbranch.
2551
            if ($this->is_sub_page_of_type($cluster->id,
2552
                    array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
2553
                    || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
2554
                unset($clusterpages[$key]);
2555
            } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
2556
                // If branchtable, check to see if any pages inside have been viewed.
2557
                $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2558
                $flag = true;
2559
                foreach ($branchpages as $branchpage) {
2560
                    if (array_key_exists($branchpage->id, $seenpages)) {  // Check if any of the pages have been viewed.
2561
                        $flag = false;
2562
                    }
2563
                }
2564
                if ($flag && count($branchpages) > 0) {
2565
                    // Add branch table.
2566
                    $unseen[] = $cluster;
2567
                }
2568
            } elseif ($cluster->is_unseen($seenpages)) {
2569
                $unseen[] = $cluster;
2570
            }
2571
        }
2572
 
2573
        if (count($unseen) > 0) {
2574
            // it does not contain elements, then use exitjump, otherwise find out next page/branch
2575
            $nextpage = $unseen[rand(0, count($unseen)-1)];
2576
            if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
2577
                // if branch table, then pick a random page inside of it
2578
                $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
2579
                return $branchpages[rand(0, count($branchpages)-1)]->id;
2580
            } else { // otherwise, return the page's id
2581
                return $nextpage->id;
2582
            }
2583
        } else {
2584
            // seen all there is to see, leave the cluster
2585
            if (end($clusterpages)->nextpageid == 0) {
2586
                return LESSON_EOL;
2587
            } else {
2588
                $clusterendid = $pageid;
2589
                while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
2590
                    if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2591
                        break;
2592
                    }
2593
                    $clusterendid = $lessonpages[$clusterendid]->nextpageid;
2594
                }
2595
                $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
2596
                if ($exitjump == LESSON_NEXTPAGE) {
2597
                    $exitjump = $lessonpages[$clusterendid]->nextpageid;
2598
                }
2599
                if ($exitjump == 0) {
2600
                    return LESSON_EOL;
2601
                } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
2602
                    return $exitjump;
2603
                } else {
2604
                    if (!array_key_exists($exitjump, $lessonpages)) {
2605
                        $found = false;
2606
                        foreach ($lessonpages as $page) {
2607
                            if ($page->id === $clusterendid) {
2608
                                $found = true;
2609
                            } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
2610
                                $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
2611
                                if ($exitjump == LESSON_NEXTPAGE) {
2612
                                    $exitjump = $lessonpages[$page->id]->nextpageid;
2613
                                }
2614
                                break;
2615
                            }
2616
                        }
2617
                    }
2618
                    if (!array_key_exists($exitjump, $lessonpages)) {
2619
                        return LESSON_EOL;
2620
                    }
2621
                    // Check to see that the return type is not a cluster.
2622
                    if ($lessonpages[$exitjump]->qtype == LESSON_PAGE_CLUSTER) {
2623
                        // If the exitjump is a cluster then go through this function again and try to find an unseen question.
2624
                        $exitjump = $this->cluster_jump($exitjump, $userid);
2625
                    }
2626
                    return $exitjump;
2627
                }
2628
            }
2629
        }
2630
    }
2631
 
2632
    /**
2633
     * Finds all pages that appear to be a subtype of the provided pageid until
2634
     * an end point specified within $ends is encountered or no more pages exist
2635
     *
2636
     * @param int $pageid
2637
     * @param array $ends An array of LESSON_PAGE_* types that signify an end of
2638
     *               the subtype
2639
     * @return array An array of specialised lesson_page objects
2640
     */
2641
    public function get_sub_pages_of($pageid, array $ends) {
2642
        $lessonpages = $this->load_all_pages();
2643
        $pageid = $lessonpages[$pageid]->nextpageid;  // move to the first page after the branch table
2644
        $pages = array();
2645
 
2646
        while (true) {
2647
            if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
2648
                break;
2649
            }
2650
            $pages[] = $lessonpages[$pageid];
2651
            $pageid = $lessonpages[$pageid]->nextpageid;
2652
        }
2653
 
2654
        return $pages;
2655
    }
2656
 
2657
    /**
2658
     * Checks to see if the specified page[id] is a subpage of a type specified in
2659
     * the $types array, until either there are no more pages of we find a type
2660
     * corresponding to that of a type specified in $ends
2661
     *
2662
     * @param int $pageid The id of the page to check
2663
     * @param array $types An array of types that would signify this page was a subpage
2664
     * @param array $ends An array of types that mean this is not a subpage
2665
     * @return bool
2666
     */
2667
    public function is_sub_page_of_type($pageid, array $types, array $ends) {
2668
        $pages = $this->load_all_pages();
2669
        $pageid = $pages[$pageid]->prevpageid; // move up one
2670
 
2671
        array_unshift($ends, 0);
2672
        // go up the pages till branch table
2673
        while (true) {
2674
            if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2675
                return false;
2676
            } else if (in_array($pages[$pageid]->qtype, $types)) {
2677
                return true;
2678
            }
2679
            $pageid = $pages[$pageid]->prevpageid;
2680
        }
2681
    }
2682
 
2683
    /**
2684
     * Move a page resorting all other pages.
2685
     *
2686
     * @param int $pageid
2687
     * @param int $after
2688
     * @return void
2689
     */
2690
    public function resort_pages($pageid, $after) {
2691
        global $CFG;
2692
 
2693
        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2694
        $context = context_module::instance($cm->id);
2695
 
2696
        $pages = $this->load_all_pages();
2697
 
2698
        if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2699
            throw new \moodle_exception('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2700
        }
2701
 
2702
        $pagetomove = clone($pages[$pageid]);
2703
        unset($pages[$pageid]);
2704
 
2705
        $pageids = array();
2706
        if ($after === 0) {
2707
            $pageids['p0'] = $pageid;
2708
        }
2709
        foreach ($pages as $page) {
2710
            $pageids[] = $page->id;
2711
            if ($page->id == $after) {
2712
                $pageids[] = $pageid;
2713
            }
2714
        }
2715
 
2716
        $pageidsref = $pageids;
2717
        reset($pageidsref);
2718
        $prev = 0;
2719
        $next = next($pageidsref);
2720
        foreach ($pageids as $pid) {
2721
            if ($pid === $pageid) {
2722
                $page = $pagetomove;
2723
            } else {
2724
                $page = $pages[$pid];
2725
            }
2726
            if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2727
                $page->move($next, $prev);
2728
 
2729
                if ($pid === $pageid) {
2730
                    // We will trigger an event.
2731
                    $pageupdated = array('next' => $next, 'prev' => $prev);
2732
                }
2733
            }
2734
 
2735
            $prev = $page->id;
2736
            $next = next($pageidsref);
2737
            if (!$next) {
2738
                $next = 0;
2739
            }
2740
        }
2741
 
2742
        // Trigger an event: page moved.
2743
        if (!empty($pageupdated)) {
2744
            $eventparams = array(
2745
                'context' => $context,
2746
                'objectid' => $pageid,
2747
                'other' => array(
2748
                    'pagetype' => $page->get_typestring(),
2749
                    'prevpageid' => $pageupdated['prev'],
2750
                    'nextpageid' => $pageupdated['next']
2751
                )
2752
            );
2753
            $event = \mod_lesson\event\page_moved::create($eventparams);
2754
            $event->trigger();
2755
        }
2756
 
2757
    }
2758
 
2759
    /**
2760
     * Return the lesson context object.
2761
     *
2762
     * @return stdClass context
2763
     * @since  Moodle 3.3
2764
     */
2765
    public function get_context() {
2766
        if ($this->context == null) {
2767
            $this->context = context_module::instance($this->get_cm()->id);
2768
        }
2769
        return $this->context;
2770
    }
2771
 
2772
    /**
2773
     * Set the lesson course module object.
2774
     *
2775
     * @param stdClass $cm course module objct
2776
     * @since  Moodle 3.3
2777
     */
2778
    private function set_cm($cm) {
2779
        $this->cm = $cm;
2780
    }
2781
 
2782
    /**
2783
     * Return the lesson course module object.
2784
     *
2785
     * @return stdClass course module
2786
     * @since  Moodle 3.3
2787
     */
2788
    public function get_cm() {
2789
        if ($this->cm == null) {
2790
            $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2791
        }
2792
        return $this->cm;
2793
    }
2794
 
2795
    /**
2796
     * Set the lesson course object.
2797
     *
2798
     * @param stdClass $course course objct
2799
     * @since  Moodle 3.3
2800
     */
2801
    private function set_courserecord($course) {
2802
        $this->courserecord = $course;
2803
    }
2804
 
2805
    /**
2806
     * Return the lesson course object.
2807
     *
2808
     * @return stdClass course
2809
     * @since  Moodle 3.3
2810
     */
2811
    public function get_courserecord() {
2812
        global $DB;
2813
 
2814
        if ($this->courserecord == null) {
2815
            $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course));
2816
        }
2817
        return $this->courserecord;
2818
    }
2819
 
2820
    /**
2821
     * Check if the user can manage the lesson activity.
2822
     *
2823
     * @return bool true if the user can manage the lesson
2824
     * @since  Moodle 3.3
2825
     */
2826
    public function can_manage() {
2827
        return has_capability('mod/lesson:manage', $this->get_context());
2828
    }
2829
 
2830
    /**
2831
     * Check if time restriction is applied.
2832
     *
2833
     * @return mixed false if  there aren't restrictions or an object with the restriction information
2834
     * @since  Moodle 3.3
2835
     */
2836
    public function get_time_restriction_status() {
2837
        if ($this->can_manage()) {
2838
            return false;
2839
        }
2840
 
2841
        if (!$this->is_accessible()) {
2842
            if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2843
                $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2844
            } else {
2845
                $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2846
            }
2847
            return (object) $status;
2848
        }
2849
        return false;
2850
    }
2851
 
2852
    /**
2853
     * Check if password restriction is applied.
2854
     *
2855
     * @param string $userpassword the user password to check (if the restriction is set)
2856
     * @return mixed false if there aren't restrictions or an object with the restriction information
2857
     * @since  Moodle 3.3
2858
     */
2859
    public function get_password_restriction_status($userpassword) {
2860
        global $USER;
2861
        if ($this->can_manage()) {
2862
            return false;
2863
        }
2864
 
2865
        if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2866
            $correctpass = false;
2867
            if (!empty($userpassword) &&
2868
                    (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2869
                // With or without md5 for backward compatibility (MDL-11090).
2870
                $correctpass = true;
2871
                $USER->lessonloggedin[$this->id] = true;
2872
            } else if (isset($this->properties->extrapasswords)) {
2873
                // Group overrides may have additional passwords.
2874
                foreach ($this->properties->extrapasswords as $password) {
2875
                    if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2876
                        $correctpass = true;
2877
                        $USER->lessonloggedin[$this->id] = true;
2878
                    }
2879
                }
2880
            }
2881
            return !$correctpass;
2882
        }
2883
        return false;
2884
    }
2885
 
2886
    /**
2887
     * Check if dependencies restrictions are applied.
2888
     *
2889
     * @return mixed false if there aren't restrictions or an object with the restriction information
2890
     * @since  Moodle 3.3
2891
     */
2892
    public function get_dependencies_restriction_status() {
2893
        global $DB, $USER;
2894
        if ($this->can_manage()) {
2895
            return false;
2896
        }
2897
 
2898
        if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2899
            // Lesson exists, so we can proceed.
2900
            $conditions = unserialize_object($this->properties->conditions);
2901
            // Assume false for all.
2902
            $errors = array();
2903
            // Check for the timespent condition.
2904
            if (!empty($conditions->timespent)) {
2905
                $timespent = false;
2906
                if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2907
                    // Go through all the times and test to see if any of them satisfy the condition.
2908
                    foreach ($attempttimes as $attempttime) {
2909
                        $duration = $attempttime->lessontime - $attempttime->starttime;
2910
                        if ($conditions->timespent < $duration / 60) {
2911
                            $timespent = true;
2912
                        }
2913
                    }
2914
                }
2915
                if (!$timespent) {
2916
                    $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2917
                }
2918
            }
2919
            // Check for the gradebetterthan condition.
2920
            if (!empty($conditions->gradebetterthan)) {
2921
                $gradebetterthan = false;
2922
                if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2923
                    // Go through all the grades and test to see if any of them satisfy the condition.
2924
                    foreach ($studentgrades as $studentgrade) {
2925
                        if ($studentgrade->grade >= $conditions->gradebetterthan) {
2926
                            $gradebetterthan = true;
2927
                        }
2928
                    }
2929
                }
2930
                if (!$gradebetterthan) {
2931
                    $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2932
                }
2933
            }
2934
            // Check for the completed condition.
2935
            if (!empty($conditions->completed)) {
2936
                if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2937
                    $errors[] = get_string('completederror', 'lesson');
2938
                }
2939
            }
2940
            if (!empty($errors)) {
2941
                return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2942
            }
2943
        }
2944
        return false;
2945
    }
2946
 
2947
    /**
2948
     * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed).
2949
     *
2950
     * @return bool true if is in review mode
2951
     * @since  Moodle 3.3
2952
     */
2953
    public function is_in_review_mode() {
2954
        global $DB, $USER;
2955
 
2956
        $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
2957
        if ($userhasgrade && !$this->properties->retake) {
2958
            return true;
2959
        }
2960
        return false;
2961
    }
2962
 
2963
    /**
2964
     * Return the last page the current user saw.
2965
     *
2966
     * @param int $retriescount the number of retries for the lesson (the last retry number).
2967
     * @return mixed false if the user didn't see the lesson or the last page id
2968
     */
2969
    public function get_last_page_seen($retriescount) {
2970
        global $DB, $USER;
2971
 
2972
        $lastpageseen = false;
2973
        $allattempts = $this->get_attempts($retriescount);
2974
        if (!empty($allattempts)) {
2975
            $attempt = end($allattempts);
2976
            $attemptpage = $this->load_page($attempt->pageid);
2977
            $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
2978
            // Convert the jumpto to a proper page id.
2979
            if ($jumpto == 0) {
2980
                // Check if a question has been incorrectly answered AND no more attempts at it are left.
2981
                $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
2982
                if (count($nattempts) >= $this->properties->maxattempts) {
2983
                    $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2984
                } else {
2985
                    $lastpageseen = $attempt->pageid;
2986
                }
2987
            } else if ($jumpto == LESSON_NEXTPAGE) {
2988
                $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
2989
            } else if ($jumpto == LESSON_CLUSTERJUMP) {
2990
                $lastpageseen = $this->cluster_jump($attempt->pageid);
2991
            } else {
2992
                $lastpageseen = $jumpto;
2993
            }
2994
        }
2995
 
2996
        if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
2997
            // In here, user has viewed a branch table.
2998
            $lastbranchtable = current($branchtables);
2999
            if (count($allattempts) > 0) {
3000
                if ($lastbranchtable->timeseen > $attempt->timeseen) {
3001
                    // This branch table was viewed more recently than the question page.
3002
                    if (!empty($lastbranchtable->nextpageid)) {
3003
                        $lastpageseen = $lastbranchtable->nextpageid;
3004
                    } else {
3005
                        // Next page ID did not exist prior to MDL-34006.
3006
                        $lastpageseen = $lastbranchtable->pageid;
3007
                    }
3008
                }
3009
            } else {
3010
                // Has not answered any questions but has viewed a branch table.
3011
                if (!empty($lastbranchtable->nextpageid)) {
3012
                    $lastpageseen = $lastbranchtable->nextpageid;
3013
                } else {
3014
                    // Next page ID did not exist prior to MDL-34006.
3015
                    $lastpageseen = $lastbranchtable->pageid;
3016
                }
3017
            }
3018
        }
3019
        return $lastpageseen;
3020
    }
3021
 
3022
    /**
3023
     * Return the number of retries in a lesson for a given user.
3024
     *
3025
     * @param  int $userid the user id
3026
     * @return int the retries count
3027
     * @since  Moodle 3.3
3028
     */
3029
    public function count_user_retries($userid) {
3030
        global $DB;
3031
 
3032
        return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid));
3033
    }
3034
 
3035
    /**
3036
     * Check if a user left a timed session.
3037
     *
3038
     * @param int $retriescount the number of retries for the lesson (the last retry number).
3039
     * @return true if the user left the timed session
3040
     * @since  Moodle 3.3
3041
     */
3042
    public function left_during_timed_session($retriescount) {
3043
        global $DB, $USER;
3044
 
3045
        $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount);
3046
        return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0;
3047
    }
3048
 
3049
    /**
3050
     * Trigger module viewed event and set the module viewed for completion.
3051
     *
3052
     * @since  Moodle 3.3
3053
     */
3054
    public function set_module_viewed() {
3055
        global $CFG;
3056
        require_once($CFG->libdir . '/completionlib.php');
3057
 
3058
        // Trigger module viewed event.
3059
        $event = \mod_lesson\event\course_module_viewed::create(array(
3060
            'objectid' => $this->properties->id,
3061
            'context' => $this->get_context()
3062
        ));
3063
        $event->add_record_snapshot('course_modules', $this->get_cm());
3064
        $event->add_record_snapshot('course', $this->get_courserecord());
3065
        $event->trigger();
3066
 
3067
        // Mark as viewed.
3068
        $completion = new completion_info($this->get_courserecord());
3069
        $completion->set_module_viewed($this->get_cm());
3070
    }
3071
 
3072
    /**
3073
     * Return the timers in the current lesson for the given user.
3074
     *
3075
     * @param  int      $userid    the user id
3076
     * @param  string   $sort      an order to sort the results in (optional, a valid SQL ORDER BY parameter).
3077
     * @param  string   $fields    a comma separated list of fields to return
3078
     * @param  int      $limitfrom return a subset of records, starting at this point (optional).
3079
     * @param  int      $limitnum  return a subset comprising this many records in total (optional, required if $limitfrom is set).
3080
     * @return array    list of timers for the given user in the lesson
3081
     * @since  Moodle 3.3
3082
     */
3083
    public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) {
3084
        global $DB, $USER;
3085
 
3086
        if ($userid === null) {
3087
            $userid = $USER->id;
3088
        }
3089
 
3090
        $params = array('lessonid' => $this->properties->id, 'userid' => $userid);
3091
        return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum);
3092
    }
3093
 
3094
    /**
3095
     * Check if the user is out of time in a timed lesson.
3096
     *
3097
     * @param  stdClass $timer timer object
3098
     * @return bool True if the user is on time, false is the user ran out of time
3099
     * @since  Moodle 3.3
3100
     */
3101
    public function check_time($timer) {
3102
        if ($this->properties->timelimit) {
3103
            $timeleft = $timer->starttime + $this->properties->timelimit - time();
3104
            if ($timeleft <= 0) {
3105
                // Out of time.
3106
                $this->add_message(get_string('eolstudentoutoftime', 'lesson'));
3107
                return false;
3108
            } else if ($timeleft < 60) {
3109
                // One minute warning.
3110
                $this->add_message(get_string('studentoneminwarning', 'lesson'));
3111
            }
3112
        }
3113
        return true;
3114
    }
3115
 
3116
    /**
3117
     * Add different informative messages to the given page.
3118
     *
3119
     * @param lesson_page $page page object
3120
     * @param reviewmode $bool whether we are in review mode or not
3121
     * @since  Moodle 3.3
3122
     */
3123
    public function add_messages_on_page_view(lesson_page $page, $reviewmode) {
3124
        global $DB, $USER;
3125
 
3126
        if (!$this->can_manage()) {
3127
            if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) {
3128
                // Tell student how many questions they have seen, how many are required and their grade.
3129
                $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3130
                $gradeinfo = lesson_grade($this, $ntries);
3131
                if ($gradeinfo->attempts) {
3132
                    if ($gradeinfo->nquestions < $this->properties->minquestions) {
3133
                        $a = new stdClass;
3134
                        $a->nquestions   = $gradeinfo->nquestions;
3135
                        $a->minquestions = $this->properties->minquestions;
3136
                        $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3137
                    }
3138
 
3139
                    if (!$reviewmode && $this->properties->ongoing) {
3140
                        $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
3141
                        if ($this->properties->grade != GRADE_TYPE_NONE) {
3142
                            $a = new stdClass;
3143
                            $a->grade = format_float($gradeinfo->grade * $this->properties->grade / 100, 1);
3144
                            $a->total = $this->properties->grade;
3145
                            $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
3146
                        }
3147
                    }
3148
                }
3149
            }
3150
        } else {
3151
            if ($this->properties->timelimit) {
3152
                $this->add_message(get_string('teachertimerwarning', 'lesson'));
3153
            }
3154
            if (lesson_display_teacher_warning($this)) {
3155
                // This is the warning msg for teachers to inform them that cluster
3156
                // and unseen does not work while logged in as a teacher.
3157
                $warningvars = new stdClass();
3158
                $warningvars->cluster = get_string('clusterjump', 'lesson');
3159
                $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
3160
                $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
3161
            }
3162
        }
3163
    }
3164
 
3165
    /**
3166
     * Get the ongoing score message for the user (depending on the user permission and lesson settings).
3167
     *
3168
     * @return str the ongoing score message
3169
     * @since  Moodle 3.3
3170
     */
3171
    public function get_ongoing_score_message() {
3172
        global $USER, $DB;
3173
 
3174
        $context = $this->get_context();
3175
 
3176
        if (has_capability('mod/lesson:manage', $context)) {
3177
            return get_string('teacherongoingwarning', 'lesson');
3178
        } else {
3179
            $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3180
            if (isset($USER->modattempts[$this->properties->id])) {
3181
                $ntries--;
3182
            }
3183
            $gradeinfo = lesson_grade($this, $ntries);
3184
            $a = new stdClass;
3185
            if ($this->properties->custom) {
3186
                $a->score = $gradeinfo->earned;
3187
                $a->currenthigh = $gradeinfo->total;
3188
                return get_string("ongoingcustom", "lesson", $a);
3189
            } else {
3190
                $a->correct = $gradeinfo->earned;
3191
                $a->viewed = $gradeinfo->attempts;
3192
                return get_string("ongoingnormal", "lesson", $a);
3193
            }
3194
        }
3195
    }
3196
 
3197
    /**
3198
     * Calculate the progress of the current user in the lesson.
3199
     *
3200
     * @return int the progress (scale 0-100)
3201
     * @since  Moodle 3.3
3202
     */
3203
    public function calculate_progress() {
3204
        global $USER, $DB;
3205
 
3206
        // Check if the user is reviewing the attempt.
3207
        if (isset($USER->modattempts[$this->properties->id])) {
3208
            return 100;
3209
        }
3210
 
3211
        // All of the lesson pages.
3212
        $pages = $this->load_all_pages();
3213
        foreach ($pages as $page) {
3214
            if ($page->prevpageid == 0) {
3215
                $pageid = $page->id;  // Find the first page id.
3216
                break;
3217
            }
3218
        }
3219
 
3220
        // Current attempt number.
3221
        if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) {
3222
            $ntries = 0;  // May not be necessary.
3223
        }
3224
 
3225
        $viewedpageids = array();
3226
        if ($attempts = $this->get_attempts($ntries, false)) {
3227
            foreach ($attempts as $attempt) {
3228
                $viewedpageids[$attempt->pageid] = $attempt;
3229
            }
3230
        }
3231
 
3232
        $viewedbranches = array();
3233
        // Collect all of the branch tables viewed.
3234
        if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) {
3235
            foreach ($branches as $branch) {
3236
                $viewedbranches[$branch->pageid] = $branch;
3237
            }
3238
            $viewedpageids = array_merge($viewedpageids, $viewedbranches);
3239
        }
3240
 
3241
        // Filter out the following pages:
3242
        // - End of Cluster
3243
        // - End of Branch
3244
        // - Pages found inside of Clusters
3245
        // Do not filter out Cluster Page(s) because we count a cluster as one.
3246
        // By keeping the cluster page, we get our 1.
3247
        $validpages = array();
3248
        while ($pageid != 0) {
3249
            $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids);
3250
        }
3251
 
3252
        // Progress calculation as a percent.
3253
        $progress = round(count($viewedpageids) / count($validpages), 2) * 100;
3254
        return (int) $progress;
3255
    }
3256
 
3257
    /**
3258
     * Calculate the correct page and prepare contents for a given page id (could be a page jump id).
3259
     *
3260
     * @param  int $pageid the given page id
3261
     * @param  mod_lesson_renderer $lessonoutput the lesson output rendered
3262
     * @param  bool $reviewmode whether we are in review mode or not
3263
     * @param  bool $redirect  Optional, default to true. Set to false to avoid redirection and return the page to redirect.
3264
     * @return array the page object and contents
3265
     * @throws moodle_exception
3266
     * @since  Moodle 3.3
3267
     */
3268
    public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) {
3269
        global $USER, $CFG;
3270
 
3271
        $page = $this->load_page($pageid);
3272
        // Check if the page is of a special type and if so take any nessecary action.
3273
        $newpageid = $page->callback_on_view($this->can_manage(), $redirect);
3274
 
3275
        // Avoid redirections returning the jump to special page id.
3276
        if (!$redirect && is_numeric($newpageid) && $newpageid < 0) {
3277
            return array($newpageid, null, null);
3278
        }
3279
 
3280
        if (is_numeric($newpageid)) {
3281
            $page = $this->load_page($newpageid);
3282
        }
3283
 
3284
        // Add different informative messages to the given page.
3285
        $this->add_messages_on_page_view($page, $reviewmode);
3286
 
3287
        if (is_array($page->answers) && count($page->answers) > 0) {
3288
            // This is for modattempts option.  Find the users previous answer to this page,
3289
            // and then display it below in answer processing.
3290
            if (isset($USER->modattempts[$this->properties->id])) {
3291
                $retries = $this->count_user_retries($USER->id);
3292
                if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) {
3293
                    throw new moodle_exception('cannotfindpreattempt', 'lesson');
3294
                }
3295
                $attempt = end($attempts);
3296
                $USER->modattempts[$this->properties->id] = $attempt;
3297
            } else {
3298
                $attempt = false;
3299
            }
3300
            $lessoncontent = $lessonoutput->display_page($this, $page, $attempt);
3301
        } else {
3302
            require_once($CFG->dirroot . '/mod/lesson/view_form.php');
3303
            $data = new stdClass;
3304
            $data->id = $this->get_cm()->id;
3305
            $data->pageid = $page->id;
3306
            $data->newpageid = $this->get_next_page($page->nextpageid);
3307
 
3308
            $customdata = array(
3309
                'title'     => $page->title,
3310
                'contents'  => $page->get_contents()
3311
            );
3312
            $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
3313
            $mform->set_data($data);
3314
            ob_start();
3315
            $mform->display();
3316
            $lessoncontent = ob_get_contents();
3317
            ob_end_clean();
3318
        }
3319
 
3320
        return array($page->id, $page, $lessoncontent);
3321
    }
3322
 
3323
    /**
3324
     * This returns a real page id to jump to (or LESSON_EOL) after processing page responses.
3325
     *
3326
     * @param  lesson_page $page      lesson page
3327
     * @param  int         $newpageid the new page id
3328
     * @return int the real page to jump to (or end of lesson)
3329
     * @since  Moodle 3.3
3330
     */
3331
    public function calculate_new_page_on_jump(lesson_page $page, $newpageid) {
3332
        global $USER, $DB;
3333
 
3334
        $canmanage = $this->can_manage();
3335
 
3336
        if (isset($USER->modattempts[$this->properties->id])) {
3337
            // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time.
3338
            if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) {
3339
                // Remember, this session variable holds the pageid of the last page that the user saw.
3340
                $newpageid = LESSON_EOL;
3341
            } else {
3342
                $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3343
                $nretakes--; // Make sure we are looking at the right try.
3344
                $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid");
3345
                $found = false;
3346
                $temppageid = 0;
3347
                // Make sure that the newpageid always defaults to something valid.
3348
                $newpageid = LESSON_EOL;
3349
                foreach ($attempts as $attempt) {
3350
                    if ($found && $temppageid != $attempt->pageid) {
3351
                        // Now try to find the next page, make sure next few attempts do no belong to current page.
3352
                        $newpageid = $attempt->pageid;
3353
                        break;
3354
                    }
3355
                    if ($attempt->pageid == $page->id) {
3356
                        $found = true; // If found current page.
3357
                        $temppageid = $attempt->pageid;
3358
                    }
3359
                }
3360
            }
3361
        } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) {
3362
            // Going to check to see if the page that the user is going to view next, is a cluster page.
3363
            // If so, dont display, go into the cluster.
3364
            // The $newpageid > 0 is used to filter out all of the negative code jumps.
3365
            $newpage = $this->load_page($newpageid);
3366
            if ($overridenewpageid = $newpage->override_next_page($newpageid)) {
3367
                $newpageid = $overridenewpageid;
3368
            }
3369
        } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) {
3370
            if ($canmanage) {
3371
                if ($page->nextpageid == 0) {
3372
                    $newpageid = LESSON_EOL;
3373
                } else {
3374
                    $newpageid = $page->nextpageid;
3375
                }
3376
            } else {
3377
                $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id);
3378
            }
3379
        } else if ($newpageid == LESSON_PREVIOUSPAGE) {
3380
            $newpageid = $page->prevpageid;
3381
        } else if ($newpageid == LESSON_RANDOMPAGE) {
3382
            $newpageid = lesson_random_question_jump($this, $page->id);
3383
        } else if ($newpageid == LESSON_CLUSTERJUMP) {
3384
            if ($canmanage) {
3385
                if ($page->nextpageid == 0) {  // If teacher, go to next page.
3386
                    $newpageid = LESSON_EOL;
3387
                } else {
3388
                    $newpageid = $page->nextpageid;
3389
                }
3390
            } else {
3391
                $newpageid = $this->cluster_jump($page->id);
3392
            }
3393
        } else if ($newpageid == 0) {
3394
            $newpageid = $page->id;
3395
        } else if ($newpageid == LESSON_NEXTPAGE) {
3396
            $newpageid = $this->get_next_page($page->nextpageid);
3397
        }
3398
 
3399
        return $newpageid;
3400
    }
3401
 
3402
    /**
3403
     * Process page responses.
3404
     *
3405
     * @param lesson_page $page page object
3406
     * @since  Moodle 3.3
3407
     */
3408
    public function process_page_responses(lesson_page $page) {
3409
        $context = $this->get_context();
3410
 
3411
        // Check the page has answers [MDL-25632].
3412
        if (count($page->answers) > 0) {
3413
            $result = $page->record_attempt($context);
3414
        } else {
3415
            // The page has no answers so we will just progress to the next page in the
3416
            // sequence (as set by newpageid).
3417
            $result = new stdClass;
3418
            $result->newpageid       = optional_param('newpageid', $page->nextpageid, PARAM_INT);
3419
            $result->nodefaultresponse  = true;
3420
            $result->inmediatejump = false;
3421
        }
3422
 
3423
        if ($result->inmediatejump) {
3424
            return $result;
3425
        }
3426
 
3427
        $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);
3428
 
3429
        return $result;
3430
    }
3431
 
3432
    /**
3433
     * Add different informative messages to the given page.
3434
     *
3435
     * @param lesson_page $page page object
3436
     * @param stdClass $result the page processing result object
3437
     * @param bool $reviewmode whether we are in review mode or not
3438
     * @since  Moodle 3.3
3439
     */
3440
    public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) {
3441
 
3442
        if ($this->can_manage()) {
3443
            // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher.
3444
            if (lesson_display_teacher_warning($this)) {
3445
                $warningvars = new stdClass();
3446
                $warningvars->cluster = get_string("clusterjump", "lesson");
3447
                $warningvars->unseen = get_string("unseenpageinbranch", "lesson");
3448
                $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars));
3449
            }
3450
            // Inform teacher that s/he will not see the timer.
3451
            if ($this->properties->timelimit) {
3452
                $this->add_message(get_string("teachertimerwarning", "lesson"));
3453
            }
3454
        }
3455
        // Report attempts remaining.
3456
        if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) {
3457
            $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining));
3458
        }
3459
    }
3460
 
3461
    /**
3462
     * Process and return all the information for the end of lesson page.
3463
     *
3464
     * @param string $outoftime used to check to see if the student ran out of time
3465
     * @return stdclass an object with all the page data ready for rendering
3466
     * @since  Moodle 3.3
3467
     */
3468
    public function process_eol_page($outoftime) {
3469
        global $DB, $USER;
3470
 
3471
        $course = $this->get_courserecord();
3472
        $cm = $this->get_cm();
3473
        $canmanage = $this->can_manage();
3474
 
3475
        // Init all the possible fields and values.
3476
        $data = (object) array(
3477
            'gradelesson' => true,
3478
            'notenoughtimespent' => false,
3479
            'numberofpagesviewed' => false,
3480
            'youshouldview' => false,
3481
            'numberofcorrectanswers' => false,
3482
            'displayscorewithessays' => false,
3483
            'displayscorewithoutessays' => false,
3484
            'yourcurrentgradeisoutof' => false,
3485
            'yourcurrentgradeis' => false,
3486
            'eolstudentoutoftimenoanswers' => false,
3487
            'welldone' => false,
3488
            'progressbar' => false,
3489
            'displayofgrade' => false,
3490
            'reviewlesson' => false,
3491
            'modattemptsnoteacher' => false,
3492
            'activitylink' => false,
3493
            'progresscompleted' => false,
3494
        );
3495
 
3496
        $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
3497
        if (isset($USER->modattempts[$this->properties->id])) {
3498
            $ntries--;  // Need to look at the old attempts :).
3499
        }
3500
 
3501
        $gradeinfo = lesson_grade($this, $ntries);
3502
        $data->gradeinfo = $gradeinfo;
3503
        if ($this->properties->custom && !$canmanage) {
3504
            // Before we calculate the custom score make sure they answered the minimum
3505
            // number of questions. We only need to do this for custom scoring as we can
3506
            // not get the miniumum score the user should achieve. If we are not using
3507
            // custom scoring (so all questions are valued as 1) then we simply check if
3508
            // they answered more than the minimum questions, if not, we mark it out of the
3509
            // number specified in the minimum questions setting - which is done in lesson_grade().
3510
            // Get the number of answers given.
3511
            if ($gradeinfo->nquestions < $this->properties->minquestions) {
3512
                $data->gradelesson = false;
3513
                $a = new stdClass;
3514
                $a->nquestions = $gradeinfo->nquestions;
3515
                $a->minquestions = $this->properties->minquestions;
3516
                $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
3517
            }
3518
        }
3519
 
3520
        if (!$canmanage) {
3521
            if ($data->gradelesson) {
3522
                // Store this now before any modifications to pages viewed.
3523
                $progresscompleted = $this->calculate_progress();
3524
 
3525
                // Update the clock / get time information for this user.
3526
                $this->stop_timer();
3527
 
3528
                // Update completion state.
3529
                $completion = new completion_info($course);
3530
                if ($completion->is_enabled($cm) && $this->properties->completionendreached) {
3531
                    $completion->update_state($cm, COMPLETION_COMPLETE);
3532
                }
3533
 
3534
                if ($this->properties->completiontimespent > 0) {
3535
                    $duration = $DB->get_field_sql(
3536
                        "SELECT SUM(lessontime - starttime)
3537
                                       FROM {lesson_timer}
3538
                                      WHERE lessonid = :lessonid
3539
                                        AND userid = :userid",
3540
                        array('userid' => $USER->id, 'lessonid' => $this->properties->id));
3541
                    if (!$duration) {
3542
                        $duration = 0;
3543
                    }
3544
 
3545
                    // If student has not spend enough time in the lesson, display a message.
3546
                    if ($duration < $this->properties->completiontimespent) {
3547
                        $a = new stdClass;
3548
                        $a->timespentraw = $duration;
3549
                        $a->timespent = format_time($duration);
3550
                        $a->timerequiredraw = $this->properties->completiontimespent;
3551
                        $a->timerequired = format_time($this->properties->completiontimespent);
3552
                        $data->notenoughtimespent = $a;
3553
                    }
3554
                }
3555
 
3556
                if ($gradeinfo->attempts) {
3557
                    if (!$this->properties->custom) {
3558
                        $data->numberofpagesviewed = $gradeinfo->nquestions;
3559
                        if ($this->properties->minquestions) {
3560
                            if ($gradeinfo->nquestions < $this->properties->minquestions) {
3561
                                $data->youshouldview = $this->properties->minquestions;
3562
                            }
3563
                        }
3564
                        $data->numberofcorrectanswers = $gradeinfo->earned;
3565
                    }
3566
                    $a = new stdClass;
3567
                    $a->score = $gradeinfo->earned;
3568
                    $a->grade = $gradeinfo->total;
3569
                    if ($gradeinfo->nmanual) {
3570
                        $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
3571
                        $a->essayquestions = $gradeinfo->nmanual;
3572
                        $data->displayscorewithessays = $a;
3573
                    } else {
3574
                        $data->displayscorewithoutessays = $a;
3575
                    }
3576
 
3577
                    $grade = new stdClass();
3578
                    $grade->lessonid = $this->properties->id;
3579
                    $grade->userid = $USER->id;
3580
                    $grade->grade = $gradeinfo->grade;
3581
                    $grade->completed = time();
3582
                    if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record.
3583
                        if (!$grades = $DB->get_records("lesson_grades",
3584
                            array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
3585
                            throw new moodle_exception('cannotfindgrade', 'lesson');
3586
                        }
3587
                        $oldgrade = array_shift($grades);
3588
                        $grade->id = $oldgrade->id;
3589
                        $DB->update_record("lesson_grades", $grade);
3590
                    } else {
3591
                        $newgradeid = $DB->insert_record("lesson_grades", $grade);
3592
                    }
3593
 
3594
                    // Update central gradebook.
3595
                    lesson_update_grades($this, $USER->id);
3596
 
3597
                    // Print grade (grade type Point).
3598
                    if ($this->properties->grade > 0) {
3599
                        $a = new stdClass;
3600
                        $a->grade = format_float($gradeinfo->grade * $this->properties->grade / 100, 1);
3601
                        $a->total = $this->properties->grade;
3602
                        $data->yourcurrentgradeisoutof = $a;
3603
                    }
3604
 
3605
                    // Print grade (grade type Scale).
3606
                    if ($this->properties->grade < 0) {
3607
                        // Grade type is Scale.
3608
                        $grades = grade_get_grades($course->id, 'mod', 'lesson', $cm->instance, $USER->id);
3609
                        $grade = reset($grades->items[0]->grades);
3610
                        $data->yourcurrentgradeis = $grade->str_grade;
3611
                    }
3612
                } else {
3613
                    if ($this->properties->timelimit) {
3614
                        if ($outoftime == 'normal') {
3615
                            $grade = new stdClass();
3616
                            $grade->lessonid = $this->properties->id;
3617
                            $grade->userid = $USER->id;
3618
                            $grade->grade = 0;
3619
                            $grade->completed = time();
3620
                            $newgradeid = $DB->insert_record("lesson_grades", $grade);
3621
                            $data->eolstudentoutoftimenoanswers = true;
3622
 
3623
                            // Update central gradebook.
3624
                            lesson_update_grades($this, $USER->id);
3625
                        }
3626
                    } else {
3627
                        $data->welldone = true;
3628
                    }
3629
                }
3630
 
3631
                $data->progresscompleted = $progresscompleted;
3632
            }
3633
        } else {
3634
            // Display for teacher.
3635
            if ($this->properties->grade != GRADE_TYPE_NONE) {
3636
                $data->displayofgrade = true;
3637
            }
3638
        }
3639
 
3640
        if ($this->properties->modattempts && !$canmanage) {
3641
            // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
3642
            // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
3643
            // to pass to view again.  This is slick cause it wont call the empty($pageid) code
3644
            // $ntries is decremented above.
3645
            if (!$attempts = $this->get_attempts($ntries)) {
3646
                $attempts = array();
3647
                $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id));
3648
            } else {
3649
                $firstattempt = current($attempts);
3650
                $pageid = $firstattempt->pageid;
3651
                // If the student wishes to review, need to know the last question page that the student answered.
3652
                // This will help to make sure that the student can leave the lesson via pushing the continue button.
3653
                $lastattempt = end($attempts);
3654
                $USER->modattempts[$this->properties->id] = $lastattempt->pageid;
3655
 
3656
                $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid));
3657
            }
3658
            $data->reviewlesson = $url->out(false);
3659
        } else if ($this->properties->modattempts && $canmanage) {
3660
            $data->modattemptsnoteacher = true;
3661
        }
3662
 
3663
        if ($this->properties->activitylink) {
3664
            $data->activitylink = $this->link_for_activitylink();
3665
        }
3666
        return $data;
3667
    }
3668
 
3669
    /**
3670
     * Returns the last "legal" attempt from the list of student attempts.
3671
     *
3672
     * @param array $attempts The list of student attempts.
3673
     * @return stdClass The updated fom data.
3674
     */
3675
    public function get_last_attempt(array $attempts): stdClass {
3676
        // If there are more tries than the max that is allowed, grab the last "legal" attempt.
3677
        if (!empty($this->maxattempts) && (count($attempts) > $this->maxattempts)) {
3678
            $lastattempt = $attempts[$this->maxattempts - 1];
3679
        } else {
3680
            // Grab the last attempt since there's no limit to the max attempts or the user has made fewer attempts than the max.
3681
            $lastattempt = end($attempts);
3682
        }
3683
        return $lastattempt;
3684
    }
3685
}
3686
 
3687
 
3688
/**
3689
 * Abstract class to provide a core functions to the all lesson classes
3690
 *
3691
 * This class should be abstracted by ALL classes with the lesson module to ensure
3692
 * that all classes within this module can be interacted with in the same way.
3693
 *
3694
 * This class provides the user with a basic properties array that can be fetched
3695
 * or set via magic methods, or alternatively by defining methods get_blah() or
3696
 * set_blah() within the extending object.
3697
 *
3698
 * @copyright  2009 Sam Hemelryk
3699
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3700
 */
3701
abstract class lesson_base {
3702
 
3703
    /**
3704
     * An object containing properties
3705
     * @var stdClass
3706
     */
3707
    protected $properties;
3708
 
3709
    /**
3710
     * The constructor
3711
     * @param stdClass $properties
3712
     */
3713
    public function __construct($properties) {
3714
        $this->properties = (object)$properties;
3715
    }
3716
 
3717
    /**
3718
     * Magic property method
3719
     *
3720
     * Attempts to call a set_$key method if one exists otherwise falls back
3721
     * to simply set the property
3722
     *
3723
     * @param string $key
3724
     * @param mixed $value
3725
     */
3726
    public function __set($key, $value) {
3727
        if (method_exists($this, 'set_'.$key)) {
3728
            $this->{'set_'.$key}($value);
3729
        }
3730
        $this->properties->{$key} = $value;
3731
    }
3732
 
3733
    /**
3734
     * Magic get method
3735
     *
3736
     * Attempts to call a get_$key method to return the property and ralls over
3737
     * to return the raw property
3738
     *
3739
     * @param str $key
3740
     * @return mixed
3741
     */
3742
    public function __get($key) {
3743
        if (method_exists($this, 'get_'.$key)) {
3744
            return $this->{'get_'.$key}();
3745
        }
3746
        return $this->properties->{$key};
3747
    }
3748
 
3749
    /**
3750
     * Stupid PHP needs an isset magic method if you use the get magic method and
3751
     * still want empty calls to work.... blah ~!
3752
     *
3753
     * @param string $key
3754
     * @return bool
3755
     */
3756
    public function __isset($key) {
3757
        if (method_exists($this, 'get_'.$key)) {
3758
            $val = $this->{'get_'.$key}();
3759
            return !empty($val);
3760
        }
3761
        return !empty($this->properties->{$key});
3762
    }
3763
 
3764
    //NOTE: E_STRICT does not allow to change function signature!
3765
 
3766
    /**
3767
     * If implemented should create a new instance, save it in the DB and return it
3768
     */
3769
    //public static function create() {}
3770
    /**
3771
     * If implemented should load an instance from the DB and return it
3772
     */
3773
    //public static function load() {}
3774
    /**
3775
     * Fetches all of the properties of the object
3776
     * @return stdClass
3777
     */
3778
    public function properties() {
3779
        return $this->properties;
3780
    }
3781
}
3782
 
3783
 
3784
/**
3785
 * Abstract class representation of a page associated with a lesson.
3786
 *
3787
 * This class should MUST be extended by all specialised page types defined in
3788
 * mod/lesson/pagetypes/.
3789
 * There are a handful of abstract methods that need to be defined as well as
3790
 * severl methods that can optionally be defined in order to make the page type
3791
 * operate in the desired way
3792
 *
3793
 * Database properties
3794
 * @property int $id The id of this lesson page
3795
 * @property int $lessonid The id of the lesson this page belongs to
3796
 * @property int $prevpageid The id of the page before this one
3797
 * @property int $nextpageid The id of the next page in the page sequence
3798
 * @property int $qtype Identifies the page type of this page
3799
 * @property int $qoption Used to record page type specific options
3800
 * @property int $layout Used to record page specific layout selections
3801
 * @property int $display Used to record page specific display selections
3802
 * @property int $timecreated Timestamp for when the page was created
3803
 * @property int $timemodified Timestamp for when the page was last modified
3804
 * @property string $title The title of this page
3805
 * @property string $contents The rich content shown to describe the page
3806
 * @property int $contentsformat The format of the contents field
3807
 *
3808
 * Calculated properties
3809
 * @property-read array $answers An array of answers for this page
3810
 * @property-read bool $displayinmenublock Toggles display in the left menu block
3811
 * @property-read array $jumps An array containing all the jumps this page uses
3812
 * @property-read lesson $lesson The lesson this page belongs to
3813
 * @property-read int $type The type of the page [question | structure]
3814
 * @property-read typeid The unique identifier for the page type
3815
 * @property-read typestring The string that describes this page type
3816
 *
3817
 * @abstract
3818
 * @copyright  2009 Sam Hemelryk
3819
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3820
 */
3821
abstract class lesson_page extends lesson_base {
3822
 
3823
    /**
3824
     * A reference to the lesson this page belongs to
3825
     * @var lesson
3826
     */
3827
    protected $lesson = null;
3828
    /**
3829
     * Contains the answers to this lesson_page once loaded
3830
     * @var null|array
3831
     */
3832
    protected $answers = null;
3833
    /**
3834
     * This sets the type of the page, can be one of the constants defined below
3835
     * @var int
3836
     */
3837
    protected $type = 0;
3838
 
3839
    /**
3840
     * Constants used to identify the type of the page
3841
     */
3842
    const TYPE_QUESTION = 0;
3843
    const TYPE_STRUCTURE = 1;
3844
 
3845
    /**
3846
     * Constant used as a delimiter when parsing multianswer questions
3847
     */
3848
    const MULTIANSWER_DELIMITER = '@^#|';
3849
 
3850
    /**
3851
     * This method should return the integer used to identify the page type within
3852
     * the database and throughout code. This maps back to the defines used in 1.x
3853
     * @abstract
3854
     * @return int
3855
     */
3856
    abstract protected function get_typeid();
3857
    /**
3858
     * This method should return the string that describes the pagetype
3859
     * @abstract
3860
     * @return string
3861
     */
3862
    abstract protected function get_typestring();
3863
 
3864
    /**
3865
     * This method gets called to display the page to the user taking the lesson
3866
     * @abstract
3867
     * @param object $renderer
3868
     * @param object $attempt
3869
     * @return string
3870
     */
3871
    abstract public function display($renderer, $attempt);
3872
 
3873
    /**
3874
     * Creates a new lesson_page within the database and returns the correct pagetype
3875
     * object to use to interact with the new lesson
3876
     *
3877
     * @final
3878
     * @static
3879
     * @param object $properties
3880
     * @param lesson $lesson
3881
     * @return lesson_page Specialised object that extends lesson_page
3882
     */
3883
    final public static function create($properties, lesson $lesson, $context, $maxbytes) {
3884
        global $DB;
3885
        $newpage = new stdClass;
3886
        $newpage->title = $properties->title;
3887
        $newpage->contents = $properties->contents_editor['text'];
3888
        $newpage->contentsformat = $properties->contents_editor['format'];
3889
        $newpage->lessonid = $lesson->id;
3890
        $newpage->timecreated = time();
3891
        $newpage->qtype = $properties->qtype;
3892
        $newpage->qoption = (isset($properties->qoption))?1:0;
3893
        $newpage->layout = (isset($properties->layout))?1:0;
3894
        $newpage->display = (isset($properties->display))?1:0;
3895
        $newpage->prevpageid = 0; // this is a first page
3896
        $newpage->nextpageid = 0; // this is the only page
3897
 
3898
        if ($properties->pageid) {
3899
            $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
3900
            if (!$prevpage) {
3901
                throw new \moodle_exception('cannotfindpages', 'lesson');
3902
            }
3903
            $newpage->prevpageid = $prevpage->id;
3904
            $newpage->nextpageid = $prevpage->nextpageid;
3905
        } else {
3906
            $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
3907
            if ($nextpage) {
3908
                // This is the first page, there are existing pages put this at the start
3909
                $newpage->nextpageid = $nextpage->id;
3910
            }
3911
        }
3912
 
3913
        $newpage->id = $DB->insert_record("lesson_pages", $newpage);
3914
 
3915
        $editor = new stdClass;
3916
        $editor->id = $newpage->id;
3917
        $editor->contents_editor = $properties->contents_editor;
3918
        $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
3919
        $DB->update_record("lesson_pages", $editor);
3920
 
3921
        if ($newpage->prevpageid > 0) {
3922
            $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
3923
        }
3924
        if ($newpage->nextpageid > 0) {
3925
            $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
3926
        }
3927
 
3928
        $page = lesson_page::load($newpage, $lesson);
3929
        $page->create_answers($properties);
3930
 
3931
        // Trigger an event: page created.
3932
        $eventparams = array(
3933
            'context' => $context,
3934
            'objectid' => $newpage->id,
3935
            'other' => array(
3936
                'pagetype' => $page->get_typestring()
3937
                )
3938
            );
3939
        $event = \mod_lesson\event\page_created::create($eventparams);
3940
        $snapshot = clone($newpage);
3941
        $snapshot->timemodified = 0;
3942
        $event->add_record_snapshot('lesson_pages', $snapshot);
3943
        $event->trigger();
3944
 
3945
        $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
3946
 
3947
        return $page;
3948
    }
3949
 
3950
    /**
3951
     * This method loads a page object from the database and returns it as a
3952
     * specialised object that extends lesson_page
3953
     *
3954
     * @final
3955
     * @static
3956
     * @param int $id
3957
     * @param lesson $lesson
3958
     * @return lesson_page Specialised lesson_page object
3959
     */
3960
    final public static function load($id, lesson $lesson) {
3961
        global $DB;
3962
 
3963
        if (is_object($id) && !empty($id->qtype)) {
3964
            $page = $id;
3965
        } else {
3966
            $page = $DB->get_record("lesson_pages", array("id" => $id));
3967
            if (!$page) {
3968
                throw new \moodle_exception('cannotfindpages', 'lesson');
3969
            }
3970
        }
3971
        $manager = lesson_page_type_manager::get($lesson);
3972
 
3973
        $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
3974
        if (!class_exists($class)) {
3975
            $class = 'lesson_page';
3976
        }
3977
 
3978
        return new $class($page, $lesson);
3979
    }
3980
 
3981
    /**
3982
     * Deletes a lesson_page from the database as well as any associated records.
3983
     * @final
3984
     * @return bool
3985
     */
3986
    final public function delete() {
3987
        global $DB;
3988
 
3989
        $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3990
        $context = context_module::instance($cm->id);
3991
 
3992
        // Delete files associated with attempts.
3993
        $fs = get_file_storage();
3994
        if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
3995
            foreach ($attempts as $attempt) {
3996
                $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
3997
                $fs->delete_area_files($context->id, 'mod_lesson', 'essay_answers', $attempt->id);
3998
            }
3999
        }
4000
 
4001
        // Then delete all the associated records...
4002
        $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
4003
 
4004
        $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
4005
 
4006
        // Delete files related to answers and responses.
4007
        if ($answers = $DB->get_records("lesson_answers", array("pageid" => $this->properties->id))) {
4008
            foreach ($answers as $answer) {
4009
                $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $answer->id);
4010
                $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $answer->id);
4011
            }
4012
        }
4013
 
4014
        // ...now delete the answers...
4015
        $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
4016
        // ..and the page itself
4017
        $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
4018
 
4019
        // Trigger an event: page deleted.
4020
        $eventparams = array(
4021
            'context' => $context,
4022
            'objectid' => $this->properties->id,
4023
            'other' => array(
4024
                'pagetype' => $this->get_typestring()
4025
                )
4026
            );
4027
        $event = \mod_lesson\event\page_deleted::create($eventparams);
4028
        $event->add_record_snapshot('lesson_pages', $this->properties);
4029
        $event->trigger();
4030
 
4031
        // Delete files associated with this page.
4032
        $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
4033
 
4034
        // repair the hole in the linkage
4035
        if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
4036
            //This is the only page, no repair needed
4037
        } elseif (!$this->properties->prevpageid) {
4038
            // this is the first page...
4039
            $page = $this->lesson->load_page($this->properties->nextpageid);
4040
            $page->move(null, 0);
4041
        } elseif (!$this->properties->nextpageid) {
4042
            // this is the last page...
4043
            $page = $this->lesson->load_page($this->properties->prevpageid);
4044
            $page->move(0);
4045
        } else {
4046
            // page is in the middle...
4047
            $prevpage = $this->lesson->load_page($this->properties->prevpageid);
4048
            $nextpage = $this->lesson->load_page($this->properties->nextpageid);
4049
 
4050
            $prevpage->move($nextpage->id);
4051
            $nextpage->move(null, $prevpage->id);
4052
        }
4053
        return true;
4054
    }
4055
 
4056
    /**
4057
     * Moves a page by updating its nextpageid and prevpageid values within
4058
     * the database
4059
     *
4060
     * @final
4061
     * @param int $nextpageid
4062
     * @param int $prevpageid
4063
     */
4064
    final public function move($nextpageid=null, $prevpageid=null) {
4065
        global $DB;
4066
        if ($nextpageid === null) {
4067
            $nextpageid = $this->properties->nextpageid;
4068
        }
4069
        if ($prevpageid === null) {
4070
            $prevpageid = $this->properties->prevpageid;
4071
        }
4072
        $obj = new stdClass;
4073
        $obj->id = $this->properties->id;
4074
        $obj->prevpageid = $prevpageid;
4075
        $obj->nextpageid = $nextpageid;
4076
        $DB->update_record('lesson_pages', $obj);
4077
    }
4078
 
4079
    /**
4080
     * Returns the answers that are associated with this page in the database
4081
     *
4082
     * @final
4083
     * @return array
4084
     */
4085
    final public function get_answers() {
4086
        global $DB;
4087
        if ($this->answers === null) {
4088
            $this->answers = array();
4089
            $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
4090
            if (!$answers) {
4091
                // It is possible that a lesson upgraded from Moodle 1.9 still
4092
                // contains questions without any answers [MDL-25632].
4093
                // debugging(get_string('cannotfindanswer', 'lesson'));
4094
                return array();
4095
            }
4096
            foreach ($answers as $answer) {
4097
                $this->answers[count($this->answers)] = new lesson_page_answer($answer);
4098
            }
4099
        }
4100
        return $this->answers;
4101
    }
4102
 
4103
    /**
4104
     * Returns the lesson this page is associated with
4105
     * @final
4106
     * @return lesson
4107
     */
4108
    final protected function get_lesson() {
4109
        return $this->lesson;
4110
    }
4111
 
4112
    /**
4113
     * Returns the type of page this is. Not to be confused with page type
4114
     * @final
4115
     * @return int
4116
     */
4117
    final protected function get_type() {
4118
        return $this->type;
4119
    }
4120
 
4121
    /**
4122
     * Records an attempt at this page
4123
     *
4124
     * @final
4125
     * @global moodle_database $DB
4126
     * @param stdClass $context
4127
     * @return stdClass Returns the result of the attempt
4128
     */
4129
    final public function record_attempt($context) {
4130
        global $DB, $USER, $OUTPUT, $PAGE;
4131
 
4132
        /**
4133
         * This should be overridden by each page type to actually check the response
4134
         * against what ever custom criteria they have defined
4135
         */
4136
        $result = $this->check_answer();
4137
 
4138
        // Processes inmediate jumps.
4139
        if ($result->inmediatejump) {
4140
            return $result;
4141
        }
4142
 
4143
        $result->attemptsremaining  = 0;
4144
        $result->maxattemptsreached = false;
4145
 
4146
        if ($result->noanswer) {
4147
            $result->newpageid = $this->properties->id; // display same page again
4148
            $result->feedback  = get_string('noanswer', 'lesson');
4149
        } else {
4150
            if (!has_capability('mod/lesson:manage', $context)) {
4151
                $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4152
 
4153
                // Get the number of attempts that have been made on this question for this student and retake,
4154
                $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
4155
                    'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
4156
 
4157
                // Check if they have reached (or exceeded) the maximum number of attempts allowed.
4158
                if (!empty($this->lesson->maxattempts) && $nattempts >= $this->lesson->maxattempts) {
4159
                    $result->maxattemptsreached = true;
4160
                    $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
4161
                    $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
4162
                    return $result;
4163
                }
4164
 
4165
                // record student's attempt
4166
                $attempt = new stdClass;
4167
                $attempt->lessonid = $this->lesson->id;
4168
                $attempt->pageid = $this->properties->id;
4169
                $attempt->userid = $USER->id;
4170
                $attempt->answerid = $result->answerid;
4171
                $attempt->retry = $nretakes;
4172
                $attempt->correct = $result->correctanswer;
4173
                if($result->userresponse !== null) {
4174
                    $attempt->useranswer = $result->userresponse;
4175
                }
4176
 
4177
                $attempt->timeseen = time();
4178
                // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
4179
                $userisreviewing = false;
4180
                if (isset($USER->modattempts[$this->lesson->id])) {
4181
                    $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
4182
                    $userisreviewing = true;
4183
                }
4184
 
4185
                // Only insert a record if we are not reviewing the lesson.
4186
                if (!$userisreviewing) {
4187
                    if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
4188
                        $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
4189
 
4190
                        list($updatedattempt, $updatedresult) = $this->on_after_write_attempt($attempt, $result);
4191
                        if ($updatedattempt) {
4192
                            $attempt = $updatedattempt;
4193
                            $result = $updatedresult;
4194
                            $DB->update_record("lesson_attempts", $attempt);
4195
                        }
4196
 
4197
                        // Trigger an event: question answered.
4198
                        $eventparams = array(
4199
                            'context' => context_module::instance($PAGE->cm->id),
4200
                            'objectid' => $this->properties->id,
4201
                            'other' => array(
4202
                                'pagetype' => $this->get_typestring()
4203
                                )
4204
                            );
4205
                        $event = \mod_lesson\event\question_answered::create($eventparams);
4206
                        $event->add_record_snapshot('lesson_attempts', $attempt);
4207
                        $event->trigger();
4208
 
4209
                        // Increase the number of attempts made.
4210
                        $nattempts++;
4211
                    }
4212
                } else {
4213
                    // When reviewing the lesson, the existing attemptid is also needed for the filearea options.
4214
                    $params = [
4215
                        'lessonid' => $attempt->lessonid,
4216
                        'pageid' => $attempt->pageid,
4217
                        'userid' => $attempt->userid,
4218
                        'answerid' => $attempt->answerid,
4219
                        'retry' => $attempt->retry
4220
                    ];
4221
                    $attempt->id = $DB->get_field('lesson_attempts', 'id', $params);
4222
                }
4223
                // "number of attempts remaining" message if $this->lesson->maxattempts > 1
4224
                // displaying of message(s) is at the end of page for more ergonomic display
4225
                // If we are showing the number of remaining attempts, we need to show it regardless of what the next
4226
                // jump to page is.
4227
                if (!$result->correctanswer) {
4228
                    // Retrieve the number of attempts left counter for displaying at bottom of feedback page.
4229
                    if ($result->newpageid == 0 && !empty($this->lesson->maxattempts) && $nattempts >= $this->lesson->maxattempts) {
4230
                        if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4231
                            $result->maxattemptsreached = true;
4232
                        }
4233
                        $result->newpageid = LESSON_NEXTPAGE;
4234
                    } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
4235
                        $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
4236
                        if ($result->attemptsremaining == 0) {
4237
                            $result->maxattemptsreached = true;
4238
                        }
4239
                    }
4240
                }
4241
            }
4242
 
4243
            // Determine default feedback if necessary
4244
            if (empty($result->response)) {
4245
                if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
4246
                    // These conditions have been met:
4247
                    //  1. The lesson manager has not supplied feedback to the student
4248
                    //  2. Not displaying default feedback
4249
                    //  3. The user did provide an answer
4250
                    //  4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
4251
 
4252
                    $result->nodefaultresponse = true;  // This will cause a redirect below
4253
                } else if ($result->isessayquestion) {
4254
                    $result->response = get_string('defaultessayresponse', 'lesson');
4255
                } else if ($result->correctanswer) {
4256
                    $result->response = get_string('thatsthecorrectanswer', 'lesson');
4257
                } else {
4258
                    $result->response = get_string('thatsthewronganswer', 'lesson');
4259
                }
4260
            }
4261
 
4262
            if ($result->response) {
4263
                if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
4264
                    $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
4265
                    $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
4266
                    if ($qattempts == 1) {
4267
                        $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
4268
                    } else {
4269
                        if (!$result->maxattemptsreached) {
4270
                            $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
4271
                        } else {
4272
                            $result->feedback = $OUTPUT->box(get_string("finalwrong", "lesson"), 'feedback');
4273
                        }
4274
                    }
4275
                } else {
4276
                    $result->feedback = '';
4277
                }
4278
                $class = 'response';
4279
                if ($result->correctanswer) {
4280
                    $class .= ' correct'; // CSS over-ride this if they exist (!important).
4281
                } else if (!$result->isessayquestion) {
4282
                    $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
4283
                }
4284
 
4285
                $options = [
4286
                    'noclean' =>  true,
4287
                    'para' =>  true,
4288
                    'overflowdiv' =>  true,
4289
                    'context' =>  $context,
4290
                ];
4291
                $answeroptions = (object) array_merge($options, [
4292
                    'attemptid' => $attempt->id ?? null,
4293
                ]);
4294
 
4295
                $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
4296
                        'generalbox boxaligncenter py-3');
4297
                $result->feedback .= '<div class="correctanswer generalbox"><em>'
4298
                        . get_string("youranswer", "lesson").'</em> : <div class="studentanswer mt-2 mb-2">';
4299
 
4300
                // Create a table containing the answers and responses.
4301
                $table = new html_table();
4302
                // Multianswer allowed.
4303
                if ($this->properties->qoption) {
4304
                    $studentanswerarray = explode(self::MULTIANSWER_DELIMITER, $result->studentanswer);
4305
                    $responsearr = explode(self::MULTIANSWER_DELIMITER, $result->response);
4306
                    $studentanswerresponse = array_combine($studentanswerarray, $responsearr);
4307
 
4308
                    foreach ($studentanswerresponse as $answer => $response) {
4309
                        // Add a table row containing the answer.
4310
                        $studentanswer = $this->format_answer($answer, $context, $result->studentanswerformat, $answeroptions);
4311
                        $table->data[] = array($studentanswer);
4312
                        // If the response exists, add a table row containing the response. If not, add en empty row.
4313
                        if (!empty(trim($response))) {
4314
                            $studentresponse = isset($result->responseformat) ?
4315
                                $this->format_response($response, $context, $result->responseformat, $options) : $response;
4316
                            $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") .
4317
                                '</em>: <br/>' . $studentresponse, $class);
4318
                            $table->data[] = array($studentresponsecontent);
4319
                        } else {
4320
                            $table->data[] = array('');
4321
                        }
4322
                    }
4323
                } else {
4324
                    // Add a table row containing the answer.
4325
                    $studentanswer = $this->format_answer($result->studentanswer, $context, $result->studentanswerformat, $answeroptions);
4326
                    $table->data[] = array($studentanswer);
4327
                    // If the response exists, add a table row containing the response. If not, add en empty row.
4328
                    if (!empty(trim($result->response))) {
4329
                        $studentresponse = isset($result->responseformat) ?
4330
                            $this->format_response($result->response, $context, $result->responseformat,
4331
                                $result->answerid, $options) : $result->response;
4332
                        $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") .
4333
                            '</em>: <br/>' . $studentresponse, $class);
4334
                        $table->data[] = array($studentresponsecontent);
4335
                    } else {
4336
                        $table->data[] = array('');
4337
                    }
4338
                }
4339
 
4340
                $result->feedback .= html_writer::table($table).'</div></div>';
4341
            }
4342
        }
4343
        return $result;
4344
    }
4345
 
4346
    /**
4347
     * Formats the answer. Override for custom formatting.
4348
     *
4349
     * @param string $answer
4350
     * @param context $context
4351
     * @param int $answerformat
4352
     * @return string Returns formatted string
4353
     */
4354
    public function format_answer($answer, $context, $answerformat, $options = []) {
4355
        if (is_object($options)) {
4356
            $options = (array) $options;
4357
        }
4358
 
4359
        if (empty($options['context'])) {
4360
            $options['context'] = $context;
4361
        }
4362
 
4363
        if (empty($options['para'])) {
4364
            $options['para'] = true;
4365
        }
4366
 
4367
        // The attemptid is used by some plugins but is not a valid argument to format_text.
4368
        unset($options['attemptid']);
4369
 
4370
        return format_text($answer, $answerformat, $options);
4371
    }
4372
 
4373
    /**
4374
     * Formats the response
4375
     *
4376
     * @param string $response
4377
     * @param context $context
4378
     * @param int $responseformat
4379
     * @param int $answerid
4380
     * @param stdClass $options
4381
     * @return string Returns formatted string
4382
     */
4383
    private function format_response($response, $context, $responseformat, $answerid, $options) {
4384
 
4385
        $convertstudentresponse = file_rewrite_pluginfile_urls($response, 'pluginfile.php',
4386
            $context->id, 'mod_lesson', 'page_responses', $answerid);
4387
 
4388
        return format_text($convertstudentresponse, $responseformat, $options);
4389
    }
4390
 
4391
    /**
4392
     * Returns the string for a jump name
4393
     *
4394
     * @final
4395
     * @param int $jumpto Jump code or page ID
4396
     * @return string
4397
     **/
4398
    final protected function get_jump_name($jumpto) {
4399
        global $DB;
4400
        static $jumpnames = array();
4401
 
4402
        if (!array_key_exists($jumpto, $jumpnames)) {
4403
            if ($jumpto == LESSON_THISPAGE) {
4404
                $jumptitle = get_string('thispage', 'lesson');
4405
            } elseif ($jumpto == LESSON_NEXTPAGE) {
4406
                $jumptitle = get_string('nextpage', 'lesson');
4407
            } elseif ($jumpto == LESSON_EOL) {
4408
                $jumptitle = get_string('endoflesson', 'lesson');
4409
            } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
4410
                $jumptitle = get_string('unseenpageinbranch', 'lesson');
4411
            } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
4412
                $jumptitle = get_string('previouspage', 'lesson');
4413
            } elseif ($jumpto == LESSON_RANDOMPAGE) {
4414
                $jumptitle = get_string('randompageinbranch', 'lesson');
4415
            } elseif ($jumpto == LESSON_RANDOMBRANCH) {
4416
                $jumptitle = get_string('randombranch', 'lesson');
4417
            } elseif ($jumpto == LESSON_CLUSTERJUMP) {
4418
                $jumptitle = get_string('clusterjump', 'lesson');
4419
            } else {
4420
                if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
4421
                    $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
4422
                }
4423
            }
4424
            $jumpnames[$jumpto] = format_string($jumptitle,true);
4425
        }
4426
 
4427
        return $jumpnames[$jumpto];
4428
    }
4429
 
4430
    /**
4431
     * Constructor method
4432
     * @param object $properties
4433
     * @param lesson $lesson
4434
     */
4435
    public function __construct($properties, lesson $lesson) {
4436
        parent::__construct($properties);
4437
        $this->lesson = $lesson;
4438
    }
4439
 
4440
    /**
4441
     * Returns the score for the attempt
4442
     * This may be overridden by page types that require manual grading
4443
     * @param array $answers
4444
     * @param object $attempt
4445
     * @return int
4446
     */
4447
    public function earned_score($answers, $attempt) {
4448
        return $answers[$attempt->answerid]->score;
4449
    }
4450
 
4451
    /**
4452
     * This is a callback method that can be override and gets called when ever a page
4453
     * is viewed
4454
     *
4455
     * @param bool $canmanage True if the user has the manage cap
4456
     * @param bool $redirect  Optional, default to true. Set to false to avoid redirection and return the page to redirect.
4457
     * @return mixed
4458
     */
4459
    public function callback_on_view($canmanage, $redirect = true) {
4460
        return true;
4461
    }
4462
 
4463
    /**
4464
     * save editor answers files and update answer record
4465
     *
4466
     * @param object $context
4467
     * @param int $maxbytes
4468
     * @param object $answer
4469
     * @param object $answereditor
4470
     * @param object $responseeditor
4471
     */
4472
    public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
4473
        global $DB;
4474
        if (isset($answereditor['itemid'])) {
4475
            $answer->answer = file_save_draft_area_files($answereditor['itemid'],
4476
                    $context->id, 'mod_lesson', 'page_answers', $answer->id,
4477
                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4478
                    $answer->answer, null);
4479
            $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
4480
        }
4481
        if (isset($responseeditor['itemid'])) {
4482
            $answer->response = file_save_draft_area_files($responseeditor['itemid'],
4483
                    $context->id, 'mod_lesson', 'page_responses', $answer->id,
4484
                    array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
4485
                    $answer->response, null);
4486
            $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
4487
        }
4488
    }
4489
 
4490
    /**
4491
     * Rewrite urls in response and optionality answer of a question answer
4492
     *
4493
     * @param object $answer
4494
     * @param bool $rewriteanswer must rewrite answer
4495
     * @return object answer with rewritten urls
4496
     */
4497
    public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
4498
        global $PAGE;
4499
 
4500
        $context = context_module::instance($PAGE->cm->id);
4501
        if ($rewriteanswer) {
4502
            $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
4503
                    'mod_lesson', 'page_answers', $answer->id);
4504
        }
4505
        $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
4506
                'mod_lesson', 'page_responses', $answer->id);
4507
 
4508
        return $answer;
4509
    }
4510
 
4511
    /**
4512
     * Updates a lesson page and its answers within the database
4513
     *
4514
     * @param object $properties
4515
     * @return bool
4516
     */
4517
    public function update($properties, $context = null, $maxbytes = null) {
4518
        global $DB, $PAGE;
4519
        $answers  = $this->get_answers();
4520
        $properties->id = $this->properties->id;
4521
        $properties->lessonid = $this->lesson->id;
4522
        if (empty($properties->qoption)) {
4523
            $properties->qoption = '0';
4524
        }
4525
        if (empty($context)) {
4526
            $context = $PAGE->context;
4527
        }
4528
        if ($maxbytes === null) {
4529
            $maxbytes = get_user_max_upload_file_size($context);
4530
        }
4531
        $properties->timemodified = time();
4532
        $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
4533
        $DB->update_record("lesson_pages", $properties);
4534
 
4535
        // Trigger an event: page updated.
4536
        \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
4537
 
4538
        if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
4539
            // These page types have only one answer to save the jump and score.
4540
            if (count($answers) > 1) {
4541
                $answer = array_shift($answers);
4542
                foreach ($answers as $a) {
4543
                    $DB->delete_records('lesson_answers', array('id' => $a->id));
4544
                }
4545
            } else if (count($answers) == 1) {
4546
                $answer = array_shift($answers);
4547
            } else {
4548
                $answer = new stdClass;
4549
                $answer->lessonid = $properties->lessonid;
4550
                $answer->pageid = $properties->id;
4551
                $answer->timecreated = time();
4552
            }
4553
 
4554
            $answer->timemodified = time();
4555
            if (isset($properties->jumpto[0])) {
4556
                $answer->jumpto = $properties->jumpto[0];
4557
            }
4558
            if (isset($properties->score[0])) {
4559
                $answer->score = $properties->score[0];
4560
            }
4561
            if (!empty($answer->id)) {
4562
                $DB->update_record("lesson_answers", $answer->properties());
4563
            } else {
4564
                $DB->insert_record("lesson_answers", $answer);
4565
            }
4566
        } else {
4567
            for ($i = 0; $i < count($properties->answer_editor); $i++) {
4568
                if (!array_key_exists($i, $this->answers)) {
4569
                    $this->answers[$i] = new stdClass;
4570
                    $this->answers[$i]->lessonid = $this->lesson->id;
4571
                    $this->answers[$i]->pageid = $this->id;
4572
                    $this->answers[$i]->timecreated = $this->timecreated;
4573
                    $this->answers[$i]->answer = null;
4574
                }
4575
 
4576
                if (isset($properties->answer_editor[$i])) {
4577
                    if (is_array($properties->answer_editor[$i])) {
4578
                        // Multichoice and true/false pages have an HTML editor.
4579
                        $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
4580
                        $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
4581
                    } else {
4582
                        // Branch tables, shortanswer and mumerical pages have only a text field.
4583
                        $this->answers[$i]->answer = $properties->answer_editor[$i];
4584
                        $this->answers[$i]->answerformat = FORMAT_MOODLE;
4585
                    }
4586
                } else {
4587
                    // If there is no data posted which means we want to reset the stored values.
4588
                    $this->answers[$i]->answer = null;
4589
                }
4590
 
4591
                if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4592
                    $this->answers[$i]->response = $properties->response_editor[$i]['text'];
4593
                    $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
4594
                }
4595
 
4596
                if ($this->answers[$i]->answer !== null && $this->answers[$i]->answer !== '') {
4597
                    if (isset($properties->jumpto[$i])) {
4598
                        $this->answers[$i]->jumpto = $properties->jumpto[$i];
4599
                    }
4600
                    if ($this->lesson->custom && isset($properties->score[$i])) {
4601
                        $this->answers[$i]->score = $properties->score[$i];
4602
                    }
4603
                    if (!isset($this->answers[$i]->id)) {
4604
                        $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
4605
                    } else {
4606
                        $DB->update_record("lesson_answers", $this->answers[$i]->properties());
4607
                    }
4608
 
4609
                    // Save files in answers and responses.
4610
                    if (isset($properties->response_editor[$i])) {
4611
                        $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4612
                                $properties->answer_editor[$i], $properties->response_editor[$i]);
4613
                    } else {
4614
                        $this->save_answers_files($context, $maxbytes, $this->answers[$i],
4615
                                $properties->answer_editor[$i]);
4616
                    }
4617
 
4618
                } else if (isset($this->answers[$i]->id)) {
4619
                    $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
4620
                    unset($this->answers[$i]);
4621
                }
4622
            }
4623
        }
4624
        return true;
4625
    }
4626
 
4627
    /**
4628
     * Can be set to true if the page requires a static link to create a new instance
4629
     * instead of simply being included in the dropdown
4630
     * @param int $previd
4631
     * @return bool
4632
     */
4633
    public function add_page_link($previd) {
4634
        return false;
4635
    }
4636
 
4637
    /**
4638
     * Returns true if a page has been viewed before
4639
     *
4640
     * @param array|int $param Either an array of pages that have been seen or the
4641
     *                   number of retakes a user has had
4642
     * @return bool
4643
     */
4644
    public function is_unseen($param) {
4645
        global $USER, $DB;
4646
        if (is_array($param)) {
4647
            $seenpages = $param;
4648
            return (!array_key_exists($this->properties->id, $seenpages));
4649
        } else {
4650
            $nretakes = $param;
4651
            if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
4652
                return true;
4653
            }
4654
        }
4655
        return false;
4656
    }
4657
 
4658
    /**
4659
     * Checks to see if a page has been answered previously
4660
     * @param int $nretakes
4661
     * @return bool
4662
     */
4663
    public function is_unanswered($nretakes) {
4664
        global $DB, $USER;
4665
        if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
4666
            return true;
4667
        }
4668
        return false;
4669
    }
4670
 
4671
    /**
4672
     * Creates answers within the database for this lesson_page. Usually only ever
4673
     * called when creating a new page instance
4674
     * @param object $properties
4675
     * @return array
4676
     */
4677
    public function create_answers($properties) {
4678
        global $DB, $PAGE;
4679
        // now add the answers
4680
        $newanswer = new stdClass;
4681
        $newanswer->lessonid = $this->lesson->id;
4682
        $newanswer->pageid = $this->properties->id;
4683
        $newanswer->timecreated = $this->properties->timecreated;
4684
 
4685
        $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
4686
        $context = context_module::instance($cm->id);
4687
 
4688
        $answers = array();
4689
 
4690
        for ($i = 0; $i < ($this->lesson->maxanswers + 1); $i++) {
4691
            $answer = clone($newanswer);
4692
 
4693
            if (isset($properties->answer_editor[$i])) {
4694
                if (is_array($properties->answer_editor[$i])) {
4695
                    // Multichoice and true/false pages have an HTML editor.
4696
                    $answer->answer = $properties->answer_editor[$i]['text'];
4697
                    $answer->answerformat = $properties->answer_editor[$i]['format'];
4698
                } else {
4699
                    // Branch tables, shortanswer and mumerical pages have only a text field.
4700
                    $answer->answer = $properties->answer_editor[$i];
4701
                    $answer->answerformat = FORMAT_MOODLE;
4702
                }
4703
            }
4704
            if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
4705
                $answer->response = $properties->response_editor[$i]['text'];
4706
                $answer->responseformat = $properties->response_editor[$i]['format'];
4707
            }
4708
 
4709
            if (isset($answer->answer) && $answer->answer != '') {
4710
                if (isset($properties->jumpto[$i])) {
4711
                    $answer->jumpto = $properties->jumpto[$i];
4712
                }
4713
                if ($this->lesson->custom && isset($properties->score[$i])) {
4714
                    $answer->score = $properties->score[$i];
4715
                }
4716
                $answer->id = $DB->insert_record("lesson_answers", $answer);
4717
                if (isset($properties->response_editor[$i])) {
4718
                    $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4719
                            $properties->answer_editor[$i], $properties->response_editor[$i]);
4720
                } else {
4721
                    $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
4722
                            $properties->answer_editor[$i]);
4723
                }
4724
                $answers[$answer->id] = new lesson_page_answer($answer);
4725
            }
4726
        }
4727
 
4728
        $this->answers = $answers;
4729
        return $answers;
4730
    }
4731
 
4732
    /**
4733
     * This method MUST be overridden by all question page types, or page types that
4734
     * wish to score a page.
4735
     *
4736
     * The structure of result should always be the same so it is a good idea when
4737
     * overriding this method on a page type to call
4738
     * <code>
4739
     * $result = parent::check_answer();
4740
     * </code>
4741
     * before modifying it as required.
4742
     *
4743
     * @return stdClass
4744
     */
4745
    public function check_answer() {
4746
        $result = new stdClass;
4747
        $result->answerid        = 0;
4748
        $result->noanswer        = false;
4749
        $result->correctanswer   = false;
4750
        $result->isessayquestion = false;   // use this to turn off review button on essay questions
4751
        $result->response        = '';
4752
        $result->newpageid       = 0;       // stay on the page
4753
        $result->studentanswer   = '';      // use this to store student's answer(s) in order to display it on feedback page
4754
        $result->studentanswerformat = FORMAT_MOODLE;
4755
        $result->userresponse    = null;
4756
        $result->feedback        = '';
4757
        // Store data that was POSTd by a form. This is currently used to perform any logic after the 1st write to the db
4758
        // of the attempt.
4759
        $result->postdata        = false;
4760
        $result->nodefaultresponse  = false; // Flag for redirecting when default feedback is turned off
4761
        $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing.
4762
        return $result;
4763
    }
4764
 
4765
    /**
4766
     * Do any post persistence processing logic of an attempt. E.g. in cases where we need update file urls in an editor
4767
     * and we need to have the id of the stored attempt. Should be overridden in each individual child
4768
     * pagetype on a as required basis
4769
     *
4770
     * @param object $attempt The attempt corresponding to the db record
4771
     * @param object $result The result from the 'check_answer' method
4772
     * @return array False if nothing to be modified, updated $attempt and $result if update required.
4773
     */
4774
    public function on_after_write_attempt($attempt, $result) {
4775
        return [false, false];
4776
    }
4777
 
4778
    /**
4779
     * True if the page uses a custom option
4780
     *
4781
     * Should be override and set to true if the page uses a custom option.
4782
     *
4783
     * @return bool
4784
     */
4785
    public function has_option() {
4786
        return false;
4787
    }
4788
 
4789
    /**
4790
     * Returns the maximum number of answers for this page given the maximum number
4791
     * of answers permitted by the lesson.
4792
     *
4793
     * @param int $default
4794
     * @return int
4795
     */
4796
    public function max_answers($default) {
4797
        return $default;
4798
    }
4799
 
4800
    /**
4801
     * Returns the properties of this lesson page as an object
4802
     * @return stdClass;
4803
     */
4804
    public function properties() {
4805
        $properties = clone($this->properties);
4806
        if ($this->answers === null) {
4807
            $this->get_answers();
4808
        }
4809
        if (count($this->answers)>0) {
4810
            $count = 0;
4811
            $qtype = $properties->qtype;
4812
            foreach ($this->answers as $answer) {
4813
                $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
4814
                if ($qtype != LESSON_PAGE_MATCHING) {
4815
                    $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
4816
                } else {
4817
                    $properties->{'response_editor['.$count.']'} = $answer->response;
4818
                }
4819
                $properties->{'jumpto['.$count.']'} = $answer->jumpto;
4820
                $properties->{'score['.$count.']'} = $answer->score;
4821
                $count++;
4822
            }
4823
        }
4824
        return $properties;
4825
    }
4826
 
4827
    /**
4828
     * Returns an array of options to display when choosing the jumpto for a page/answer
4829
     * @static
4830
     * @param int $pageid
4831
     * @param lesson $lesson
4832
     * @return array
4833
     */
4834
    public static function get_jumptooptions($pageid, lesson $lesson) {
4835
        global $DB;
4836
        $jump = array();
4837
        $jump[0] = get_string("thispage", "lesson");
4838
        $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
4839
        $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
4840
        $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
4841
 
4842
        if ($pageid == 0) {
4843
            return $jump;
4844
        }
4845
 
4846
        $pages = $lesson->load_all_pages();
4847
        if ($pages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))) {
4848
            $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
4849
            $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
4850
        }
4851
        if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
4852
            $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
4853
        }
4854
        if (!optional_param('firstpage', 0, PARAM_INT)) {
4855
            $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
4856
            while (true) {
4857
                if ($apageid) {
4858
                    $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
4859
                    $jump[$apageid] = strip_tags(format_string($title,true));
4860
                    $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
4861
                } else {
4862
                    // last page reached
4863
                    break;
4864
                }
4865
            }
4866
        }
4867
        return $jump;
4868
    }
4869
    /**
4870
     * Returns the contents field for the page properly formatted and with plugin
4871
     * file url's converted
4872
     * @return string
4873
     */
4874
    public function get_contents() {
4875
        global $PAGE;
4876
        if (!empty($this->properties->contents)) {
4877
            if (!isset($this->properties->contentsformat)) {
4878
                $this->properties->contentsformat = FORMAT_HTML;
4879
            }
4880
            $context = context_module::instance($PAGE->cm->id);
4881
            $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
4882
                                                     'page_contents', $this->properties->id);  // Must do this BEFORE format_text()!
4883
            return format_text($contents, $this->properties->contentsformat,
4884
                               array('context' => $context, 'noclean' => true,
4885
                                     'overflowdiv' => true));  // Page edit is marked with XSS, we want all content here.
4886
        } else {
4887
            return '';
4888
        }
4889
    }
4890
 
4891
    /**
4892
     * Set to true if this page should display in the menu block
4893
     * @return bool
4894
     */
4895
    protected function get_displayinmenublock() {
4896
        return false;
4897
    }
4898
 
4899
    /**
4900
     * Get the string that describes the options of this page type
4901
     * @return string
4902
     */
4903
    public function option_description_string() {
4904
        return '';
4905
    }
4906
 
4907
    /**
4908
     * Updates a table with the answers for this page
4909
     * @param html_table $table
4910
     * @return html_table
4911
     */
4912
    public function display_answers(html_table $table) {
4913
        $answers = $this->get_answers();
4914
        $i = 1;
4915
        foreach ($answers as $answer) {
4916
            $cells = array();
4917
            $cells[] = '<label>' . get_string('jump', 'lesson') . ' ' . $i . '</label>:';
4918
            $cells[] = $this->get_jump_name($answer->jumpto);
4919
            $table->data[] = new html_table_row($cells);
4920
            if ($i === 1){
4921
                $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
4922
            }
4923
            $i++;
4924
        }
4925
        return $table;
4926
    }
4927
 
4928
    /**
4929
     * Determines if this page should be grayed out on the management/report screens
4930
     * @return int 0 or 1
4931
     */
4932
    protected function get_grayout() {
4933
        return 0;
4934
    }
4935
 
4936
    /**
4937
     * Adds stats for this page to the &pagestats object. This should be defined
4938
     * for all page types that grade
4939
     * @param array $pagestats
4940
     * @param int $tries
4941
     * @return bool
4942
     */
4943
    public function stats(array &$pagestats, $tries) {
4944
        return true;
4945
    }
4946
 
4947
    /**
4948
     * Formats the answers of this page for a report
4949
     *
4950
     * @param object $answerpage
4951
     * @param object $answerdata
4952
     * @param object $useranswer
4953
     * @param array $pagestats
4954
     * @param int $i Count of first level answers
4955
     * @param int $n Count of second level answers
4956
     * @return object The answer page for this
4957
     */
4958
    public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
4959
        $answers = $this->get_answers();
4960
        $formattextdefoptions = new stdClass;
4961
        $formattextdefoptions->para = false;  //I'll use it widely in this page
4962
        foreach ($answers as $answer) {
4963
            $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
4964
            $answerdata->answers[] = array($data, "");
4965
            $answerpage->answerdata = $answerdata;
4966
        }
4967
        return $answerpage;
4968
    }
4969
 
4970
    /**
4971
     * Gets an array of the jumps used by the answers of this page
4972
     *
4973
     * @return array
4974
     */
4975
    public function get_jumps() {
4976
        global $DB;
4977
        $jumps = array();
4978
        $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id);
4979
        if ($answers = $this->get_answers()) {
4980
            foreach ($answers as $answer) {
4981
                $jumps[] = $this->get_jump_name($answer->jumpto);
4982
            }
4983
        } else {
4984
            $jumps[] = $this->get_jump_name($this->properties->nextpageid);
4985
        }
4986
        return $jumps;
4987
    }
4988
    /**
4989
     * Informs whether this page type require manual grading or not
4990
     * @return bool
4991
     */
4992
    public function requires_manual_grading() {
4993
        return false;
4994
    }
4995
 
4996
    /**
4997
     * A callback method that allows a page to override the next page a user will
4998
     * see during when this page is being completed.
4999
     * @return false|int
5000
     */
5001
    public function override_next_page() {
5002
        return false;
5003
    }
5004
 
5005
    /**
5006
     * This method is used to determine if this page is a valid page
5007
     *
5008
     * @param array $validpages
5009
     * @param array $pageviews
5010
     * @return int The next page id to check
5011
     */
5012
    public function valid_page_and_view(&$validpages, &$pageviews) {
5013
        $validpages[$this->properties->id] = 1;
5014
        return $this->properties->nextpageid;
5015
    }
5016
 
5017
    /**
5018
     * Get files from the page area file.
5019
     *
5020
     * @param bool $includedirs whether or not include directories
5021
     * @param int $updatedsince return files updated since this time
5022
     * @return array list of stored_file objects
5023
     * @since  Moodle 3.2
5024
     */
5025
    public function get_files($includedirs = true, $updatedsince = 0) {
5026
        $fs = get_file_storage();
5027
        return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id,
5028
                                    'itemid, filepath, filename', $includedirs, $updatedsince);
5029
    }
5030
 
5031
    /**
5032
     * Make updates to the form data if required.
5033
     *
5034
     * @since Moodle 3.7
5035
     * @param stdClass $data The form data to update.
5036
     * @return stdClass The updated fom data.
5037
     */
5038
    public function update_form_data(stdClass $data): stdClass {
5039
        return $data;
5040
    }
5041
}
5042
 
5043
 
5044
 
5045
/**
5046
 * Class used to represent an answer to a page
5047
 *
5048
 * @property int $id The ID of this answer in the database
5049
 * @property int $lessonid The ID of the lesson this answer belongs to
5050
 * @property int $pageid The ID of the page this answer belongs to
5051
 * @property int $jumpto Identifies where the user goes upon completing a page with this answer
5052
 * @property int $grade The grade this answer is worth
5053
 * @property int $score The score this answer will give
5054
 * @property int $flags Used to store options for the answer
5055
 * @property int $timecreated A timestamp of when the answer was created
5056
 * @property int $timemodified A timestamp of when the answer was modified
5057
 * @property string $answer The answer itself
5058
 * @property string $response The response the user sees if selecting this answer
5059
 *
5060
 * @copyright  2009 Sam Hemelryk
5061
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5062
 */
5063
class lesson_page_answer extends lesson_base {
5064
 
5065
    /**
5066
     * Loads an page answer from the DB
5067
     *
5068
     * @param int $id
5069
     * @return lesson_page_answer
5070
     */
5071
    public static function load($id) {
5072
        global $DB;
5073
        $answer = $DB->get_record("lesson_answers", array("id" => $id));
5074
        return new lesson_page_answer($answer);
5075
    }
5076
 
5077
    /**
5078
     * Given an object of properties and a page created answer(s) and saves them
5079
     * in the database.
5080
     *
5081
     * @param stdClass $properties
5082
     * @param lesson_page $page
5083
     * @return array
5084
     */
5085
    public static function create($properties, lesson_page $page) {
5086
        return $page->create_answers($properties);
5087
    }
5088
 
5089
    /**
5090
     * Get files from the answer area file.
5091
     *
5092
     * @param bool $includedirs whether or not include directories
5093
     * @param int $updatedsince return files updated since this time
5094
     * @return array list of stored_file objects
5095
     * @since  Moodle 3.2
5096
     */
5097
    public function get_files($includedirs = true, $updatedsince = 0) {
5098
 
5099
        $lesson = lesson::load($this->properties->lessonid);
5100
        $fs = get_file_storage();
5101
        $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
5102
                                            'itemid, filepath, filename', $includedirs, $updatedsince);
5103
        $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
5104
                                            'itemid, filepath, filename', $includedirs, $updatedsince);
5105
        return array_merge($answerfiles, $responsefiles);
5106
    }
5107
 
5108
}
5109
 
5110
/**
5111
 * A management class for page types
5112
 *
5113
 * This class is responsible for managing the different pages. A manager object can
5114
 * be retrieved by calling the following line of code:
5115
 * <code>
5116
 * $manager  = lesson_page_type_manager::get($lesson);
5117
 * </code>
5118
 * The first time the page type manager is retrieved the it includes all of the
5119
 * different page types located in mod/lesson/pagetypes.
5120
 *
5121
 * @copyright  2009 Sam Hemelryk
5122
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5123
 */
5124
class lesson_page_type_manager {
5125
 
5126
    /**
5127
     * An array of different page type classes
5128
     * @var array
5129
     */
5130
    protected $types = array();
5131
 
5132
    /**
5133
     * Retrieves the lesson page type manager object
5134
     *
5135
     * If the object hasn't yet been created it is created here.
5136
     *
5137
     * @staticvar lesson_page_type_manager $pagetypemanager
5138
     * @param lesson $lesson
5139
     * @return lesson_page_type_manager
5140
     */
5141
    public static function get(lesson $lesson) {
5142
        static $pagetypemanager;
5143
        if (!($pagetypemanager instanceof lesson_page_type_manager)) {
5144
            $pagetypemanager = new lesson_page_type_manager();
5145
            $pagetypemanager->load_lesson_types($lesson);
5146
        }
5147
        return $pagetypemanager;
5148
    }
5149
 
5150
    /**
5151
     * Finds and loads all lesson page types in mod/lesson/pagetypes
5152
     *
5153
     * @param lesson $lesson
5154
     */
5155
    public function load_lesson_types(lesson $lesson) {
5156
        global $CFG;
5157
        $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/';
5158
        $dir = dir($basedir);
5159
        while (false !== ($entry = $dir->read())) {
5160
            if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) {
5161
                continue;
5162
            }
5163
            require_once($basedir.$entry);
5164
            $class = 'lesson_page_type_'.strtok($entry,'.');
5165
            if (class_exists($class)) {
5166
                $pagetype = new $class(new stdClass, $lesson);
5167
                $this->types[$pagetype->typeid] = $pagetype;
5168
            }
5169
        }
5170
 
5171
    }
5172
 
5173
    /**
5174
     * Returns an array of strings to describe the loaded page types
5175
     *
5176
     * @param int $type Can be used to return JUST the string for the requested type
5177
     * @return array
5178
     */
5179
    public function get_page_type_strings($type=null, $special=true) {
5180
        $types = array();
5181
        foreach ($this->types as $pagetype) {
5182
            if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) {
5183
                $types[$pagetype->typeid] = $pagetype->typestring;
5184
            }
5185
        }
5186
        return $types;
5187
    }
5188
 
5189
    /**
5190
     * Returns the basic string used to identify a page type provided with an id
5191
     *
5192
     * This string can be used to instantiate or identify the page type class.
5193
     * If the page type id is unknown then 'unknown' is returned
5194
     *
5195
     * @param int $id
5196
     * @return string
5197
     */
5198
    public function get_page_type_idstring($id) {
5199
        foreach ($this->types as $pagetype) {
5200
            if ((int)$pagetype->typeid === (int)$id) {
5201
                return $pagetype->idstring;
5202
            }
5203
        }
5204
        return 'unknown';
5205
    }
5206
 
5207
    /**
5208
     * Loads a page for the provided lesson given it's id
5209
     *
5210
     * This function loads a page from the lesson when given both the lesson it belongs
5211
     * to as well as the page's id.
5212
     * If the page doesn't exist an error is thrown
5213
     *
5214
     * @param int $pageid The id of the page to load
5215
     * @param lesson $lesson The lesson the page belongs to
5216
     * @return lesson_page A class that extends lesson_page
5217
     */
5218
    public function load_page($pageid, lesson $lesson) {
5219
        global $DB;
5220
        if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) {
5221
            throw new \moodle_exception('cannotfindpages', 'lesson');
5222
        }
5223
        $pagetype = get_class($this->types[$page->qtype]);
5224
        $page = new $pagetype($page, $lesson);
5225
        return $page;
5226
    }
5227
 
5228
    /**
5229
     * This function detects errors in the ordering between 2 pages and updates the page records.
5230
     *
5231
     * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list.
5232
     * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list.
5233
     */
5234
    protected function check_page_order($page1, $page2) {
5235
        global $DB;
5236
        if (empty($page1)) {
5237
            if ($page2->prevpageid != 0) {
5238
                debugging("***prevpageid of page " . $page2->id . " set to 0***");
5239
                $page2->prevpageid = 0;
5240
                $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id));
5241
            }
5242
        } else if (empty($page2)) {
5243
            if ($page1->nextpageid != 0) {
5244
                debugging("***nextpageid of page " . $page1->id . " set to 0***");
5245
                $page1->nextpageid = 0;
5246
                $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id));
5247
            }
5248
        } else {
5249
            if ($page1->nextpageid != $page2->id) {
5250
                debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***");
5251
                $page1->nextpageid = $page2->id;
5252
                $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id));
5253
            }
5254
            if ($page2->prevpageid != $page1->id) {
5255
                debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***");
5256
                $page2->prevpageid = $page1->id;
5257
                $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id));
5258
            }
5259
        }
5260
    }
5261
 
5262
    /**
5263
     * This function loads ALL pages that belong to the lesson.
5264
     *
5265
     * @param lesson $lesson
5266
     * @return array An array of lesson_page_type_*
5267
     */
5268
    public function load_all_pages(lesson $lesson) {
5269
        global $DB;
5270
        if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
5271
            return array(); // Records returned empty.
5272
        }
5273
        foreach ($pages as $key=>$page) {
5274
            $pagetype = get_class($this->types[$page->qtype]);
5275
            $pages[$key] = new $pagetype($page, $lesson);
5276
        }
5277
 
5278
        $orderedpages = array();
5279
        $lastpageid = 0;
5280
        $morepages = true;
5281
        while ($morepages) {
5282
            $morepages = false;
5283
            foreach ($pages as $page) {
5284
                if ((int)$page->prevpageid === (int)$lastpageid) {
5285
                    // Check for errors in page ordering and fix them on the fly.
5286
                    $prevpage = null;
5287
                    if ($lastpageid !== 0) {
5288
                        $prevpage = $orderedpages[$lastpageid];
5289
                    }
5290
                    $this->check_page_order($prevpage, $page);
5291
                    $morepages = true;
5292
                    $orderedpages[$page->id] = $page;
5293
                    unset($pages[$page->id]);
5294
                    $lastpageid = $page->id;
5295
                    if ((int)$page->nextpageid===0) {
5296
                        break 2;
5297
                    } else {
5298
                        break 1;
5299
                    }
5300
                }
5301
            }
5302
        }
5303
 
5304
        // Add remaining pages and fix the nextpageid links for each page.
5305
        foreach ($pages as $page) {
5306
            // Check for errors in page ordering and fix them on the fly.
5307
            $prevpage = null;
5308
            if ($lastpageid !== 0) {
5309
                $prevpage = $orderedpages[$lastpageid];
5310
            }
5311
            $this->check_page_order($prevpage, $page);
5312
            $orderedpages[$page->id] = $page;
5313
            unset($pages[$page->id]);
5314
            $lastpageid = $page->id;
5315
        }
5316
 
5317
        if ($lastpageid !== 0) {
5318
            $this->check_page_order($orderedpages[$lastpageid], null);
5319
        }
5320
 
5321
        return $orderedpages;
5322
    }
5323
 
5324
    /**
5325
     * Fetches an mform that can be used to create/edit an page
5326
     *
5327
     * @param int $type The id for the page type
5328
     * @param array $arguments Any arguments to pass to the mform
5329
     * @return lesson_add_page_form_base
5330
     */
5331
    public function get_page_form($type, $arguments) {
5332
        $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type);
5333
        if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') {
5334
            debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER);
5335
            $class = 'lesson_add_page_form_selection';
5336
        } else if ($class === 'lesson_add_page_form_unknown') {
5337
            $class = 'lesson_add_page_form_selection';
5338
        }
5339
        return new $class(null, $arguments);
5340
    }
5341
 
5342
    /**
5343
     * Returns an array of links to use as add page links
5344
     * @param int $previd The id of the previous page
5345
     * @return array
5346
     */
5347
    public function get_add_page_type_links($previd) {
5348
        global $OUTPUT;
5349
 
5350
        $links = array();
5351
 
5352
        foreach ($this->types as $key=>$type) {
5353
            if ($link = $type->add_page_link($previd)) {
5354
                $links[$key] = $link;
5355
            }
5356
        }
5357
 
5358
        return $links;
5359
    }
5360
}