Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace mod_quiz;
18
 
19
use action_link;
20
use block_contents;
21
use cm_info;
22
use coding_exception;
23
use context_module;
24
use core\di;
25
use core\hook;
26
use Exception;
27
use html_writer;
28
use mod_quiz\hook\attempt_state_changed;
29
use mod_quiz\output\grades\grade_out_of;
30
use mod_quiz\output\links_to_other_attempts;
31
use mod_quiz\output\renderer;
32
use mod_quiz\question\bank\qbank_helper;
33
use mod_quiz\question\display_options;
34
use moodle_exception;
35
use moodle_url;
36
use popup_action;
37
use qtype_description_question;
38
use question_attempt;
39
use question_bank;
40
use question_display_options;
41
use question_engine;
42
use question_out_of_sequence_exception;
43
use question_state;
44
use question_usage_by_activity;
45
use stdClass;
46
 
47
/**
48
 * This class represents one user's attempt at a particular quiz.
49
 *
50
 * @package   mod_quiz
51
 * @copyright 2008 Tim Hunt
52
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53
 */
54
class quiz_attempt {
55
 
56
    /** @var string to identify the in progress state. */
57
    const IN_PROGRESS = 'inprogress';
58
    /** @var string to identify the overdue state. */
59
    const OVERDUE     = 'overdue';
60
    /** @var string to identify the finished state. */
61
    const FINISHED    = 'finished';
62
    /** @var string to identify the abandoned state. */
63
    const ABANDONED   = 'abandoned';
64
 
65
    /** @var int maximum number of slots in the quiz for the review page to default to show all. */
66
    const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL = 50;
67
 
68
    /** @var int amount of time considered 'immedately after the attempt', in seconds. */
69
    const IMMEDIATELY_AFTER_PERIOD = 2 * MINSECS;
70
 
71
    /** @var quiz_settings object containing the quiz settings. */
72
    protected $quizobj;
73
 
74
    /** @var stdClass the quiz_attempts row. */
75
    protected $attempt;
76
 
77
    /**
78
     * @var question_usage_by_activity|null the question usage for this quiz attempt.
79
     *
80
     * Only available after load_questions is called, e.g. if the class is constructed
81
     * with $loadquestions true (the default).
82
     */
83
    protected ?question_usage_by_activity $quba = null;
84
 
85
    /**
86
     * @var array of slot information. These objects contain ->id (int), ->slot (int),
87
     *      ->requireprevious (bool), ->displaynumber (string) and quizgradeitemid (int) from the DB.
88
     *      They do not contain page - get that from {@see get_question_page()} -
89
     *      or maxmark - get that from $this->quba. It is augmented with
90
     *      ->firstinsection (bool), ->section (stdClass from $this->sections).
91
     */
92
    protected $slots;
93
 
94
    /** @var array of quiz_sections rows, with a ->lastslot field added. */
95
    protected $sections;
96
 
97
    /** @var grade_calculator instance for this quiz. */
98
    protected grade_calculator $gradecalculator;
99
 
100
    /**
101
     * @var grade_out_of[]|null can be used to store the total grade for each section.
102
     *
103
     * This is typically done when one or more attempts are created without load_questions.
104
     * This lets the mark totals be passed in and later used. Format of this array should
105
     * match what {@see grade_calculator::compute_grade_item_totals()} would return.
106
     */
107
    protected ?array $gradeitemmarks = null;
108
 
109
    /** @var array page no => array of slot numbers on the page in order. */
110
    protected $pagelayout;
111
 
112
    /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */
113
    protected $questionnumbers;
114
 
115
    /** @var array slot => page number for this slot. */
116
    protected $questionpages;
117
 
118
    /** @var display_options cache for the appropriate review options. */
119
    protected $reviewoptions = null;
120
 
121
    // Constructor =============================================================.
122
    /**
123
     * Constructor assuming we already have the necessary data loaded.
124
     *
125
     * @param stdClass $attempt the row of the quiz_attempts table.
126
     * @param stdClass $quiz the quiz object for this attempt and user.
127
     * @param cm_info $cm the course_module object for this quiz.
128
     * @param stdClass $course the row from the course table for the course we belong to.
129
     * @param bool $loadquestions (optional) if true, the default, load all the details
130
     *      of the state of each question. Else just set up the basic details of the attempt.
131
     */
132
    public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) {
133
        $this->attempt = $attempt;
134
        $this->quizobj = new quiz_settings($quiz, $cm, $course);
135
        $this->gradecalculator = $this->quizobj->get_grade_calculator();
136
 
137
        if ($loadquestions) {
138
            $this->load_questions();
139
            $this->gradecalculator->set_slots($this->slots);
140
        }
141
    }
142
 
143
    /**
144
     * Used by {create()} and {create_from_usage_id()}.
145
     *
146
     * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions).
147
     * @return quiz_attempt the desired instance of this class.
148
     */
149
    protected static function create_helper($conditions) {
150
        global $DB;
151
 
152
        $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST);
153
        $quiz = access_manager::load_quiz_and_settings($attempt->quiz);
154
        $course = get_course($quiz->course);
155
        $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
156
 
157
        // Update quiz with override information.
158
        $quiz = quiz_update_effective_access($quiz, $attempt->userid);
159
 
160
        return new quiz_attempt($attempt, $quiz, $cm, $course);
161
    }
162
 
163
    /**
164
     * Static function to create a new quiz_attempt object given an attemptid.
165
     *
166
     * @param int $attemptid the attempt id.
167
     * @return quiz_attempt the new quiz_attempt object
168
     */
169
    public static function create($attemptid) {
170
        return self::create_helper(['id' => $attemptid]);
171
    }
172
 
173
    /**
174
     * Static function to create a new quiz_attempt object given a usage id.
175
     *
176
     * @param int $usageid the attempt usage id.
177
     * @return quiz_attempt the new quiz_attempt object
178
     */
179
    public static function create_from_usage_id($usageid) {
180
        return self::create_helper(['uniqueid' => $usageid]);
181
    }
182
 
183
    /**
184
     * Get a human-readable name for one of the quiz attempt states.
185
     *
186
     * @param string $state one of the state constants like IN_PROGRESS.
187
     * @return string the human-readable state name.
188
     */
189
    public static function state_name($state) {
190
        return quiz_attempt_state_name($state);
191
    }
192
 
193
    /**
194
     * This method can be called later if the object was constructed with $loadquestions = false.
195
     */
196
    public function load_questions() {
197
        global $DB;
198
 
199
        if (isset($this->quba)) {
200
            throw new coding_exception('This quiz attempt has already had the questions loaded.');
201
        }
202
 
203
        $this->quba = question_engine::load_questions_usage_by_activity($this->attempt->uniqueid);
204
        $this->slots = $DB->get_records('quiz_slots', ['quizid' => $this->get_quizid()],
205
                'slot', 'slot, id, requireprevious, displaynumber, quizgradeitemid');
206
        $this->sections = array_values($DB->get_records('quiz_sections',
207
                ['quizid' => $this->get_quizid()], 'firstslot'));
208
 
209
        $this->link_sections_and_slots();
210
        $this->determine_layout();
211
        $this->number_questions();
212
    }
213
 
214
    /**
215
     * Preload all attempt step users to show in Response history.
216
     */
217
    public function preload_all_attempt_step_users(): void {
218
        $this->quba->preload_all_step_users();
219
    }
220
 
221
    /**
222
     * Let each slot know which section it is part of.
223
     */
224
    protected function link_sections_and_slots() {
225
        foreach ($this->sections as $i => $section) {
226
            if (isset($this->sections[$i + 1])) {
227
                $section->lastslot = $this->sections[$i + 1]->firstslot - 1;
228
            } else {
229
                $section->lastslot = count($this->slots);
230
            }
231
            for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
232
                $this->slots[$slot]->section = $section;
233
            }
234
        }
235
    }
236
 
237
    /**
238
     * Parse attempt->layout to populate the other arrays that represent the layout.
239
     */
240
    protected function determine_layout() {
241
 
242
        // Break up the layout string into pages.
243
        $pagelayouts = explode(',0', $this->attempt->layout);
244
 
245
        // Strip off any empty last page (normally there is one).
246
        if (end($pagelayouts) == '') {
247
            array_pop($pagelayouts);
248
        }
249
 
250
        // File the ids into the arrays.
251
        // Tracking which is the first slot in each section in this attempt is
252
        // trickier than you might guess, since the slots in this section
253
        // may be shuffled, so $section->firstslot (the lowest numbered slot in
254
        // the section) may not be the first one.
255
        $unseensections = $this->sections;
256
        $this->pagelayout = [];
257
        foreach ($pagelayouts as $page => $pagelayout) {
258
            $pagelayout = trim($pagelayout, ',');
259
            if ($pagelayout == '') {
260
                continue;
261
            }
262
            $this->pagelayout[$page] = explode(',', $pagelayout);
263
            foreach ($this->pagelayout[$page] as $slot) {
264
                $sectionkey = array_search($this->slots[$slot]->section, $unseensections);
265
                if ($sectionkey !== false) {
266
                    $this->slots[$slot]->firstinsection = true;
267
                    unset($unseensections[$sectionkey]);
268
                } else {
269
                    $this->slots[$slot]->firstinsection = false;
270
                }
271
            }
272
        }
273
    }
274
 
275
    /**
276
     * Work out the number to display for each question/slot.
277
     */
278
    protected function number_questions() {
279
        $number = 1;
280
        foreach ($this->pagelayout as $page => $slots) {
281
            foreach ($slots as $slot) {
282
                if ($length = $this->is_real_question($slot)) {
283
                    // Whether question numbering is customised or is numeric and automatically incremented.
284
                    if ($this->slots[$slot]->displaynumber !== null && $this->slots[$slot]->displaynumber !== '' &&
285
                            !$this->slots[$slot]->section->shufflequestions) {
286
                        $this->questionnumbers[$slot] = $this->slots[$slot]->displaynumber;
287
                    } else {
288
                        $this->questionnumbers[$slot] = (string) $number;
289
                    }
290
                    $number += $length;
291
                } else {
292
                    $this->questionnumbers[$slot] = get_string('infoshort', 'quiz');
293
                }
294
                $this->questionpages[$slot] = $page;
295
            }
296
        }
297
    }
298
 
299
    /**
300
     * If the given page number is out of range (before the first page, or after
301
     * the last page, change it to be within range).
302
     *
303
     * @param int $page the requested page number.
304
     * @return int a safe page number to use.
305
     */
306
    public function force_page_number_into_range($page) {
307
        return min(max($page, 0), count($this->pagelayout) - 1);
308
    }
309
 
310
    // Simple getters ==========================================================.
311
 
312
    /**
313
     * Get the raw quiz settings object.
314
     *
315
     * @return stdClass
316
     */
317
    public function get_quiz() {
318
        return $this->quizobj->get_quiz();
319
    }
320
 
321
    /**
322
     * Get the {@see seb_quiz_settings} object for this quiz.
323
     *
324
     * @return quiz_settings
325
     */
326
    public function get_quizobj() {
327
        return $this->quizobj;
328
    }
329
 
330
    /**
331
     * Git the id of the course this quiz belongs to.
332
     *
333
     * @return int the course id.
334
     */
335
    public function get_courseid() {
336
        return $this->quizobj->get_courseid();
337
    }
338
 
339
    /**
340
     * Get the course settings object.
341
     *
342
     * @return stdClass the course settings object.
343
     */
