Proyectos de Subversion Moodle

Rev

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