344
    public function get_course() {
345
        return $this->quizobj->get_course();
346
    }
347
 
348
    /**
349
     * Get the quiz id.
350
     *
351
     * @return int the quiz id.
352
     */
353
    public function get_quizid() {
354
        return $this->quizobj->get_quizid();
355
    }
356
 
357
    /**
358
     * Get the name of this quiz.
359
     *
360
     * @return string Quiz name, directly from the database (format_string must be called before output).
361
     */
362
    public function get_quiz_name() {
363
        return $this->quizobj->get_quiz_name();
364
    }
365
 
366
    /**
367
     * Get the quiz navigation method.
368
     *
369
     * @return int QUIZ_NAVMETHOD_FREE or QUIZ_NAVMETHOD_SEQ.
370
     */
371
    public function get_navigation_method() {
372
        return $this->quizobj->get_navigation_method();
373
    }
374
 
375
    /**
376
     * Get the course_module for this quiz.
377
     *
378
     * @return cm_info the course_module object.
379
     */
380
    public function get_cm() {
381
        return $this->quizobj->get_cm();
382
    }
383
 
384
    /**
385
     * Get the course-module id.
386
     *
387
     * @return int the course_module id.
388
     */
389
    public function get_cmid() {
390
        return $this->quizobj->get_cmid();
391
    }
392
 
393
    /**
394
     * Get the quiz context.
395
     *
396
     * @return context_module the context of the quiz this attempt belongs to.
397
     */
398
    public function get_context(): context_module {
399
        return $this->quizobj->get_context();
400
    }
401
 
402
    /**
403
     * Is the current user is someone who previews the quiz, rather than attempting it?
404
     *
405
     * @return bool true user is a preview user. False, if they can do real attempts.
406
     */
407
    public function is_preview_user() {
408
        return $this->quizobj->is_preview_user();
409
    }
410
 
411
    /**
412
     * Get the number of attempts the user is allowed at this quiz.
413
     *
414
     * @return int the number of attempts allowed at this quiz (0 = infinite).
415
     */
416
    public function get_num_attempts_allowed() {
417
        return $this->quizobj->get_num_attempts_allowed();
418
    }
419
 
420
    /**
421
     * Get the number of quizzes in the quiz attempt.
422
     *
423
     * @return int number pages.
424
     */
425
    public function get_num_pages() {
426
        return count($this->pagelayout);
427
    }
428
 
429
    /**
430
     * Get the access_manager for this quiz attempt.
431
     *
432
     * @param int $timenow the current time as a unix timestamp.
433
     * @return access_manager and instance of the access_manager class
434
     *      for this quiz at this time.
435
     */
436
    public function get_access_manager($timenow) {
437
        return $this->quizobj->get_access_manager($timenow);
438
    }
439
 
440
    /**
441
     * Get the id of this attempt.
442
     *
443
     * @return int the attempt id.
444
     */
445
    public function get_attemptid() {
446
        return $this->attempt->id;
447
    }
448
 
449
    /**
450
     * Get the question-usage id corresponding to this quiz attempt.
451
     *
452
     * @return int the attempt unique id.
453
     */
454
    public function get_uniqueid() {
455
        return $this->attempt->uniqueid;
456
    }
457
 
458
    /**
459
     * Get the raw quiz attempt object.
460
     *
461
     * @return stdClass the row from the quiz_attempts table.
462
     */
463
    public function get_attempt() {
464
        return $this->attempt;
465
    }
466
 
467
    /**
468
     * Get the attempt number.
469
     *
470
     * @return int the number of this attempt (is it this user's first, second, ... attempt).
471
     */
472
    public function get_attempt_number() {
473
        return $this->attempt->attempt;
474
    }
475
 
476
    /**
477
     * Get the state of this attempt.
478
     *
479
     * @return string {@see IN_PROGRESS}, {@see FINISHED}, {@see OVERDUE} or {@see ABANDONED}.
480
     */
481
    public function get_state() {
482
        return $this->attempt->state;
483
    }
484
 
485
    /**
486
     * Get the id of the user this attempt belongs to.
487
     * @return int user id.
488
     */
489
    public function get_userid() {
490
        return $this->attempt->userid;
491
    }
492
 
493
    /**
494
     * Get the current page of the attempt
495
     * @return int page number.
496
     */
497
    public function get_currentpage() {
498
        return $this->attempt->currentpage;
499
    }
500
 
501
    /**
502
     * Compute the grade and maximum grade for each grade item, for this attempt.
503
     *
504
     * @return grade_out_of[] the grade for each item where the total grade is not zero.
505
     *      ->name will be set to the grade item name. Must be output through {@see format_string()}.
506
     */
507
    public function get_grade_item_totals(): array {
508
        if ($this->gradeitemmarks !== null) {
509
            return $this->gradeitemmarks;
510
        } else if ($this->quba !== null) {
511
            return $this->gradecalculator->compute_grade_item_totals($this->quba);
512
        } else {
513
            throw new coding_exception('To call get_grade_item_totals, you must either have ' .
514
                '->quba set (e.g. create this class with $loadquestions true) or you must ' .
515
                'previously have computed the totals (e.g. with ' .
516
                'grade_calculator::compute_grade_item_totals_for_attempts() and pass them to ' .
517
                '->set_grade_item_totals().');
518
        }
519
    }
520
 
521
    /**
522
     * Set the total grade for each grade_item for this quiz.
523
     *
524
     * You only need to do this if the instance of this class was created with $loadquestions false.
525
     * Typically, you will have got the grades from {@see grade_calculator::compute_grade_item_totals_for_attempts()}.
526
     *
527
     * @param grade_out_of[] $grades same form as {@see grade_calculator::compute_grade_item_totals()} would return.
528
     */
529
    public function set_grade_item_totals(array $grades): void {
530
        $this->gradeitemmarks = $grades;
531
    }
532
 
533
    /**
534
     * Get the total number of marks that the user had scored on all the questions.
535
     *
536
     * @return float
537
     */
538
    public function get_sum_marks() {
539
        return $this->attempt->sumgrades;
540
    }
541
 
542
    /**
543
     * Has this attempt been finished?
544
     *
545
     * States {@see FINISHED} and {@see ABANDONED} are both considered finished in this state.
546
     * Other states are not.
547
     *
548
     * @return bool
549
     */
550
    public function is_finished() {
551
        return $this->attempt->state == self::FINISHED || $this->attempt->state == self::ABANDONED;
552
    }
553
 
554
    /**
555
     * Is this attempt a preview?
556
     *
557
     * @return bool true if it is.
558
     */
559
    public function is_preview() {
560
        return $this->attempt->preview;
561
    }
562
 
563
    /**
564
     * Does this attempt belong to the current user?
565
     *
566
     * @return bool true => own attempt/preview. false => reviewing someone else's.
567
     */
568
    public function is_own_attempt() {
569
        global $USER;
570
        return $this->attempt->userid == $USER->id;
571
    }
572
 
573
    /**
574
     * Is this attempt is a preview belonging to the current user.
575
     *
576
     * @return bool true if it is.
577
     */
578
    public function is_own_preview() {
579
        return $this->is_own_attempt() &&
580
                $this->is_preview_user() && $this->attempt->preview;
581
    }
582
 
583
    /**
584
     * Is the current user allowed to review this attempt. This applies when
585
     * {@see is_own_attempt()} returns false.
586
     *
587
     * @return bool whether the review should be allowed.
588
     */
589
    public function is_review_allowed() {
590
        if (!$this->has_capability('mod/quiz:viewreports')) {
591
            return false;
592
        }
593
 
594
        $cm = $this->get_cm();
595
        if ($this->has_capability('moodle/site:accessallgroups') ||
596
                groups_get_activity_groupmode($cm) != SEPARATEGROUPS) {
597
            return true;
598
        }
599
 
600
        // Check the users have at least one group in common.
601
        $teachersgroups = groups_get_activity_allowed_groups($cm);
602
        $studentsgroups = groups_get_all_groups(
603
                $cm->course, $this->attempt->userid, $cm->groupingid);
604
        return $teachersgroups && $studentsgroups &&
605
                array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
606
    }
607
 
608
    /**
609
     * Has the student, in this attempt, engaged with the quiz in a non-trivial way?
610
     *
611
     * That is, is there any question worth a non-zero number of marks, where
612
     * the student has made some response that we have saved?
613
     *
614
     * @return bool true if we have saved a response for at least one graded question.
615
     */
616
    public function has_response_to_at_least_one_graded_question() {
617
        foreach ($this->quba->get_attempt_iterator() as $qa) {
618
            if ($qa->get_max_mark() == 0) {
619
                continue;
620
            }
621
            if ($qa->get_num_steps() > 1) {
622
                return true;
623
            }
624
        }
625
        return false;
626
    }
627
 
628
    /**
629
     * Do any questions in this attempt need to be graded manually?
630
     *
631
     * @return bool True if we have at least one question still needs manual grading.
632
     */
633
    public function requires_manual_grading(): bool {
634
        return $this->quba->get_total_mark() === null;
635
    }
636
 
637
    /**
638
     * Get extra summary information about this attempt.
639
     *
640
     * Some behaviours may be able to provide interesting summary information
641
     * about the attempt as a whole, and this method provides access to that data.
642
     * To see how this works, try setting a quiz to one of the CBM behaviours,
643
     * and then look at the extra information displayed at the top of the quiz
644
     * review page once you have submitted an attempt.
645
     *
646
     * In the return value, the array keys are identifiers of the form
647
     * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
648
     * The values are arrays with two items, title and content. Each of these
649
     * will be either a string, or a renderable.
650
     *
651
     * If this method is called before load_questions() is called, then an empty array is returned.
652
     *
653
     * @param question_display_options $options the display options for this quiz attempt at this time.
654
     * @return array as described above.
655
     */
656
    public function get_additional_summary_data(question_display_options $options) {
657
        if (!isset($this->quba)) {
658
            return [];
659
        }
660
        return $this->quba->get_summary_information($options);
661
    }
662
 
663
    /**
664
     * Get the overall feedback corresponding to a particular mark.
665
     *
666
     * @param number $grade a particular grade.
667
     * @return string the feedback.
668
     */
669
    public function get_overall_feedback($grade) {
670
        return quiz_feedback_for_grade($grade, $this->get_quiz(),
671
                $this->quizobj->get_context());
672
    }
673
 
674
    /**
675
     * Wrapper round the has_capability function that automatically passes in the quiz context.
676
     *
677
     * @param string $capability the name of the capability to check. For example mod/forum:view.
678
     * @param int|null $userid A user id. If null checks the permissions of the current user.
679
     * @param bool $doanything If false, ignore effect of admin role assignment.
680
     * @return boolean true if the user has this capability, otherwise false.
681
     */
682
    public function has_capability($capability, $userid = null, $doanything = true) {
683
        return $this->quizobj->has_capability($capability, $userid, $doanything);
684
    }
685
 
686
    /**
687
     * Wrapper round the require_capability function that automatically passes in the quiz context.
688
     *
689
     * @param string $capability the name of the capability to check. For example mod/forum:view.
690
     * @param int|null $userid A user id. If null checks the permissions of the current user.
691
     * @param bool $doanything If false, ignore effect of admin role assignment.
692
     */
693
    public function require_capability($capability, $userid = null, $doanything = true) {
694
        $this->quizobj->require_capability($capability, $userid, $doanything);
695
    }
696
 
697
    /**
698
     * Check the appropriate capability to see whether this user may review their own attempt.
699
     * If not, prints an error.
700
     */
701
    public function check_review_capability() {
702
        if ($this->get_attempt_state() == display_options::IMMEDIATELY_AFTER) {
703
            $capability = 'mod/quiz:attempt';
704
        } else {
705
            $capability = 'mod/quiz:reviewmyattempts';
706
        }
707
 
708
        // These next tests are in a slightly funny order. The point is that the
709
        // common and most performance-critical case is students attempting a quiz,
710
        // so we want to check that permission first.
711
 
712
        if ($this->has_capability($capability)) {
713
            // User has the permission that lets you do the quiz as a student. Fine.
714
            return;
715
        }
716
 
717
        if ($this->has_capability('mod/quiz:viewreports') ||
718
                $this->has_capability('mod/quiz:preview')) {
719
            // User has the permission that lets teachers review. Fine.
720
            return;
721
        }
722
 
723
        // They should not be here. Trigger the standard no-permission error
724
        // but using the name of the student capability.
725
        // We know this will fail. We just want the standard exception thrown.
726
        $this->require_capability($capability);
727
    }
728
 
729
    /**
730
     * Checks whether a user may navigate to a particular slot.
731
     *
732
     * @param int $slot the target slot (currently does not affect the answer).
733
     * @return bool true if the navigation should be allowed.
734
     */
735
    public function can_navigate_to($slot) {
736
        if ($this->attempt->state == self::OVERDUE) {
737
            // When the attempt is overdue, students can only see the
738
            // attempt summary page and cannot navigate anywhere else.
739
            return false;
740
        }
741
 
742
        return $this->get_navigation_method() == QUIZ_NAVMETHOD_FREE;
743
    }
744
 
745
    /**
746
     * Get where we are time-wise in relation to this attempt and the quiz settings.
747
     *
748
     * @return int one of {@see display_options::DURING}, {@see display_options::IMMEDIATELY_AFTER},
749
     *      {@see display_options::LATER_WHILE_OPEN} or {@see display_options::AFTER_CLOSE}.
750
     */
751
    public function get_attempt_state() {
752
        return quiz_attempt_state($this->get_quiz(), $this->attempt);
753
    }
754
 
755
    /**
756
     * Wrapper that the correct display_options for this quiz at the
757
     * moment.
758
     *
759
     * @param bool $reviewing true for options when reviewing, false for when attempting.
760
     * @return question_display_options the render options for this user on this attempt.
761
     */
762
    public function get_display_options($reviewing) {
763
        if ($reviewing) {
764
            if (is_null($this->reviewoptions)) {
765
                $this->reviewoptions = quiz_get_review_options($this->get_quiz(),
766
                        $this->attempt, $this->quizobj->get_context());
767
                if ($this->is_own_preview()) {
768
                    // It should  always be possible for a teacher to review their
769
                    // own preview irrespective of the review options settings.
770
                    $this->reviewoptions->attempt = true;
771
                }
772
            }
773
            return $this->reviewoptions;
774
 
775
        } else {
776
            $options = display_options::make_from_quiz($this->get_quiz(),
777
                    display_options::DURING);
778
            $options->flags = quiz_get_flag_option($this->attempt, $this->quizobj->get_context());
779
            return $options;
780
        }
781
    }
782
 
783
    /**
784
     * Wrapper that the correct display_options for this quiz at the
785
     * moment.
786
     *
787
     * @param bool $reviewing true for review page, else attempt page.
788
     * @param int $slot which question is being displayed.
789
     * @param moodle_url $thispageurl to return to after the editing form is
790
     *      submitted or cancelled. If null, no edit link will be generated.
791
     *
792
     * @return question_display_options the render options for this user on this
793
     *      attempt, with extra info to generate an edit link, if applicable.
794
     */
795
    public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) {
796
        $options = clone($this->get_display_options($reviewing));
797
 
798
        if (!$thispageurl) {
799
            return $options;
800
        }
801
 
802
        if (!($reviewing || $this->is_preview())) {
803
            return $options;
804
        }
805
 
806
        $question = $this->quba->get_question($slot, false);
807
        if (!question_has_capability_on($question, 'edit', $question->category)) {
808
            return $options;
809
        }
810
 
811
        $options->editquestionparams['cmid'] = $this->get_cmid();
812
        $options->editquestionparams['returnurl'] = $thispageurl;
813
 
814
        return $options;
815
    }
816
 
817
    /**
818
     * Is a particular page the last one in the quiz?
819
     *
820
     * @param int $page a page number
821
     * @return bool true if that is the last page of the quiz.
822
     */
823
    public function is_last_page($page) {
824
        return $page == count($this->pagelayout) - 1;
825
    }
826
 
827
    /**
828
     * Return the list of slot numbers for either a given page of the quiz, or for the
829
     * whole quiz.
830
     *
831
     * @param mixed $page string 'all' or integer page number.
832
     * @return array the requested list of slot numbers.
833
     */
834
    public function get_slots($page = 'all') {
835
        if ($page === 'all') {
836
            $numbers = [];
837
            foreach ($this->pagelayout as $numbersonpage) {
838
                $numbers = array_merge($numbers, $numbersonpage);
839
            }
840
            return $numbers;
841
        } else {
842
            return $this->pagelayout[$page];
843
        }
844
    }
845
 
846
    /**
847
     * Return the list of slot numbers for either a given page of the quiz, or for the
848
     * whole quiz.
849
     *
850
     * @param mixed $page string 'all' or integer page number.
851
     * @return array the requested list of slot numbers.
852
     */
853
    public function get_active_slots($page = 'all') {
854
        $activeslots = [];
855
        foreach ($this->get_slots($page) as $slot) {
856
            if (!$this->is_blocked_by_previous_question($slot)) {
857
                $activeslots[] = $slot;
858
            }
859
        }
860
        return $activeslots;
861
    }
862
 
863
    /**
864
     * Helper method for unit tests. Get the underlying question usage object.
865
     *
866
     * @return question_usage_by_activity the usage.
867
     */
868
    public function get_question_usage() {
869
        if (!(PHPUNIT_TEST || defined('BEHAT_TEST'))) {
870
            throw new coding_exception('get_question_usage is only for use in unit tests. ' .
871
                    'For other operations, use the quiz_attempt api, or extend it properly.');
872
        }
873
        return $this->quba;
874
    }
875
 
876
    /**
877
     * Get the question_attempt object for a particular question in this attempt.
878
     *
879
     * @param int $slot the number used to identify this question within this attempt.
880
     * @return question_attempt the requested question_attempt.
881
     */
882
    public function get_question_attempt($slot) {
883
        return $this->quba->get_question_attempt($slot);
884
    }
885
 
886
    /**
887
     * Get all the question_attempt objects that have ever appeared in a given slot.
888
     *
889
     * This relates to the 'Try another question like this one' feature.
890
     *
891
     * @param int $slot the number used to identify this question within this attempt.
892
     * @return question_attempt[] the attempts.
893
     */
894
    public function all_question_attempts_originally_in_slot($slot) {
895
        $qas = [];
896
        foreach ($this->quba->get_attempt_iterator() as $qa) {
897
            if ($qa->get_metadata('originalslot') == $slot) {
898
                $qas[] = $qa;
899
            }
900
        }
901
        $qas[] = $this->quba->get_question_attempt($slot);
902
        return $qas;
903
    }
904
 
905
    /**
906
     * Is a particular question in this attempt a real question, or something like a description.
907
     *
908
     * @param int $slot the number used to identify this question within this attempt.
909
     * @return int whether that question is a real question. Actually returns the
910
     *     question length, which could theoretically be greater than one.
911
     */
912
    public function is_real_question($slot) {
913
        return $this->quba->get_question($slot, false)->length;
914
    }
915
 
916
    /**
917
     * Is a particular question in this attempt a real question, or something like a description.
918
     *
919
     * @param int $slot the number used to identify this question within this attempt.
920
     * @return bool whether that question is a real question.
921
     */
922
    public function is_question_flagged($slot) {
923
        return $this->quba->get_question_attempt($slot)->is_flagged();
924
    }
925
 
926
    /**
927
     * Checks whether the question in this slot requires the previous
928
     * question to have been completed.
929
     *
930
     * @param int $slot the number used to identify this question within this attempt.
931
     * @return bool whether the previous question must have been completed before
932
     *      this one can be seen.
933
     */
934
    public function is_blocked_by_previous_question($slot) {
935
        return $slot > 1 && isset($this->slots[$slot]) && $this->slots[$slot]->requireprevious &&
936
            !$this->slots[$slot]->section->shufflequestions &&
937
            !$this->slots[$slot - 1]->section->shufflequestions &&
938
            $this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ &&
939
            !$this->get_question_state($slot - 1)->is_finished() &&
940
            $this->quba->can_question_finish_during_attempt($slot - 1);
941
    }
942
 
943
    /**
944
     * Is it possible for this question to be re-started within this attempt?
945
     *
946
     * @param int $slot the number used to identify this question within this attempt.
947
     * @return bool whether the student should be given the option to restart this question now.
948
     */
949
    public function can_question_be_redone_now($slot) {
950
        return $this->get_quiz()->canredoquestions && !$this->is_finished() &&
951
                $this->get_question_state($slot)->is_finished();
952
    }
953
 
954
    /**
955
     * Given a slot in this attempt, which may or not be a redone question, return the original slot.
956
     *
957
     * @param int $slot identifies a particular question in this attempt.
958
     * @return int the slot where this question was originally.
959
     */
960
    public function get_original_slot($slot) {
961
        $originalslot = $this->quba->get_question_attempt_metadata($slot, 'originalslot');
962
        if ($originalslot) {
963
            return $originalslot;
964
        } else {
965
            return $slot;
966
        }
967
    }
968
 
969
    /**
970
     * Get the displayed question number for a slot.
971
     *
972
     * @param int $slot the number used to identify this question within this attempt.
973
     * @return string the displayed question number for the question in this slot.
974
     *      For example '1', '2', '3' or 'i'.
975
     */
976
    public function get_question_number($slot): string {
977
        return $this->questionnumbers[$slot];
978
    }
979
 
980
    /**
981
     * If the section heading, if any, that should come just before this slot.
982
     *
983
     * @param int $slot identifies a particular question in this attempt.
984
     * @return string|null the required heading, or null if there is not one here.
985
     */
986
    public function get_heading_before_slot($slot) {
987
        if ($this->slots[$slot]->firstinsection) {
988
            return $this->slots[$slot]->section->heading;
989
        } else {
990
            return null;
991
        }
992
    }
993
 
994
    /**
995
     * Return the page of the quiz where this question appears.
996
     *
997
     * @param int $slot the number used to identify this question within this attempt.
998
     * @return int the page of the quiz this question appears on.
999
     */
1000
    public function get_question_page($slot) {
1001
        return $this->questionpages[$slot];
1002
    }
1003
 
1004
    /**
1005
     * Return the grade obtained on a particular question, if the user is permitted
1006
     * to see it. You must previously have called load_question_states to load the
1007
     * state data about this question.
1008
     *
1009
     * @param int $slot the number used to identify this question within this attempt.
1010
     * @return string the name of the question. Must be output through format_string.
1011
     */
1012
    public function get_question_name($slot) {
1013
        return $this->quba->get_question($slot, false)->name;
1014
    }
1015
 
1016
    /**
1017
     * Return the {@see question_state} that this question is in.
1018
     *
1019
     * @param int $slot the number used to identify this question within this attempt.
1020
     * @return question_state the state this question is in.
1021
     */
1022
    public function get_question_state($slot) {
1023
        return $this->quba->get_question_state($slot);
1024
    }
1025
 
1026
    /**
1027
     * Return the grade obtained on a particular question, if the user is permitted
1028
     * to see it. You must previously have called load_question_states to load the
1029
     * state data about this question.
1030
     *
1031
     * @param int $slot the number used to identify this question within this attempt.
1032
     * @param bool $showcorrectness Whether right/partial/wrong states should
1033
     *      be distinguished.
1034
     * @return string the formatted grade, to the number of decimal places specified
1035
     *      by the quiz.
1036
     */
1037
    public function get_question_status($slot, $showcorrectness) {
1038
        return $this->quba->get_question_state_string($slot, $showcorrectness);
1039
    }
1040
 
1041
    /**
1042
     * Return the grade obtained on a particular question, if the user is permitted
1043
     * to see it. You must previously have called load_question_states to load the
1044
     * state data about this question.
1045
     *
1046
     * @param int $slot the number used to identify this question within this attempt.
1047
     * @param bool $showcorrectness Whether right/partial/wrong states should
1048
     *      be distinguished.
1049
     * @return string class name for this state.
1050
     */
1051
    public function get_question_state_class($slot, $showcorrectness) {
1052
        return $this->quba->get_question_state_class($slot, $showcorrectness);
1053
    }
1054
 
1055
    /**
1056
     * Return the grade obtained on a particular question.
1057
     *
1058
     * You must previously have called load_question_states to load the state
1059
     * data about this question.
1060
     *
1061
     * @param int $slot the number used to identify this question within this attempt.
1062
     * @return string the formatted grade, to the number of decimal places specified by the quiz.
1063
     */
1064
    public function get_question_mark($slot) {
1065
        return quiz_format_question_grade($this->get_quiz(), $this->quba->get_question_mark($slot));
1066
    }
1067
 
1068
    /**
1069
     * Get the time of the most recent action performed on a question.
1070
     *
1071
     * @param int $slot the number used to identify this question within this usage.
1072
     * @return int timestamp.
1073
     */
1074
    public function get_question_action_time($slot) {
1075
        return $this->quba->get_question_action_time($slot);
1076
    }
1077
 
1078
    /**
1079
     * Return the question type name for a given slot within the current attempt.
1080
     *
1081
     * @param int $slot the number used to identify this question within this attempt.
1082
     * @return string the question type name.
1083
     */
1084
    public function get_question_type_name($slot) {
1085
        return $this->quba->get_question($slot, false)->get_type_name();
1086
    }
1087
 
1088
    /**
1089
     * Get the time remaining for an in-progress attempt, if the time is short
1090
     * enough that it would be worth showing a timer.
1091
     *
1092
     * @param int $timenow the time to consider as 'now'.
1093
     * @return int|false the number of seconds remaining for this attempt.
1094
     *      False if there is no limit.
1095
     */
1096
    public function get_time_left_display($timenow) {
1097
        if ($this->attempt->state != self::IN_PROGRESS) {
1098
            return false;
1099
        }
1100
        return $this->get_access_manager($timenow)->get_time_left_display($this->attempt, $timenow);
1101
    }
1102
 
1103
 
1104
    /**
1105
     * Get the time when this attempt was submitted.
1106
     *
1107
     * @return int timestamp, or 0 if it has not been submitted yet.
1108
     */
1109
    public function get_submitted_date() {
1110
        return $this->attempt->timefinish;
1111
    }
1112
 
1113
    /**
1114
     * If the attempt is in an applicable state, work out the time by which the
1115
     * student should next do something.
1116
     *
1117
     * @return int timestamp by which the student needs to do something.
1118
     */
1119
    public function get_due_date() {
1120
        $deadlines = [];
1121
        if ($this->quizobj->get_quiz()->timelimit) {
1122
            $deadlines[] = $this->attempt->timestart + $this->quizobj->get_quiz()->timelimit;
1123
        }
1124
        if ($this->quizobj->get_quiz()->timeclose) {
1125
            $deadlines[] = $this->quizobj->get_quiz()->timeclose;
1126
        }
1127
        if ($deadlines) {
1128
            $duedate = min($deadlines);
1129
        } else {
1130
            return false;
1131
        }
1132
 
1133
        switch ($this->attempt->state) {
1134
            case self::IN_PROGRESS:
1135
                return $duedate;
1136
 
1137
            case self::OVERDUE:
1138
                return $duedate + $this->quizobj->get_quiz()->graceperiod;
1139
 
1140
            default:
1141
                throw new coding_exception('Unexpected state: ' . $this->attempt->state);
1142
        }
1143
    }
1144
 
1145
    // URLs related to this attempt ============================================.
1146
 
1147
    /**
1148
     * Get the URL of this quiz's view.php page.
1149
     *
1150
     * @return moodle_url quiz view url.
1151
     */
1152
    public function view_url() {
1153
        return $this->quizobj->view_url();
1154
    }
1155
 
1156
    /**
1157
     * Get the URL to start or continue an attempt.
1158
     *
1159
     * @param int|null $slot which question in the attempt to go to after starting (optional).
1160
     * @param int $page which page in the attempt to go to after starting.
1161
     * @return moodle_url the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
1162
     */
1163
    public function start_attempt_url($slot = null, $page = -1) {
1164
        if ($page == -1 && !is_null($slot)) {
1165
            $page = $this->get_question_page($slot);
1166
        } else {
1167
            $page = 0;
1168
        }
1169
        return $this->quizobj->start_attempt_url($page);
1170
    }
1171
 
1172
    /**
1173
     * Generates the title of the attempt page.
1174
     *
1175
     * @param int $page the page number (starting with 0) in the attempt.
1176
     * @return string attempt page title.
1177
     */
1178
    public function attempt_page_title(int $page): string {
1179
        if ($this->get_num_pages() > 1) {
1180
            $a = new stdClass();
1181
            $a->name = $this->get_quiz_name();
1182
            $a->currentpage = $page + 1;
1183
            $a->totalpages = $this->get_num_pages();
1184
            $title = get_string('attempttitlepaged', 'quiz', $a);
1185
        } else {
1186
            $title = get_string('attempttitle', 'quiz', $this->get_quiz_name());
1187
        }
1188
 
1189
        return $title;
1190
    }
1191
 
1192
    /**
1193
     * Get the URL of a particular page within this attempt.
1194
     *
1195
     * @param int|null $slot if specified, the slot number of a specific question to link to.
1196
     * @param int $page if specified, a particular page to link to. If not given deduced
1197
     *      from $slot, or goes to the first page.
1198
     * @param int $thispage if not -1, the current page. Will cause links to other things on
1199
     *      this page to be output as only a fragment.
1200
     * @return moodle_url the URL to continue this attempt.
1201
     */
1202
    public function attempt_url($slot = null, $page = -1, $thispage = -1) {
1203
        return $this->page_and_question_url('attempt', $slot, $page, false, $thispage);
1204
    }
1205
 
1206
    /**
1207
     * Generates the title of the summary page.
1208
     *
1209
     * @return string summary page title.
1210
     */
1211
    public function summary_page_title(): string {
1212
        return get_string('attemptsummarytitle', 'quiz', $this->get_quiz_name());
1213
    }
1214
 
1215
    /**
1216
     * Get the URL of the summary page of this attempt.
1217
     *
1218
     * @return moodle_url the URL of this quiz's summary page.
1219
     */
1220
    public function summary_url() {
1221
        return new moodle_url('/mod/quiz/summary.php', ['attempt' => $this->attempt->id, 'cmid' => $this->get_cmid()]);
1222
    }
1223
 
1224
    /**
1225
     * Get the URL to which the attempt data should be submitted.
1226
     *
1227
     * @return moodle_url the URL of this quiz's summary page.
1228
     */
1229
    public function processattempt_url() {
1230
        return new moodle_url('/mod/quiz/processattempt.php');
1231
    }
1232
 
1233
    /**
1234
     * Generates the title of the review page.
1235
     *
1236
     * @param int $page the page number (starting with 0) in the attempt.
1237
     * @param bool $showall whether the review page contains the entire attempt on one page.
1238
     * @return string title of the review page.
1239
     */
1240
    public function review_page_title(int $page, bool $showall = false): string {
1241
        if (!$showall && $this->get_num_pages() > 1) {
1242
            $a = new stdClass();
1243
            $a->name = $this->get_quiz_name();
1244
            $a->currentpage = $page + 1;
1245
            $a->totalpages = $this->get_num_pages();
1246
            $title = get_string('attemptreviewtitlepaged', 'quiz', $a);
1247
        } else {
1248
            $title = get_string('attemptreviewtitle', 'quiz', $this->get_quiz_name());
1249
        }
1250
 
1251
        return $title;
1252
    }
1253
 
1254
    /**
1255
     * Get the URL of a particular page in the review of this attempt.
1256
     *
1257
     * @param int|null $slot indicates which question to link to.
1258
     * @param int $page if specified, the URL of this particular page of the attempt, otherwise
1259
     *      the URL will go to the first page.  If -1, deduce $page from $slot.
1260
     * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
1261
     *      and $page will be ignored. If null, a sensible default will be chosen.
1262
     * @param int $thispage if not -1, the current page. Will cause links to other things on
1263
     *      this page to be output as only a fragment.
1264
     * @return moodle_url the URL to review this attempt.
1265
     */
1266
    public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) {
1267
        return $this->page_and_question_url('review', $slot, $page, $showall, $thispage);
1268
    }
1269
 
1270
    /**
1271
     * By default, should this script show all questions on one page for this attempt?
1272
     *
1273
     * @param string $script the script name, e.g. 'attempt', 'summary', 'review'.
1274
     * @return bool whether show all on one page should be on by default.
1275
     */
1276
    public function get_default_show_all($script) {
1277
        return $script === 'review' && count($this->questionpages) < self::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL;
1278
    }
1279
 
1280
    // Bits of content =========================================================.
1281
 
1282
    /**
1283
     * If $reviewoptions->attempt is false, meaning that students can't review this
1284
     * attempt at the moment, return an appropriate string explaining why.
1285
     *
1286
     * @param bool $short if true, return a shorter string.
1287
     * @return string an appropriate message.
1288
     */
1289
    public function cannot_review_message($short = false) {
1290
        return $this->quizobj->cannot_review_message(
1291
                $this->get_attempt_state(), $short, $this->attempt->timefinish);
1292
    }
1293
 
1294
    /**
1295
     * Initialise the JS etc. required all the questions on a page.
1296
     *
1297
     * @param int|string $page a page number, or 'all'.
1298
     * @param bool $showall if true, forces page number to all.
1299
     * @return string HTML to output - mostly obsolete, will probably be an empty string.
1300
     */
1301
    public function get_html_head_contributions($page = 'all', $showall = false) {
1302
        if ($showall) {
1303
            $page = 'all';
1304
        }
1305
        $result = '';
1306
        foreach ($this->get_slots($page) as $slot) {
1307
            $result .= $this->quba->render_question_head_html($slot);
1308
        }
1309
        $result .= question_engine::initialise_js();
1310
        return $result;
1311
    }
1312
 
1313
    /**
1314
     * Initialise the JS etc. required by one question.
1315
     *
1316
     * @param int $slot the question slot number.
1317
     * @return string HTML to output - but this is mostly obsolete. Will probably be an empty string.
1318
     */
1319
    public function get_question_html_head_contributions($slot) {
1320
        return $this->quba->render_question_head_html($slot) .
1321
                question_engine::initialise_js();
1322
    }
1323
 
1324
    /**
1325
     * Print the HTML for the start new preview button, if the current user
1326
     * is allowed to see one.
1327
     *
1328
     * @return string HTML for the button.
1329
     */
1330
    public function restart_preview_button() {
1331
        global $OUTPUT;
1332
        if ($this->is_preview() && $this->is_preview_user()) {
1333
            return $OUTPUT->single_button(new moodle_url(
1334
                    $this->start_attempt_url(), ['forcenew' => true]),
1335
                    get_string('startnewpreview', 'quiz'));
1336
        } else {
1337
            return '';
1338
        }
1339
    }
1340
 
1341
    /**
1342
     * Generate the HTML that displays the question in its current state, with
1343
     * the appropriate display options.
1344
     *
1345
     * @param int $slot identifies the question in the attempt.
1346
     * @param bool $reviewing is the being printed on an attempt or a review page.
1347
     * @param renderer $renderer the quiz renderer.
1348
     * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1349
     * @return string HTML for the question in its current state.
1350
     */
1351
    public function render_question($slot, $reviewing, renderer $renderer, $thispageurl = null) {
1352
        if ($this->is_blocked_by_previous_question($slot)) {
1353
            $placeholderqa = $this->make_blocked_question_placeholder($slot);
1354
 
1355
            $displayoptions = $this->get_display_options($reviewing);
1356
            $displayoptions->manualcomment = question_display_options::HIDDEN;
1357
            $displayoptions->history = question_display_options::HIDDEN;
1358
            $displayoptions->readonly = true;
1359
            $displayoptions->versioninfo = question_display_options::HIDDEN;
1360
 
1361
            return html_writer::div($placeholderqa->render($displayoptions,
1362
                    $this->get_question_number($this->get_original_slot($slot))),
1363
                    'mod_quiz-blocked_question_warning');
1364
        }
1365
 
1366
        return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, null);
1367
    }
1368
 
1369
    /**
1370
     * Helper used by {@see render_question()} and {@see render_question_at_step()}.
1371
     *
1372
     * @param int $slot identifies the question in the attempt.
1373
     * @param bool $reviewing is the being printed on an attempt or a review page.
1374
     * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1375
     * @param renderer $renderer the quiz renderer.
1376
     * @param int|null $seq the seq number of the past state to display.
1377
     * @return string HTML fragment.
1378
     */
1379
    protected function render_question_helper($slot, $reviewing, $thispageurl,
1380
            renderer $renderer, $seq) {
1381
        $originalslot = $this->get_original_slot($slot);
1382
        $number = $this->get_question_number($originalslot);
1383
        $displayoptions = $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl);
1384
 
1385
        if ($slot != $originalslot) {
1386
            $originalmaxmark = $this->get_question_attempt($slot)->get_max_mark();
1387
            $this->get_question_attempt($slot)->set_max_mark($this->get_question_attempt($originalslot)->get_max_mark());
1388
        }
1389
 
1390
        if ($this->can_question_be_redone_now($slot)) {
1391
            $displayoptions->extrainfocontent = $renderer->redo_question_button(
1392
                    $slot, $displayoptions->readonly);
1393
        }
1394
 
1395
        if ($displayoptions->history && $displayoptions->questionreviewlink) {
1396
            $links = $this->links_to_other_redos($slot, $displayoptions->questionreviewlink);
1397
            if ($links) {
1398
                $displayoptions->extrahistorycontent = html_writer::tag('p',
1399
                        get_string('redoesofthisquestion', 'quiz', $renderer->render($links)));
1400
            }
1401
        }
1402
 
1403
        if ($seq === null) {
1404
            $output = $this->quba->render_question($slot, $displayoptions, $number);
1405
        } else {
1406
            $output = $this->quba->render_question_at_step($slot, $seq, $displayoptions, $number);
1407
        }
1408
 
1409
        if ($slot != $originalslot) {
1410
            $this->get_question_attempt($slot)->set_max_mark($originalmaxmark);
1411
        }
1412
 
1413
        return $output;
1414
    }
1415
 
1416
    /**
1417
     * Create a fake question to be displayed in place of a question that is blocked
1418
     * until the previous question has been answered.
1419
     *
1420
     * @param int $slot int slot number of the question to replace.
1421
     * @return question_attempt the placeholder question attempt.
1422
     */
1423
    protected function make_blocked_question_placeholder($slot) {
1424
        $replacedquestion = $this->get_question_attempt($slot)->get_question(false);
1425
 
1426
        question_bank::load_question_definition_classes('description');
1427
        $question = new qtype_description_question();
1428
        $question->id = $replacedquestion->id;
1429
        $question->category = null;
1430
        $question->parent = 0;
1431
        $question->qtype = question_bank::get_qtype('description');
1432
        $question->name = '';
1433
        $question->questiontext = get_string('questiondependsonprevious', 'quiz');
1434
        $question->questiontextformat = FORMAT_HTML;
1435
        $question->generalfeedback = '';
1436
        $question->defaultmark = $this->quba->get_question_max_mark($slot);
1437
        $question->length = $replacedquestion->length;
1438
        $question->penalty = 0;
1439
        $question->stamp = '';
1440
        $question->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
1441
        $question->timecreated = null;
1442
        $question->timemodified = null;
1443
        $question->createdby = null;
1444
        $question->modifiedby = null;
1445
 
1446
        $placeholderqa = new question_attempt($question, $this->quba->get_id(),
1447
                null, $this->quba->get_question_max_mark($slot));
1448
        $placeholderqa->set_slot($slot);
1449
        $placeholderqa->start($this->get_quiz()->preferredbehaviour, 1);
1450
        $placeholderqa->set_flagged($this->is_question_flagged($slot));
1451
        return $placeholderqa;
1452
    }
1453
 
1454
    /**
1455
     * Like {@see render_question()} but displays the question at the past step
1456
     * indicated by $seq, rather than showing the latest step.
1457
     *
1458
     * @param int $slot the slot number of a question in this quiz attempt.
1459
     * @param int $seq the seq number of the past state to display.
1460
     * @param bool $reviewing is the being printed on an attempt or a review page.
1461
     * @param renderer $renderer the quiz renderer.
1462
     * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1463
     * @return string HTML for the question in its current state.
1464
     */
1465
    public function render_question_at_step($slot, $seq, $reviewing,
1466
            renderer $renderer, $thispageurl = null) {
1467
        return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, $seq);
1468
    }
1469
 
1470
    /**
1471
     * Wrapper round print_question from lib/questionlib.php.
1472
     *
1473
     * @param int $slot the id of a question in this quiz attempt.
1474
     * @return string HTML of the question.
1475
     */
1476
    public function render_question_for_commenting($slot) {
1477
        $options = $this->get_display_options(true);
1478
        $options->generalfeedback = question_display_options::HIDDEN;
1479
        $options->manualcomment = question_display_options::EDITABLE;
1480
        return $this->quba->render_question($slot, $options,
1481
                $this->get_question_number($slot));
1482
    }
1483
 
1484
    /**
1485
     * Check whether access should be allowed to a particular file.
1486
     *
1487
     * @param int $slot the slot of a question in this quiz attempt.
1488
     * @param bool $reviewing is the being printed on an attempt or a review page.
1489
     * @param int $contextid the file context id from the request.
1490
     * @param string $component the file component from the request.
1491
     * @param string $filearea the file area from the request.
1492
     * @param array $args extra part components from the request.
1493
     * @param bool $forcedownload whether to force download.
1494
     * @return bool true if the file can be accessed.
1495
     */
1496
    public function check_file_access($slot, $reviewing, $contextid, $component,
1497
            $filearea, $args, $forcedownload) {
1498
        $options = $this->get_display_options($reviewing);
1499
 
1500
        // Check permissions - warning there is similar code in review.php and
1501
        // reviewquestion.php. If you change on, change them all.
1502
        if ($reviewing && $this->is_own_attempt() && !$options->attempt) {
1503
            return false;
1504
        }
1505
 
1506
        if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) {
1507
            return false;
1508
        }
1509
 
1510
        return $this->quba->check_file_access($slot, $options,
1511
                $component, $filearea, $args, $forcedownload);
1512
    }
1513
 
1514
    /**
1515
     * Get the navigation panel object for this attempt.
1516
     *
1517
     * @param renderer $output the quiz renderer to use to output things.
1518
     * @param string $panelclass The type of panel, navigation_panel_attempt::class or navigation_panel_review::class
1519
     * @param int $page the current page number.
1520
     * @param bool $showall whether we are showing the whole quiz on one page. (Used by review.php.)
1521
     * @return block_contents the requested object.
1522
     */
1523
    public function get_navigation_panel(renderer $output,
1524
             $panelclass, $page, $showall = false) {
1525
        $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall);
1526
 
1527
        $bc = new block_contents();
1528
        $bc->attributes['id'] = 'mod_quiz_navblock';
1529
        $bc->attributes['role'] = 'navigation';
1530
        $bc->title = get_string('quiznavigation', 'quiz');
1531
        $bc->content = $output->navigation_panel($panel);
1532
        return $bc;
1533
    }
1534
 
1535
    /**
1536
     * Return an array of variant URLs to other attempts at this quiz.
1537
     *
1538
     * The $url passed in must contain an attempt parameter.
1539
     *
1540
     * The {@see links_to_other_attempts} object returned contains an
1541
     * array with keys that are the attempt number, 1, 2, 3.
1542
     * The array values are either a {@see moodle_url} with the attempt parameter
1543
     * updated to point to the attempt id of the other attempt, or null corresponding
1544
     * to the current attempt number.
1545
     *
1546
     * @param moodle_url $url a URL.
1547
     * @return links_to_other_attempts|bool containing array int => null|moodle_url.
1548
     *      False if none.
1549
     */
1550
    public function links_to_other_attempts(moodle_url $url) {
1551
        $attempts = quiz_get_user_attempts($this->get_quiz()->id, $this->attempt->userid, 'all');
1552
        if (count($attempts) <= 1) {
1553
            return false;
1554
        }
1555
 
1556
        $links = new links_to_other_attempts();
1557
        foreach ($attempts as $at) {
1558
            if ($at->id == $this->attempt->id) {
1559
                $links->links[$at->attempt] = null;
1560
            } else {
1561
                $links->links[$at->attempt] = new moodle_url($url, ['attempt' => $at->id]);
1562
            }
1563
        }
1564
        return $links;
1565
    }
1566
 
1567
    /**
1568
     * Return an array of variant URLs to other redos of the question in a particular slot.
1569
     *
1570
     * The $url passed in must contain a slot parameter.
1571
     *
1572
     * The {@see links_to_other_attempts} object returned contains an
1573
     * array with keys that are the redo number, 1, 2, 3.
1574
     * The array values are either a {@see moodle_url} with the slot parameter
1575
     * updated to point to the slot that has that redo of this question; or null
1576
     * corresponding to the redo identified by $slot.
1577
     *
1578
     * @param int $slot identifies a question in this attempt.
1579
     * @param moodle_url $baseurl the base URL to modify to generate each link.
1580
     * @return links_to_other_attempts|null containing array int => null|moodle_url,
1581
     *      or null if the question in this slot has not been redone.
1582
     */
1583
    public function links_to_other_redos($slot, moodle_url $baseurl) {
1584
        $originalslot = $this->get_original_slot($slot);
1585
 
1586
        $qas = $this->all_question_attempts_originally_in_slot($originalslot);
1587
        if (count($qas) <= 1) {
1588
            return null;
1589
        }
1590
 
1591
        $links = new links_to_other_attempts();
1592
        $index = 1;
1593
        foreach ($qas as $qa) {
1594
            if ($qa->get_slot() == $slot) {
1595
                $links->links[$index] = null;
1596
            } else {
1597
                $url = new moodle_url($baseurl, ['slot' => $qa->get_slot()]);
1598
                $links->links[$index] = new action_link($url, $index,
1599
                        new popup_action('click', $url, 'reviewquestion',
1600
                                ['width' => 450, 'height' => 650]),
1601
                        ['title' => get_string('reviewresponse', 'question')]);
1602
            }
1603
            $index++;
1604
        }
1605
        return $links;
1606
    }
1607
 
1608
    // Methods for processing ==================================================.
1609
 
1610
    /**
1611
     * Check this attempt, to see if there are any state transitions that should
1612
     * happen automatically. This function will update the attempt checkstatetime.
1613
     * @param int $timestamp the timestamp that should be stored as the modified
1614
     * @param bool $studentisonline is the student currently interacting with Moodle?
1615
     */
1616
    public function handle_if_time_expired($timestamp, $studentisonline) {
1617
 
1618
        $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt);
1619
 
1620
        if ($timeclose === false || $this->is_preview()) {
1621
            $this->update_timecheckstate(null);
1622
            return; // No time limit.
1623
        }
1624
        if ($timestamp < $timeclose) {
1625
            $this->update_timecheckstate($timeclose);
1626
            return; // Time has not yet expired.
1627
        }
1628
 
1629
        // If the attempt is already overdue, look to see if it should be abandoned ...
1630
        if ($this->attempt->state == self::OVERDUE) {
1631
            $timeoverdue = $timestamp - $timeclose;
1632
            $graceperiod = $this->quizobj->get_quiz()->graceperiod;
1633
            if ($timeoverdue >= $graceperiod) {
1634
                $this->process_abandon($timestamp, $studentisonline);
1635
            } else {
1636
                // Overdue time has not yet expired.
1637
                $this->update_timecheckstate($timeclose + $graceperiod);
1638
            }
1639
            return; // ... and we are done.
1640
        }
1641
 
1642
        if ($this->attempt->state != self::IN_PROGRESS) {
1643
            $this->update_timecheckstate(null);
1644
            return; // Attempt is already in a final state.
1645
        }
1646
 
1647
        // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired.
1648
        // Transition to the appropriate state.
1649
        switch ($this->quizobj->get_quiz()->overduehandling) {
1650
            case 'autosubmit':
1651
                $this->process_finish($timestamp, false, $studentisonline ? $timestamp : $timeclose, $studentisonline);
1652
                return;
1653
 
1654
            case 'graceperiod':
1655
                $this->process_going_overdue($timestamp, $studentisonline);
1656
                return;
1657
 
1658
            case 'autoabandon':
1659
                $this->process_abandon($timestamp, $studentisonline);
1660
                return;
1661
        }
1662
 
1663
        // This is an overdue attempt with no overdue handling defined, so just abandon.
1664
        $this->process_abandon($timestamp, $studentisonline);
1665
    }
1666
 
1667
    /**
1668
     * Process all the actions that were submitted as part of the current request.
1669
     *
1670
     * @param int $timestamp the timestamp that should be stored as the modified.
1671
     *      time in the database for these actions. If null, will use the current time.
1672
     * @param bool $becomingoverdue
1673
     * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data.
1674
     *      There are two formats supported here, for historical reasons. The newer approach is to pass an array created by
1675
     *      {@see core_question_generator::get_simulated_post_data_for_questions_in_usage()}.
1676
     *      the second is to pass an array slot no => contains arrays representing student
1677
     *      responses which will be passed to {@see question_definition::prepare_simulated_post_data()}.
1678
     *      This second method will probably get deprecated one day.
1679
     */
1680
    public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) {
1681
        global $DB;
1682
 
1683
        $transaction = $DB->start_delegated_transaction();
1684
 
1685
        if ($simulatedresponses !== null) {
1686
            if (is_int(key($simulatedresponses))) {
1687
                // Legacy approach. Should be removed one day.
1688
                $simulatedpostdata = $this->quba->prepare_simulated_post_data($simulatedresponses);
1689
            } else {
1690
                $simulatedpostdata = $simulatedresponses;
1691
            }
1692
        } else {
1693
            $simulatedpostdata = null;
1694
        }
1695
 
1696
        $this->quba->process_all_actions($timestamp, $simulatedpostdata);
1697
        question_engine::save_questions_usage_by_activity($this->quba);
1698
 
1699
        $this->attempt->timemodified = $timestamp;
1700
        if ($this->attempt->state == self::FINISHED) {
1701
            $this->attempt->sumgrades = $this->quba->get_total_mark();
1702
        }
1703
        if ($becomingoverdue) {
1704
            $this->process_going_overdue($timestamp, true);
1705
        } else {
1706
            $DB->update_record('quiz_attempts', $this->attempt);
1707
        }
1708
 
1709
        if (!$this->is_preview() && $this->attempt->state == self::FINISHED) {
1710
            $this->recompute_final_grade();
1711
        }
1712
 
1713
        $transaction->allow_commit();
1714
    }
1715
 
1716
    /**
1717
     * Replace a question in an attempt with a new attempt at the same question.
1718
     *
1719
     * Well, for randomised questions, it won't be the same question, it will be
1720
     * a different randomly selected pick from the available question.
1721
     *
1722
     * @param int $slot the question to restart.
1723
     * @param int $timestamp the timestamp to record for this action.
1724
     */
1725
    public function process_redo_question($slot, $timestamp) {
1726
        global $DB;
1727
 
1728
        if (!$this->can_question_be_redone_now($slot)) {
1729
            throw new coding_exception('Attempt to restart the question in slot ' . $slot .
1730
                    ' when it is not in a state to be restarted.');
1731
        }
1732
 
1733
        $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
1734
                $this->get_quizid(), $this->get_userid(), 'all', true);
1735
 
1736
        $transaction = $DB->start_delegated_transaction();
1737
 
1738
        // Add the question to the usage. It is important we do this before we choose a variant.
1739
        $newquestionid = qbank_helper::choose_question_for_redo($this->get_quizid(),
1740
                    $this->get_quizobj()->get_context(), $this->slots[$slot]->id, $qubaids);
1741
        $newquestion = question_bank::load_question($newquestionid, $this->get_quiz()->shuffleanswers);
1742
        $newslot = $this->quba->add_question_in_place_of_other($slot, $newquestion);
1743
 
1744
        // Choose the variant.
1745
        if ($newquestion->get_num_variants() == 1) {
1746
            $variant = 1;
1747
        } else {
1748
            $variantstrategy = new \core_question\engine\variants\least_used_strategy(
1749
                    $this->quba, $qubaids);
1750
            $variant = $variantstrategy->choose_variant($newquestion->get_num_variants(),
1751
                    $newquestion->get_variants_selection_seed());
1752
        }
1753
 
1754
        // Start the question.
1755
        $this->quba->start_question($slot, $variant);
1756
        $this->quba->set_max_mark($newslot, 0);
1757
        $this->quba->set_question_attempt_metadata($newslot, 'originalslot', $slot);
1758
        question_engine::save_questions_usage_by_activity($this->quba);
1759
        $this->fire_attempt_question_restarted_event($slot, $newquestion->id);
1760
 
1761
        $transaction->allow_commit();
1762
    }
1763
 
1764
    /**
1765
     * Process all the autosaved data that was part of the current request.
1766
     *
1767
     * @param int $timestamp the timestamp that should be stored as the modified.
1768
     * time in the database for these actions. If null, will use the current time.
1769
     */
1770
    public function process_auto_save($timestamp) {
1771
        global $DB;
1772
 
1773
        $transaction = $DB->start_delegated_transaction();
1774
 
1775
        $this->quba->process_all_autosaves($timestamp);
1776
        question_engine::save_questions_usage_by_activity($this->quba);
1777
        $this->fire_attempt_autosaved_event();
1778
 
1779
        $transaction->allow_commit();
1780
    }
1781
 
1782
    /**
1783
     * Update the flagged state for all question_attempts in this usage, if their
1784
     * flagged state was changed in the request.
1785
     */
1786
    public function save_question_flags() {
1787
        global $DB;
1788
 
1789
        $transaction = $DB->start_delegated_transaction();
1790
        $this->quba->update_question_flags();
1791
        question_engine::save_questions_usage_by_activity($this->quba);
1792
        $transaction->allow_commit();
1793
    }
1794
 
1795
    /**
1796
     * Submit the attempt.
1797
     *
1798
     * The separate $timefinish argument should be used when the quiz attempt
1799
     * is being processed asynchronously (for example when cron is submitting
1800
     * attempts where the time has expired).
1801
     *
1802
     * @param int $timestamp the time to record as last modified time.
1803
     * @param bool $processsubmitted if true, and question responses in the current
1804
     *      POST request are stored to be graded, before the attempt is finished.
1805
     * @param ?int $timefinish if set, use this as the finish time for the attempt.
1806
     *      (otherwise use $timestamp as the finish time as well).
1807
     * @param bool $studentisonline is the student currently interacting with Moodle?
1808
     */
1809
    public function process_finish($timestamp, $processsubmitted, $timefinish = null, $studentisonline = false) {
1810
        global $DB;
1811
 
1812
        $transaction = $DB->start_delegated_transaction();
1813
 
1814
        if ($processsubmitted) {
1815
            $this->quba->process_all_actions($timestamp);
1816
        }
1817
        $this->quba->finish_all_questions($timestamp);
1818
 
1819
        question_engine::save_questions_usage_by_activity($this->quba);
1820
 
1821
        $originalattempt = clone $this->attempt;
1822
 
1823
        $this->attempt->timemodified = $timestamp;
1824
        $this->attempt->timefinish = $timefinish ?? $timestamp;
1825
        $this->attempt->sumgrades = $this->quba->get_total_mark();
1826
        $this->attempt->state = self::FINISHED;
1827
        $this->attempt->timecheckstate = null;
1828
        $this->attempt->gradednotificationsenttime = null;
1829
 
1830
        if (!$this->requires_manual_grading() ||
1831
                !has_capability('mod/quiz:emailnotifyattemptgraded', $this->get_quizobj()->get_context(),
1832
                        $this->get_userid())) {
1833
            $this->attempt->gradednotificationsenttime = $this->attempt->timefinish;
1834
        }
1835
 
1836
        $DB->update_record('quiz_attempts', $this->attempt);
1837
 
1838
        if (!$this->is_preview()) {
1839
            $this->recompute_final_grade();
1840
 
1841
            // Trigger event.
1842
            $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp, $studentisonline);
1843
 
1844
            di::get(hook\manager::class)->dispatch(new attempt_state_changed($originalattempt, $this->attempt));
1845
            // Tell any access rules that care that the attempt is over.
1846
            $this->get_access_manager($timestamp)->current_attempt_finished();
1847
        }
1848
 
1849
        $transaction->allow_commit();
1850
    }
1851
 
1852
    /**
1853
     * Update this attempt timecheckstate if necessary.
1854
     *
1855
     * @param int|null $time the timestamp to set.
1856
     */
1857
    public function update_timecheckstate($time) {
1858
        global $DB;
1859
        if ($this->attempt->timecheckstate !== $time) {
1860
            $this->attempt->timecheckstate = $time;
1861
            $DB->set_field('quiz_attempts', 'timecheckstate', $time, ['id' => $this->attempt->id]);
1862
        }
1863
    }
1864
 
1865
    /**
1866
     * Needs to be called after this attempt's grade is changed, to update the overall quiz grade.
1867
     */
1868
    protected function recompute_final_grade(): void {
1869
        $this->quizobj->get_grade_calculator()->recompute_final_grade($this->get_userid());
1870
    }
1871
 
1872
    /**
1873
     * Mark this attempt as now overdue.
1874
     *
1875
     * @param int $timestamp the time to deem as now.
1876
     * @param bool $studentisonline is the student currently interacting with Moodle?
1877
     */
1878
    public function process_going_overdue($timestamp, $studentisonline) {
1879
        global $DB;
1880
 
1881
        $originalattempt = clone $this->attempt;
1882
        $transaction = $DB->start_delegated_transaction();
1883
        $this->attempt->timemodified = $timestamp;
1884
        $this->attempt->state = self::OVERDUE;
1885
        // If we knew the attempt close time, we could compute when the graceperiod ends.
1886
        // Instead, we'll just fix it up through cron.
1887
        $this->attempt->timecheckstate = $timestamp;
1888
        $DB->update_record('quiz_attempts', $this->attempt);
1889
 
1890
        $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp, $studentisonline);
1891
 
1892
        di::get(hook\manager::class)->dispatch(new attempt_state_changed($originalattempt, $this->attempt));
1893
        $transaction->allow_commit();
1894
 
1895
        quiz_send_overdue_message($this);
1896
    }
1897
 
1898
    /**
1899
     * Mark this attempt as abandoned.
1900
     *
1901
     * @param int $timestamp the time to deem as now.
1902
     * @param bool $studentisonline is the student currently interacting with Moodle?
1903
     */
1904
    public function process_abandon($timestamp, $studentisonline) {
1905
        global $DB;
1906
 
1907
        $originalattempt = clone $this->attempt;
1908
        $transaction = $DB->start_delegated_transaction();
1909
        $this->attempt->timemodified = $timestamp;
1910
        $this->attempt->state = self::ABANDONED;
1911
        $this->attempt->timecheckstate = null;
1912
        $DB->update_record('quiz_attempts', $this->attempt);
1913
 
1914
        $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp, $studentisonline);
1915
 
1916
        di::get(hook\manager::class)->dispatch(new attempt_state_changed($originalattempt, $this->attempt));
1917
 
1918
        $transaction->allow_commit();
1919
    }
1920
 
1921
    /**
1922
     * This method takes an attempt in the 'Never submitted' state, and reopens it.
1923
     *
1924
     * If, for this student, time has not expired (perhaps, because an override has
1925
     * been added, then the attempt is left open. Otherwise, it is immediately submitted
1926
     * for grading.
1927
     *
1928
     * @param int $timestamp the time to deem as now.
1929
     */
1930
    public function process_reopen_abandoned($timestamp) {
1931
        global $DB;
1932
 
1933
        // Verify that things are as we expect.
1934
        if ($this->get_state() != self::ABANDONED) {
1935
            throw new coding_exception('Can only reopen an attempt that was never submitted.');
1936
        }
1937
 
1938
        $originalattempt = clone $this->attempt;
1939
        $transaction = $DB->start_delegated_transaction();
1940
        $this->attempt->timemodified = $timestamp;
1941
        $this->attempt->state = self::IN_PROGRESS;
1942
        $this->attempt->timecheckstate = null;
1943
        $DB->update_record('quiz_attempts', $this->attempt);
1944
 
1945
        $this->fire_state_transition_event('\mod_quiz\event\attempt_reopened', $timestamp, false);
1946
 
1947
        di::get(hook\manager::class)->dispatch(new attempt_state_changed($originalattempt, $this->attempt));
1948
        $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt);
1949
        if ($timeclose && $timestamp > $timeclose) {
1950
            $this->process_finish($timestamp, false, $timeclose);
1951
        }
1952
 
1953
        $transaction->allow_commit();
1954
    }
1955
 
1956
    /**
1957
     * Fire a state transition event.
1958
     *
1959
     * @param string $eventclass the event class name.
1960
     * @param int $timestamp the timestamp to include in the event.
1961
     * @param bool $studentisonline is the student currently interacting with Moodle?
1962
     */
1963
    protected function fire_state_transition_event($eventclass, $timestamp, $studentisonline) {
1964
        global $USER;
1965
        $quizrecord = $this->get_quiz();
1966
        $params = [
1967
            'context' => $this->get_quizobj()->get_context(),
1968
            'courseid' => $this->get_courseid(),
1969
            'objectid' => $this->attempt->id,
1970
            'relateduserid' => $this->attempt->userid,
1971
            'other' => [
1972
                'submitterid' => CLI_SCRIPT ? null : $USER->id,
1973
                'quizid' => $quizrecord->id,
1974
                'studentisonline' => $studentisonline
1975
            ]
1976
        ];
1977
        $event = $eventclass::create($params);
1978
        $event->add_record_snapshot('quiz', $this->get_quiz());
1979
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
1980
        $event->trigger();
1981
    }
1982
 
1983
    // Private methods =========================================================.
1984
 
1985
    /**
1986
     * Get a URL for a particular question on a particular page of the quiz.
1987
     * Used by {@see attempt_url()} and {@see review_url()}.
1988
     *
1989
     * @param string $script e.g. 'attempt' or 'review'. Used in the URL like /mod/quiz/$script.php.
1990
     * @param int $slot identifies the specific question on the page to jump to.
1991
     *      0 to just use the $page parameter.
1992
     * @param int $page -1 to look up the page number from the slot, otherwise
1993
     *      the page number to go to.
1994
     * @param bool|null $showall if true, return a URL with showall=1, and not page number.
1995
     *      if null, then an intelligent default will be chosen.
1996
     * @param int $thispage the page we are currently on. Links to questions on this
1997
     *      page will just be a fragment #q123. -1 to disable this.
1998
     * @return moodle_url The requested URL.
1999
     */
2000
    protected function page_and_question_url($script, $slot, $page, $showall, $thispage) {
2001
 
2002
        $defaultshowall = $this->get_default_show_all($script);
2003
        if ($showall === null && ($page == 0 || $page == -1)) {
2004
            $showall = $defaultshowall;
2005
        }
2006
 
2007
        // Fix up $page.
2008
        if ($page == -1) {
2009
            if ($slot !== null && !$showall) {
2010
                $page = $this->get_question_page($slot);
2011
            } else {
2012
                $page = 0;
2013
            }
2014
        }
2015
 
2016
        if ($showall) {
2017
            $page = 0;
2018
        }
2019
 
2020
        // Add a fragment to scroll down to the question.
2021
        $fragment = '';
2022
        if ($slot !== null) {
2023
            if ($slot == reset($this->pagelayout[$page]) && $thispage != $page) {
2024
                // Changing the page, go to top.
2025
                $fragment = '#';
2026
            } else {
2027
                // Link to the question container.
2028
                $qa = $this->get_question_attempt($slot);
2029
                $fragment = '#' . $qa->get_outer_question_div_unique_id();
2030
            }
2031
        }
2032
 
2033
        // Work out the correct start to the URL.
2034
        if ($thispage == $page) {
2035
            return new moodle_url($fragment);
2036
 
2037
        } else {
2038
            $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment,
2039
                    ['attempt' => $this->attempt->id, 'cmid' => $this->get_cmid()]);
2040
            if ($page == 0 && $showall != $defaultshowall) {
2041
                $url->param('showall', (int) $showall);
2042
            } else if ($page > 0) {
2043
                $url->param('page', $page);
2044
            }
2045
            return $url;
2046
        }
2047
    }
2048
 
2049
    /**
2050
     * Process responses during an attempt at a quiz.
2051
     *
2052
     * @param  int $timenow time when the processing started.
2053
     * @param  bool $finishattempt whether to finish the attempt or not.
2054
     * @param  bool $timeup true if form was submitted by timer.
2055
     * @param  int $thispage current page number.
2056
     * @return string the attempt state once the data has been processed.
2057
     * @since  Moodle 3.1
2058
     */
2059
    public function process_attempt($timenow, $finishattempt, $timeup, $thispage) {
2060
        global $DB;
2061
 
2062
        $transaction = $DB->start_delegated_transaction();
2063
 
2064
        // Get key times.
2065
        $accessmanager = $this->get_access_manager($timenow);
2066
        $timeclose = $accessmanager->get_end_time($this->get_attempt());
2067
        $graceperiodmin = get_config('quiz', 'graceperiodmin');
2068
 
2069
        // Don't enforce timeclose for previews.
2070
        if ($this->is_preview()) {
2071
            $timeclose = false;
2072
        }
2073
 
2074
        // Check where we are in relation to the end time, if there is one.
2075
        $toolate = false;
2076
        if ($timeclose !== false) {
2077
            if ($timenow > $timeclose - QUIZ_MIN_TIME_TO_CONTINUE) {
2078
                // If there is only a very small amount of time left, there is no point trying
2079
                // to show the student another page of the quiz. Just finish now.
2080
                $timeup = true;
2081
                if ($timenow > $timeclose + $graceperiodmin) {
2082
                    $toolate = true;
2083
                }
2084
            } else {
2085
                // If time is not close to expiring, then ignore the client-side timer's opinion
2086
                // about whether time has expired. This can happen if the time limit has changed
2087
                // since the student's previous interaction.
2088
                $timeup = false;
2089
            }
2090
        }
2091
 
2092
        // If time is running out, trigger the appropriate action.
2093
        $becomingoverdue = false;
2094
        $becomingabandoned = false;
2095
        if ($timeup) {
2096
            if ($this->get_quiz()->overduehandling === 'graceperiod') {
2097
                if ($timenow > $timeclose + $this->get_quiz()->graceperiod + $graceperiodmin) {
2098
                    // Grace period has run out.
2099
                    $finishattempt = true;
2100
                    $becomingabandoned = true;
2101
                } else {
2102
                    $becomingoverdue = true;
2103
                }
2104
            } else {
2105
                $finishattempt = true;
2106
            }
2107
        }
2108
 
2109
        if (!$finishattempt) {
2110
            // Just process the responses for this page and go to the next page.
2111
            if (!$toolate) {
2112
                try {
2113
                    $this->process_submitted_actions($timenow, $becomingoverdue);
2114
                    $this->fire_attempt_updated_event();
2115
                } catch (question_out_of_sequence_exception $e) {
2116
                    throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2117
                            $this->attempt_url(null, $thispage));
2118
 
2119
                } catch (Exception $e) {
2120
                    // This sucks, if we display our own custom error message, there is no way
2121
                    // to display the original stack trace.
2122
                    $debuginfo = '';
2123
                    if (!empty($e->debuginfo)) {
2124
                        $debuginfo = $e->debuginfo;
2125
                    }
2126
                    throw new moodle_exception('errorprocessingresponses', 'question',
2127
                            $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2128
                }
2129
 
2130
                if (!$becomingoverdue) {
2131
                    foreach ($this->get_slots() as $slot) {
2132
                        if (optional_param('redoslot' . $slot, false, PARAM_BOOL)) {
2133
                            $this->process_redo_question($slot, $timenow);
2134
                        }
2135
                    }
2136
                }
2137
 
2138
            } else {
2139
                // The student is too late.
2140
                $this->process_going_overdue($timenow, true);
2141
            }
2142
 
2143
            $transaction->allow_commit();
2144
 
2145
            return $becomingoverdue ? self::OVERDUE : self::IN_PROGRESS;
2146
        }
2147
 
2148
        // Update the quiz attempt record.
2149
        try {
2150
            if ($becomingabandoned) {
2151
                $this->process_abandon($timenow, true);
2152
            } else {
2153
                if (!$toolate || $this->get_quiz()->overduehandling === 'graceperiod') {
2154
                    // Normally, we record the accurate finish time when the student is online.
2155
                    $finishtime = $timenow;
2156
                } else {
2157
                    // But, if there is no grade period, and the final responses were too
2158
                    // late to be processed, record the close time, to reduce confusion.
2159
                    $finishtime = $timeclose;
2160
                }
2161
                $this->process_finish($timenow, !$toolate, $finishtime, true);
2162
            }
2163
 
2164
        } catch (question_out_of_sequence_exception $e) {
2165
            throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2166
                    $this->attempt_url(null, $thispage));
2167
 
2168
        } catch (Exception $e) {
2169
            // This sucks, if we display our own custom error message, there is no way
2170
            // to display the original stack trace.
2171
            $debuginfo = '';
2172
            if (!empty($e->debuginfo)) {
2173
                $debuginfo = $e->debuginfo;
2174
            }
2175
            throw new moodle_exception('errorprocessingresponses', 'question',
2176
                    $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2177
        }
2178
 
2179
        // Send the user to the review page.
2180
        $transaction->allow_commit();
2181
 
2182
        return $becomingabandoned ? self::ABANDONED : self::FINISHED;
2183
    }
2184
 
2185
    /**
2186
     * Check a page read access to see if is an out of sequence access.
2187
     *
2188
     * If allownext is set then we also check whether access to the page
2189
     * after the current one should be permitted.
2190
     *
2191
     * @param int $page page number.
2192
     * @param bool $allownext in case of a sequential navigation, can we go to next page ?
2193
     * @return boolean false is an out of sequence access, true otherwise.
2194
     * @since Moodle 3.1
2195
     */
2196
    public function check_page_access(int $page, bool $allownext = true): bool {
2197
        if ($this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ) {
2198
            return true;
2199
        }
2200
        // Sequential access: allow access to the summary, current page or next page.
2201
        // Or if the user review his/her attempt, see MDLQA-1523.
2202
        return $page == -1
2203
            || $page == $this->get_currentpage()
2204
            || $allownext && ($page == $this->get_currentpage() + 1);
2205
    }
2206
 
2207
    /**
2208
     * Update attempt page.
2209
     *
2210
     * @param  int $page page number.
2211
     * @return boolean true if everything was ok, false otherwise (out of sequence access).
2212
     * @since Moodle 3.1
2213
     */
2214
    public function set_currentpage($page) {
2215
        global $DB;
2216
 
2217
        if ($this->check_page_access($page)) {
2218
            $DB->set_field('quiz_attempts', 'currentpage', $page, ['id' => $this->get_attemptid()]);
2219
            return true;
2220
        }
2221
        return false;
2222
    }
2223
 
2224
    /**
2225
     * Trigger the attempt_viewed event.
2226
     *
2227
     * @since Moodle 3.1
2228
     */
2229
    public function fire_attempt_viewed_event() {
2230
        $params = [
2231
            'objectid' => $this->get_attemptid(),
2232
            'relateduserid' => $this->get_userid(),
2233
            'courseid' => $this->get_courseid(),
2234
            'context' => $this->get_context(),
2235
            'other' => [
2236
                'quizid' => $this->get_quizid(),
2237
                'page' => $this->get_currentpage()
2238
            ]
2239
        ];
2240
        $event = \mod_quiz\event\attempt_viewed::create($params);
2241
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2242
        $event->trigger();
2243
    }
2244
 
2245
    /**
2246
     * Trigger the attempt_updated event.
2247
     *
2248
     * @return void
2249
     */
2250
    public function fire_attempt_updated_event(): void {
2251
        $params = [
2252
            'objectid' => $this->get_attemptid(),
2253
            'relateduserid' => $this->get_userid(),
2254
            'courseid' => $this->get_courseid(),
2255
            'context' => $this->get_context(),
2256
            'other' => [
2257
                'quizid' => $this->get_quizid(),
2258
                'page' => $this->get_currentpage()
2259
            ]
2260
        ];
2261
        $event = \mod_quiz\event\attempt_updated::create($params);
2262
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2263
        $event->trigger();
2264
    }
2265
 
2266
    /**
2267
     * Trigger the attempt_autosaved event.
2268
     *
2269
     * @return void
2270
     */
2271
    public function fire_attempt_autosaved_event(): void {
2272
        $params = [
2273
            'objectid' => $this->get_attemptid(),
2274
            'relateduserid' => $this->get_userid(),
2275
            'courseid' => $this->get_courseid(),
2276
            'context' => $this->get_context(),
2277
            'other' => [
2278
                'quizid' => $this->get_quizid(),
2279
                'page' => $this->get_currentpage()
2280
            ]
2281
        ];
2282
        $event = \mod_quiz\event\attempt_autosaved::create($params);
2283
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2284
        $event->trigger();
2285
    }
2286
 
2287
    /**
2288
     * Trigger the attempt_question_restarted event.
2289
     *
2290
     * @param int $slot Slot number
2291
     * @param int $newquestionid New question id.
2292
     * @return void
2293
     */
2294
    public function fire_attempt_question_restarted_event(int $slot, int $newquestionid): void {
2295
        $params = [
2296
            'objectid' => $this->get_attemptid(),
2297
            'relateduserid' => $this->get_userid(),
2298
            'courseid' => $this->get_courseid(),
2299
            'context' => $this->get_context(),
2300
            'other' => [
2301
                'quizid' => $this->get_quizid(),
2302
                'page' => $this->get_currentpage(),
2303
                'slot' => $slot,
2304
                'newquestionid' => $newquestionid
2305
            ]
2306
        ];
2307
        $event = \mod_quiz\event\attempt_question_restarted::create($params);
2308
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2309
        $event->trigger();
2310
    }
2311
 
2312
    /**
2313
     * Trigger the attempt_summary_viewed event.
2314
     *
2315
     * @since Moodle 3.1
2316
     */
2317
    public function fire_attempt_summary_viewed_event() {
2318
 
2319
        $params = [
2320
            'objectid' => $this->get_attemptid(),
2321
            'relateduserid' => $this->get_userid(),
2322
            'courseid' => $this->get_courseid(),
2323
            'context' => $this->get_context(),
2324
            'other' => [
2325
                'quizid' => $this->get_quizid()
2326
            ]
2327
        ];
2328
        $event = \mod_quiz\event\attempt_summary_viewed::create($params);
2329
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2330
        $event->trigger();
2331
    }
2332
 
2333
    /**
2334
     * Trigger the attempt_reviewed event.
2335
     *
2336
     * @since Moodle 3.1
2337
     */
2338
    public function fire_attempt_reviewed_event() {
2339
 
2340
        $params = [
2341
            'objectid' => $this->get_attemptid(),
2342
            'relateduserid' => $this->get_userid(),
2343
            'courseid' => $this->get_courseid(),
2344
            'context' => $this->get_context(),
2345
            'other' => [
2346
                'quizid' => $this->get_quizid()
2347
            ]
2348
        ];
2349
        $event = \mod_quiz\event\attempt_reviewed::create($params);
2350
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2351
        $event->trigger();
2352
    }
2353
 
2354
    /**
2355
     * Trigger the attempt manual grading completed event.
2356
     */
2357
    public function fire_attempt_manual_grading_completed_event() {
2358
        $params = [
2359
            'objectid' => $this->get_attemptid(),
2360
            'relateduserid' => $this->get_userid(),
2361
            'courseid' => $this->get_courseid(),
2362
            'context' => $this->get_context(),
2363
            'other' => [
2364
                'quizid' => $this->get_quizid()
2365
            ]
2366
        ];
2367
 
2368
        $event = \mod_quiz\event\attempt_manual_grading_completed::create($params);
2369
        $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2370
        $event->trigger();
2371
    }
2372
 
2373
    /**
2374
     * Update the timemodifiedoffline attempt field.
2375
     *
2376
     * This function should be used only when web services are being used.
2377
     *
2378
     * @param int $time time stamp.
2379
     * @return boolean false if the field is not updated because web services aren't being used.
2380
     * @since Moodle 3.2
2381
     */
2382
    public function set_offline_modified_time($time) {
2383
        // Update the timemodifiedoffline field only if web services are being used.
2384
        if (WS_SERVER) {
2385
            $this->attempt->timemodifiedoffline = $time;
2386
            return true;
2387
        }
2388
        return false;
2389
    }
2390
 
2391
    /**
2392
     * Get the total number of unanswered questions in the attempt.
2393
     *
2394
     * @return int
2395
     */
2396
    public function get_number_of_unanswered_questions(): int {
2397
        $totalunanswered = 0;
2398
        foreach ($this->get_slots() as $slot) {
2399
            if (!$this->is_real_question($slot)) {
2400
                continue;
2401
            }
2402
            $questionstate = $this->get_question_state($slot);
2403
            if ($questionstate == question_state::$todo || $questionstate == question_state::$invalid) {
2404
                $totalunanswered++;
2405
            }
2406
        }
2407
        return $totalunanswered;
2408
    }
2409
 
2410
    /**
2411
     * If any questions in this attempt have changed, update the attempts.
2412
     *
2413
     * For now, this should only be done for previews.
2414
     *
2415
     * When we update the question, we keep the same question (in the case of random questions)
2416
     * and the same variant (if this question has variants). If possible, we use regrade to
2417
     * preserve any interaction that has been had with this question (e.g. a saved answer) but
2418
     * if that is not possible, we put in a newly started attempt.
2419
     */
2420
    public function update_questions_to_new_version_if_changed(): void {
2421
        global $DB;
2422
 
2423
        $versioninformation = qbank_helper::get_version_information_for_questions_in_attempt(
2424
            $this->attempt, $this->get_context());
2425
 
2426
        $anychanges = false;
2427
        foreach ($versioninformation as $slotinformation) {
2428
            if ($slotinformation->currentquestionid == $slotinformation->newquestionid) {
2429
                continue;
2430
            }
2431
 
2432
            $anychanges = true;
2433
 
2434
            $slot = $slotinformation->questionattemptslot;
2435
            $newquestion = question_bank::load_question($slotinformation->newquestionid);
2436
            if (empty($this->quba->validate_can_regrade_with_other_version($slot, $newquestion))) {
2437
                // We can use regrade to replace the question while preserving any existing state.
2438
                $finished = $this->get_attempt()->state == self::FINISHED;
2439
                $this->quba->regrade_question($slot, $finished, null, $newquestion);
2440
            } else {
2441
                // So much has changed, we have to replace the question with a new attempt.
2442
                $oldvariant = $this->get_question_attempt($slot)->get_variant();
2443
                $slot = $this->quba->add_question_in_place_of_other($slot, $newquestion, null, false);
2444
                $this->quba->start_question($slot, $oldvariant);
2445
            }
2446
        }
2447
 
2448
        if ($anychanges) {
2449
            question_engine::save_questions_usage_by_activity($this->quba);
2450
            if ($this->attempt->state == self::FINISHED) {
2451
                $this->attempt->sumgrades = $this->quba->get_total_mark();
2452
                $DB->update_record('quiz_attempts', $this->attempt);
2453
                $this->recompute_final_grade();
2454
            }
2455
        }
2456
    }
2457
}