Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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 coding_exception;
20
use context_module;
21
use core\output\inplace_editable;
22
use mod_quiz\event\quiz_grade_item_created;
23
use mod_quiz\event\quiz_grade_item_deleted;
24
use mod_quiz\event\quiz_grade_item_updated;
25
use mod_quiz\event\slot_grade_item_updated;
26
use mod_quiz\event\slot_mark_updated;
27
use mod_quiz\question\bank\qbank_helper;
28
use mod_quiz\question\qubaids_for_quiz;
29
use stdClass;
30
 
31
/**
32
 * Quiz structure class.
33
 *
34
 * The structure of the quiz. That is, which questions it is built up
35
 * from. This is used on the Edit quiz page (edit.php) and also when
36
 * starting an attempt at the quiz (startattempt.php). Once an attempt
37
 * has been started, then the attempt holds the specific set of questions
38
 * that that student should answer, and we no longer use this class.
39
 *
40
 * @package   mod_quiz
41
 * @copyright 2014 The Open University
42
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43
 */
44
class structure {
45
    /** @var quiz_settings the quiz this is the structure of. */
46
    protected $quizobj = null;
47
 
48
    /**
49
     * @var stdClass[] the questions in this quiz. Contains the row from the questions
50
     * table, with the data from the quiz_slots table added, and also question_categories.contextid.
51
     */
52
    protected $questions = [];
53
 
54
    /** @var stdClass[] quiz_slots.slot => the quiz_slots rows for this quiz, augmented by sectionid. */
55
    protected $slotsinorder = [];
56
 
57
    /**
58
     * @var stdClass[] this quiz's data from the quiz_sections table. Each item has a ->lastslot field too.
59
     */
60
    protected $sections = [];
61
 
62
    /** @var stdClass[] quiz_grade_items for this quiz indexed by id. */
63
    protected array $gradeitems = [];
64
 
65
    /** @var bool caches the results of can_be_edited. */
66
    protected $canbeedited = null;
67
 
68
    /** @var bool caches the results of can_add_random_question. */
69
    protected $canaddrandom = null;
70
 
71
    /**
72
     * Create an instance of this class representing an empty quiz.
73
     *
74
     * @return structure
75
     */
76
    public static function create() {
77
        return new self();
78
    }
79
 
80
    /**
81
     * Create an instance of this class representing the structure of a given quiz.
82
     *
83
     * @param quiz_settings $quizobj the quiz.
84
     * @return structure
85
     */
86
    public static function create_for_quiz($quizobj) {
87
        $structure = self::create();
88
        $structure->quizobj = $quizobj;
89
        $structure->populate_structure();
90
        return $structure;
91
    }
92
 
93
    /**
94
     * Whether there are any questions in the quiz.
95
     *
96
     * @return bool true if there is at least one question in the quiz.
97
     */
98
    public function has_questions() {
99
        return !empty($this->questions);
100
    }
101
 
102
    /**
103
     * Get the number of questions in the quiz.
104
     *
105
     * @return int the number of questions in the quiz.
106
     */
107
    public function get_question_count() {
108
        return count($this->questions);
109
    }
110
 
111
    /**
112
     * Get the information about the question with this id.
113
     *
114
     * @param int $questionid The question id.
115
     * @return stdClass the data from the questions table, augmented with
116
     * question_category.contextid, and the quiz_slots data for the question in this quiz.
117
     */
118
    public function get_question_by_id($questionid) {
119
        return $this->questions[$questionid];
120
    }
121
 
122
    /**
123
     * Get the information about the question in a given slot.
124
     *
125
     * @param int $slotnumber the index of the slot in question.
126
     * @return stdClass the data from the questions table, augmented with
127
     * question_category.contextid, and the quiz_slots data for the question in this quiz.
128
     */
129
    public function get_question_in_slot($slotnumber) {
130
        return $this->questions[$this->slotsinorder[$slotnumber]->questionid];
131
    }
132
 
133
    /**
134
     * Get the name of the question in a given slot.
135
     *
136
     * @param int $slotnumber the index of the slot in question.
137
     * @return stdClass the data from the questions table, augmented with
138
     */
139
    public function get_question_name_in_slot($slotnumber) {
140
        return $this->questions[$this->slotsinorder[$slotnumber]->name];
141
    }
142
 
143
    /**
144
     * Get the displayed question number (or 'i') for a given slot.
145
     *
146
     * @param int $slotnumber the index of the slot in question.
147
     * @return string the question number ot display for this slot.
148
     */
149
    public function get_displayed_number_for_slot($slotnumber) {
150
        $slot = $this->slotsinorder[$slotnumber];
151
        return $slot->displaynumber ?? $slot->defaultnumber;
152
    }
153
 
154
    /**
155
     * Check the question has a number that could be customised.
156
     *
157
     * @param int $slotnumber
158
     * @return bool
159
     */
160
    public function can_display_number_be_customised(int $slotnumber): bool {
161
        return $this->is_real_question($slotnumber) && !quiz_has_attempts($this->quizobj->get_quizid());
162
    }
163
 
164
    /**
165
     * Check whether the question number is customised.
166
     *
167
     * @param int $slotid
168
     * @return bool
169
     * @todo MDL-76612 Final deprecation in Moodle 4.6
170
     * @deprecated since 4.2. $slot->displayednumber is no longer used. If you need this,
171
     *      use isset(...->displaynumber), but this method was not used.
172
     */
173
    public function is_display_number_customised(int $slotid): bool {
174
        $slotobj = $this->get_slot_by_id($slotid);
175
        return isset($slotobj->displaynumber);
176
    }
177
 
178
    /**
179
     * Make slot display number in place editable api call.
180
 
181
     * @param int $slotid
182
     * @param \context $context
183
     * @return \core\output\inplace_editable
184
     */
185
    public function make_slot_display_number_in_place_editable(int $slotid, \context $context): \core\output\inplace_editable {
186
        $slot = $this->get_slot_by_id($slotid);
187
        $editable = has_capability('mod/quiz:manage', $context);
188
 
189
        // Get the current value.
190
        $value = $slot->displaynumber ?? $slot->defaultnumber;
191
        $displayvalue = s($value);
192
 
193
        return new inplace_editable('mod_quiz', 'slotdisplaynumber', $slotid,
194
                $editable, $displayvalue, $value,
195
                get_string('edit_slotdisplaynumber_hint', 'mod_quiz'),
196
                get_string('edit_slotdisplaynumber_label', 'mod_quiz', $displayvalue));
197
    }
198
 
199
    /**
200
     * Get the page a given slot is on.
201
     *
202
     * @param int $slotnumber the index of the slot in question.
203
     * @return int the page number of the page that slot is on.
204
     */
205
    public function get_page_number_for_slot($slotnumber) {
206
        return $this->slotsinorder[$slotnumber]->page;
207
    }
208
 
209
    /**
210
     * Get the slot id of a given slot slot.
211
     *
212
     * @param int $slotnumber the index of the slot in question.
213
     * @return int the page number of the page that slot is on.
214
     */
215
    public function get_slot_id_for_slot($slotnumber) {
216
        return $this->slotsinorder[$slotnumber]->id;
217
    }
218
 
219
    /**
220
     * Get the question type in a given slot.
221
     *
222
     * @param int $slotnumber the index of the slot in question.
223
     * @return string the question type (e.g. multichoice).
224
     */
225
    public function get_question_type_for_slot($slotnumber) {
226
        return $this->questions[$this->slotsinorder[$slotnumber]->questionid]->qtype;
227
    }
228
 
229
    /**
230
     * Whether it would be possible, given the question types, etc. for the
231
     * question in the given slot to require that the previous question had been
232
     * answered before this one is displayed.
233
     *
234
     * @param int $slotnumber the index of the slot in question.
235
     * @return bool can this question require the previous one.
236
     */
237
    public function can_question_depend_on_previous_slot($slotnumber) {
238
        return $slotnumber > 1 && $this->can_finish_during_the_attempt($slotnumber - 1);
239
    }
240
 
241
    /**
242
     * Whether it is possible for another question to depend on this one finishing.
243
     * Note that the answer is not exact, because of random questions, and sometimes
244
     * questions cannot be depended upon because of quiz options.
245
     *
246
     * @param int $slotnumber the index of the slot in question.
247
     * @return bool can this question finish naturally during the attempt?
248
     */
249
    public function can_finish_during_the_attempt($slotnumber) {
250
        if ($this->quizobj->get_navigation_method() == QUIZ_NAVMETHOD_SEQ) {
251
            return false;
252
        }
253
 
254
        if ($this->slotsinorder[$slotnumber]->section->shufflequestions) {
255
            return false;
256
        }
257
 
258
        if (in_array($this->get_question_type_for_slot($slotnumber), ['random', 'missingtype'])) {
259
            return \question_engine::can_questions_finish_during_the_attempt(
260
                    $this->quizobj->get_quiz()->preferredbehaviour);
261
        }
262
 
263
        if (isset($this->slotsinorder[$slotnumber]->canfinish)) {
264
            return $this->slotsinorder[$slotnumber]->canfinish;
265
        }
266
 
267
        try {
268
            $quba = \question_engine::make_questions_usage_by_activity('mod_quiz', $this->quizobj->get_context());
269
            $tempslot = $quba->add_question(\question_bank::load_question(
270
                    $this->slotsinorder[$slotnumber]->questionid));
271
            $quba->set_preferred_behaviour($this->quizobj->get_quiz()->preferredbehaviour);
272
            $quba->start_all_questions();
273
 
274
            $this->slotsinorder[$slotnumber]->canfinish = $quba->can_question_finish_during_attempt($tempslot);
275
            return $this->slotsinorder[$slotnumber]->canfinish;
276
        } catch (\Exception $e) {
277
            // If the question fails to start, this should not block editing.
278
            return false;
279
        }
280
    }
281
 
282
    /**
283
     * Whether it would be possible, given the question types, etc. for the
284
     * question in the given slot to require that the previous question had been
285
     * answered before this one is displayed.
286
     *
287
     * @param int $slotnumber the index of the slot in question.
288
     * @return bool can this question require the previous one.
289
     */
290
    public function is_question_dependent_on_previous_slot($slotnumber) {
291
        return $this->slotsinorder[$slotnumber]->requireprevious;
292
    }
293
 
294
    /**
295
     * Is a particular question in this attempt a real question, or something like a description.
296
     *
297
     * @param int $slotnumber the index of the slot in question.
298
     * @return bool whether that question is a real question.
299
     */
300
    public function is_real_question($slotnumber) {
301
        return $this->get_question_in_slot($slotnumber)->length != 0;
302
    }
303
 
304
    /**
305
     * Does the current user have '...use' capability over the question(s) in a given slot?
306
     *
307
     *
308
     * @param int $slotnumber the index of the slot in question.
309
     * @return bool true if they have the required capability.
310
     */
311
    public function has_use_capability(int $slotnumber): bool {
312
        $slot = $this->slotsinorder[$slotnumber];
313
        if (is_numeric($slot->questionid)) {
314
            // Non-random question.
315
            return question_has_capability_on($this->get_question_by_id($slot->questionid), 'use');
316
        } else {
317
            // Random question.
318
            $context = \context::instance_by_id($slot->contextid);
319
            return has_capability('moodle/question:useall', $context);
320
        }
321
    }
322
 
323
    /**
324
     * Get the course id that the quiz belongs to.
325
     *
326
     * @return int the course.id for the quiz.
327
     */
328
    public function get_courseid() {
329
        return $this->quizobj->get_courseid();
330
    }
331
 
332
    /**
333
     * Get the course module id of the quiz.
334
     *
335
     * @return int the course_modules.id for the quiz.
336
     */
337
    public function get_cmid() {
338
        return $this->quizobj->get_cmid();
339
    }
340
 
341
    /**
342
     * Get the quiz context.
343
     *
344
     * @return context_module the context of the quiz that this is the structure of.
345
     */
346
    public function get_context(): context_module {
347
        return $this->quizobj->get_context();
348
    }
349
 
350
    /**
351
     * Get id of the quiz.
352
     *
353
     * @return int the quiz.id for the quiz.
354
     */
355
    public function get_quizid() {
356
        return $this->quizobj->get_quizid();
357
    }
358
 
359
    /**
360
     * Get the quiz object.
361
     *
362
     * @return stdClass the quiz settings row from the database.
363
     */
364
    public function get_quiz() {
365
        return $this->quizobj->get_quiz();
366
    }
367
 
368
    /**
369
     * Quizzes can only be repaginated if they have not been attempted, the
370
     * questions are not shuffled, and there are two or more questions.
371
     *
372
     * @return bool whether this quiz can be repaginated.
373
     */
374
    public function can_be_repaginated() {
375
        return $this->can_be_edited() && $this->get_question_count() >= 2;
376
    }
377
 
378
    /**
379
     * Quizzes can only be edited if they have not been attempted.
380
     *
381
     * @return bool whether the quiz can be edited.
382
     */
383
    public function can_be_edited() {
384
        if ($this->canbeedited === null) {
385
            $this->canbeedited = !quiz_has_attempts($this->quizobj->get_quizid());
386
        }
387
        return $this->canbeedited;
388
    }
389
 
390
    /**
391
     * This quiz can only be edited if they have not been attempted.
392
     * Throw an exception if this is not the case.
393
     */
394
    public function check_can_be_edited() {
395
        if (!$this->can_be_edited()) {
396
            $reportlink = quiz_attempt_summary_link_to_reports($this->get_quiz(),
397
                    $this->quizobj->get_cm(), $this->quizobj->get_context());
398
            throw new \moodle_exception('cannoteditafterattempts', 'quiz',
399
                    new \moodle_url('/mod/quiz/edit.php', ['cmid' => $this->get_cmid()]), $reportlink);
400
        }
401
    }
402
 
403
    /**
404
     * How many questions are allowed per page in the quiz.
405
     * This setting controls how frequently extra page-breaks should be inserted
406
     * automatically when questions are added to the quiz.
407
     *
408
     * @return int the number of questions that should be on each page of the
409
     * quiz by default.
410
     */
411
    public function get_questions_per_page() {
412
        return $this->quizobj->get_quiz()->questionsperpage;
413
    }
414
 
415
    /**
416
     * Get quiz slots.
417
     *
418
     * @return stdClass[] the slots in this quiz.
419
     */
420
    public function get_slots() {
421
        return array_column($this->slotsinorder, null, 'id');
422
    }
423
 
424
    /**
425
     * Is this slot the first one on its page?
426
     *
427
     * @param int $slotnumber the index of the slot in question.
428
     * @return bool whether this slot the first one on its page.
429
     */
430
    public function is_first_slot_on_page($slotnumber) {
431
        if ($slotnumber == 1) {
432
            return true;
433
        }
434
        return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber - 1]->page;
435
    }
436
 
437
    /**
438
     * Is this slot the last one on its page?
439
     *
440
     * @param int $slotnumber the index of the slot in question.
441
     * @return bool whether this slot the last one on its page.
442
     */
443
    public function is_last_slot_on_page($slotnumber) {
444
        if (!isset($this->slotsinorder[$slotnumber + 1])) {
445
            return true;
446
        }
447
        return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber + 1]->page;
448
    }
449
 
450
    /**
451
     * Is this slot the last one in its section?
452
     *
453
     * @param int $slotnumber the index of the slot in question.
454
     * @return bool whether this slot the last one on its section.
455
     */
456
    public function is_last_slot_in_section($slotnumber) {
457
        return $slotnumber == $this->slotsinorder[$slotnumber]->section->lastslot;
458
    }
459
 
460
    /**
461
     * Is this slot the only one in its section?
462
     *
463
     * @param int $slotnumber the index of the slot in question.
464
     * @return bool whether this slot the only one on its section.
465
     */
466
    public function is_only_slot_in_section($slotnumber) {
467
        return $this->slotsinorder[$slotnumber]->section->firstslot ==
468
                $this->slotsinorder[$slotnumber]->section->lastslot;
469
    }
470
 
471
    /**
472
     * Is this slot the last one in the quiz?
473
     *
474
     * @param int $slotnumber the index of the slot in question.
475
     * @return bool whether this slot the last one in the quiz.
476
     */
477
    public function is_last_slot_in_quiz($slotnumber) {
478
        end($this->slotsinorder);
479
        return $slotnumber == key($this->slotsinorder);
480
    }
481
 
482
    /**
483
     * Is this the first section in the quiz?
484
     *
485
     * @param stdClass $section the quiz_sections row.
486
     * @return bool whether this is first section in the quiz.
487
     */
488
    public function is_first_section($section) {
489
        return $section->firstslot == 1;
490
    }
491
 
492
    /**
493
     * Is this the last section in the quiz?
494
     *
495
     * @param stdClass $section the quiz_sections row.
496
     * @return bool whether this is first section in the quiz.
497
     */
498
    public function is_last_section($section) {
499
        return $section->id == end($this->sections)->id;
500
    }
501
 
502
    /**
503
     * Does this section only contain one slot?
504
     *
505
     * @param stdClass $section the quiz_sections row.
506
     * @return bool whether this section contains only one slot.
507
     */
508
    public function is_only_one_slot_in_section($section) {
509
        return $section->firstslot == $section->lastslot;
510
    }
511
 
512
    /**
513
     * Get the final slot in the quiz.
514
     *
515
     * @return stdClass the quiz_slots for the final slot in the quiz.
516
     */
517
    public function get_last_slot() {
518
        return end($this->slotsinorder);
519
    }
520
 
521
    /**
522
     * Get a slot by its id. Throws an exception if it is missing.
523
     *
524
     * @param int $slotid the slot id.
525
     * @return stdClass the requested quiz_slots row.
526
     */
527
    public function get_slot_by_id($slotid) {
528
        foreach ($this->slotsinorder as $slot) {
529
            if ($slot->id == $slotid) {
530
                return $slot;
531
            }
532
        }
533
 
534
        throw new coding_exception('The slot with id ' . $slotid .
535
                ' could not be found in the quiz with id ' . $this->get_quizid() . '.');
536
    }
537
 
538
    /**
539
     * Get a slot by its slot number. Throws an exception if it is missing.
540
     *
541
     * @param int $slotnumber The slot number
542
     * @return stdClass
543
     * @throws coding_exception
544
     */
545
    public function get_slot_by_number($slotnumber) {
546
        if (!array_key_exists($slotnumber, $this->slotsinorder)) {
547
            throw new coding_exception('The \'slotnumber\' could not be found.');
548
        }
549
        return $this->slotsinorder[$slotnumber];
550
    }
551
 
552
    /**
553
     * Check whether adding a section heading is possible
554
     *
555
     * @param int $pagenumber the number of the page.
556
     * @return boolean
557
     */
558
    public function can_add_section_heading($pagenumber) {
559
        // There is a default section heading on this page,
560
        // do not show adding new section heading in the Add menu.
561
        if ($pagenumber == 1) {
562
            return false;
563
        }
564
        // Get an array of firstslots.
565
        $firstslots = [];
566
        foreach ($this->sections as $section) {
567
            $firstslots[] = $section->firstslot;
568
        }
569
        foreach ($this->slotsinorder as $slot) {
570
            if ($slot->page == $pagenumber) {
571
                if (in_array($slot->slot, $firstslots)) {
572
                    return false;
573
                }
574
            }
575
        }
576
        // Do not show the adding section heading on the last add menu.
577
        if ($pagenumber == 0) {
578
            return false;
579
        }
580
        return true;
581
    }
582
 
583
    /**
584
     * Get all the slots in a section of the quiz.
585
     *
586
     * @param int $sectionid the section id.
587
     * @return int[] slot numbers.
588
     */
589
    public function get_slots_in_section($sectionid) {
590
        $slots = [];
591
        foreach ($this->slotsinorder as $slot) {
592
            if ($slot->section->id == $sectionid) {
593
                $slots[] = $slot->slot;
594
            }
595
        }
596
        return $slots;
597
    }
598
 
599
    /**
600
     * Get all the sections of the quiz.
601
     *
602
     * @return stdClass[] the sections in this quiz.
603
     */
604
    public function get_sections() {
605
        return $this->sections;
606
    }
607
 
608
    /**
609
     * Get a particular section by id.
610
     *
611
     * @return stdClass the section.
612
     */
613
    public function get_section_by_id($sectionid) {
614
        return $this->sections[$sectionid];
615
    }
616
 
617
    /**
618
     * Get the number of questions in the quiz.
619
     *
620
     * @return int the number of questions in the quiz.
621
     */
622
    public function get_section_count() {
623
        return count($this->sections);
624
    }
625
 
626
    /**
627
     * Get the overall quiz grade formatted for display.
628
     *
629
     * @return string the maximum grade for this quiz.
630
     */
631
    public function formatted_quiz_grade() {
632
        return quiz_format_grade($this->get_quiz(), $this->get_quiz()->grade);
633
    }
634
 
635
    /**
636
     * Get the maximum mark for a question, formatted for display.
637
     *
638
     * @param int $slotnumber the index of the slot in question.
639
     * @return string the maximum mark for the question in this slot.
640
     */
641
    public function formatted_question_grade($slotnumber) {
642
        return quiz_format_question_grade($this->get_quiz(), $this->slotsinorder[$slotnumber]->maxmark);
643
    }
644
 
645
    /**
646
     * Get the number of decimal places for displaying overall quiz grades or marks.
647
     *
648
     * @return int the number of decimal places.
649
     */
650
    public function get_decimal_places_for_grades() {
651
        return $this->get_quiz()->decimalpoints;
652
    }
653
 
654
    /**
655
     * Get the number of decimal places for displaying question marks.
656
     *
657
     * @return int the number of decimal places.
658
     */
659
    public function get_decimal_places_for_question_marks() {
660
        return quiz_get_grade_format($this->get_quiz());
661
    }
662
 
663
    /**
664
     * Get any warnings to show at the top of the edit page.
665
     * @return string[] array of strings.
666
     */
667
    public function get_edit_page_warnings() {
668
        $warnings = [];
669
 
670
        if (quiz_has_attempts($this->quizobj->get_quizid())) {
671
            $reviewlink = quiz_attempt_summary_link_to_reports($this->quizobj->get_quiz(),
672
                    $this->quizobj->get_cm(), $this->quizobj->get_context());
673
            $warnings[] = get_string('cannoteditafterattempts', 'quiz', $reviewlink);
674
        }
675
 
676
        return $warnings;
677
    }
678
 
679
    /**
680
     * Get the date information about the current state of the quiz.
681
     * @return string[] array of two strings. First a short summary, then a longer
682
     * explanation of the current state, e.g. for a tool-tip.
683
     */
684
    public function get_dates_summary() {
685
        $timenow = time();
686
        $quiz = $this->quizobj->get_quiz();
687
 
688
        // Exact open and close dates for the tool-tip.
689
        $dates = [];
690
        if ($quiz->timeopen > 0) {
691
            if ($timenow > $quiz->timeopen) {
692
                $dates[] = get_string('quizopenedon', 'quiz', userdate($quiz->timeopen));
693
            } else {
694
                $dates[] = get_string('quizwillopen', 'quiz', userdate($quiz->timeopen));
695
            }
696
        }
697
        if ($quiz->timeclose > 0) {
698
            if ($timenow > $quiz->timeclose) {
699
                $dates[] = get_string('quizclosed', 'quiz', userdate($quiz->timeclose));
700
            } else {
701
                $dates[] = get_string('quizcloseson', 'quiz', userdate($quiz->timeclose));
702
            }
703
        }
704
        if (empty($dates)) {
705
            $dates[] = get_string('alwaysavailable', 'quiz');
706
        }
707
        $explanation = implode(', ', $dates);
708
 
709
        // Brief summary on the page.
710
        if ($timenow < $quiz->timeopen) {
711
            $currentstatus = get_string('quizisclosedwillopen', 'quiz',
712
                    userdate($quiz->timeopen, get_string('strftimedatetimeshort', 'langconfig')));
713
        } else if ($quiz->timeclose && $timenow <= $quiz->timeclose) {
714
            $currentstatus = get_string('quizisopenwillclose', 'quiz',
715
                    userdate($quiz->timeclose, get_string('strftimedatetimeshort', 'langconfig')));
716
        } else if ($quiz->timeclose && $timenow > $quiz->timeclose) {
717
            $currentstatus = get_string('quizisclosed', 'quiz');
718
        } else {
719
            $currentstatus = get_string('quizisopen', 'quiz');
720
        }
721
 
722
        return [$currentstatus, $explanation];
723
    }
724
 
725
    /**
726
     * Set up this class with the structure for a given quiz.
727
     */
728
    protected function populate_structure() {
729
        global $DB;
730
 
731
        $this->populate_grade_items();
732
        $slots = qbank_helper::get_question_structure($this->quizobj->get_quizid(), $this->quizobj->get_context());
733
        $this->questions = [];
734
        $this->slotsinorder = [];
735
        foreach ($slots as $slotdata) {
736
            $this->questions[$slotdata->questionid] = $slotdata;
737
 
738
            $slot = clone($slotdata);
739
            $slot->quizid = $this->quizobj->get_quizid();
740
            $this->slotsinorder[$slot->slot] = $slot;
741
        }
742
 
743
        // Get quiz sections in ascending order of the firstslot.
744
        $this->sections = $DB->get_records('quiz_sections', ['quizid' => $this->quizobj->get_quizid()], 'firstslot');
745
        $this->populate_slots_with_sections();
746
        $this->populate_question_numbers();
747
    }
748
 
749
    /**
750
     * Load the information about the grade items for this quiz.
751
     */
752
    protected function populate_grade_items(): void {
753
        global $DB;
754
        $this->gradeitems = $DB->get_records('quiz_grade_items',
755
                ['quizid' => $this->get_quizid()], 'sortorder');
756
    }
757
 
758
    /**
759
     * Fill in the section ids for each slot.
760
     */
761
    public function populate_slots_with_sections() {
762
        $sections = array_values($this->sections);
763
        foreach ($sections as $i => $section) {
764
            if (isset($sections[$i + 1])) {
765
                $section->lastslot = $sections[$i + 1]->firstslot - 1;
766
            } else {
767
                $section->lastslot = count($this->slotsinorder);
768
            }
769
            for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
770
                $this->slotsinorder[$slot]->section = $section;
771
            }
772
        }
773
    }
774
 
775
    /**
776
     * Number the questions.
777
     */
778
    protected function populate_question_numbers() {
779
        $number = 1;
780
        foreach ($this->slotsinorder as $slot) {
781
            $question = $this->questions[$slot->questionid];
782
            if ($question->length == 0) {
783
                $slot->displaynumber = null;
784
                $slot->defaultnumber = get_string('infoshort', 'quiz');
785
            } else {
786
                $slot->defaultnumber = $number;
787
            }
788
            if ($slot->displaynumber === '') {
789
                $slot->displaynumber = null;
790
            }
791
            $number += $question->length;
792
        }
793
    }
794
 
795
    /**
796
     * Get the version options to show on the 'Questions' page for a particular question.
797
     *
798
     * @param int $slotnumber which slot to get the choices for.
799
     * @return stdClass[] other versions of this question. Each object has fields versionid,
800
     *       version and selected. Array is returned most recent version first.
801
     */
802
    public function get_version_choices_for_slot(int $slotnumber): array {
803
        $slot = $this->get_slot_by_number($slotnumber);
804
 
805
        // Get all the versions which exist.
806
        $versions = qbank_helper::get_version_options($slot->questionid);
807
        $latestversion = reset($versions);
808
 
809
        // Format the choices for display.
810
        $versionoptions = [];
811
        foreach ($versions as $version) {
812
            $version->selected = $version->version === $slot->requestedversion;
813
 
814
            if ($version->version === $latestversion->version) {
815
                $version->versionvalue = get_string('questionversionlatest', 'quiz', $version->version);
816
            } else {
817
                $version->versionvalue = get_string('questionversion', 'quiz', $version->version);
818
            }
819
 
820
            $versionoptions[] = $version;
821
        }
822
 
823
        // Make a choice for 'Always latest'.
824
        $alwaysuselatest = new stdClass();
825
        $alwaysuselatest->versionid = 0;
826
        $alwaysuselatest->version = 0;
827
        $alwaysuselatest->versionvalue = get_string('alwayslatest', 'quiz');
828
        $alwaysuselatest->selected = $slot->requestedversion === null;
829
        array_unshift($versionoptions, $alwaysuselatest);
830
 
831
        return $versionoptions;
832
    }
833
 
834
    /**
835
     * Move a slot from its current location to a new location.
836
     *
837
     * After calling this method, this class will be in an invalid state, and
838
     * should be discarded if you want to manipulate the structure further.
839
     *
840
     * @param int $idmove id of slot to be moved
841
     * @param int $idmoveafter id of slot to come before slot being moved
842
     * @param int $page new page number of slot being moved
843
     */
844
    public function move_slot($idmove, $idmoveafter, $page) {
845
        global $DB;
846
 
847
        $this->check_can_be_edited();
848
 
849
        $movingslot = $this->get_slot_by_id($idmove);
850
        if (empty($movingslot)) {
851
            throw new \moodle_exception('Bad slot ID ' . $idmove);
852
        }
853
        $movingslotnumber = (int) $movingslot->slot;
854
 
855
        // Empty target slot means move slot to first.
856
        if (empty($idmoveafter)) {
857
            $moveafterslotnumber = 0;
858
        } else {
859
            $moveafterslotnumber = (int) $this->get_slot_by_id($idmoveafter)->slot;
860
        }
861
 
862
        // If the action came in as moving a slot to itself, normalise this to
863
        // moving the slot to after the previous slot.
864
        if ($moveafterslotnumber == $movingslotnumber) {
865
            $moveafterslotnumber = $moveafterslotnumber - 1;
866
        }
867
 
868
        $followingslotnumber = $moveafterslotnumber + 1;
869
        // Prevent checking against non-existence slot when already at the last slot.
870
        if ($followingslotnumber == $movingslotnumber && !$this->is_last_slot_in_quiz($followingslotnumber)) {
871
            $followingslotnumber += 1;
872
        }
873
 
874
        // Check the target page number is OK.
875
        if ($page == 0 || $page === '') {
876
            $page = 1;
877
        }
878
        if (($moveafterslotnumber > 0 && $page < $this->get_page_number_for_slot($moveafterslotnumber)) ||
879
                $page < 1) {
880
            throw new coding_exception('The target page number is too small.');
881
        } else if (!$this->is_last_slot_in_quiz($moveafterslotnumber) &&
882
                $page > $this->get_page_number_for_slot($followingslotnumber)) {
883
            throw new coding_exception('The target page number is too large.');
884
        }
885
 
886
        // Work out how things are being moved.
887
        $slotreorder = [];
888
        if ($moveafterslotnumber > $movingslotnumber) {
889
            // Moving down.
890
            $slotreorder[$movingslotnumber] = $moveafterslotnumber;
891
            for ($i = $movingslotnumber; $i < $moveafterslotnumber; $i++) {
892
                $slotreorder[$i + 1] = $i;
893
            }
894
 
895
            $headingmoveafter = $movingslotnumber;
896
            if ($this->is_last_slot_in_quiz($moveafterslotnumber) ||
897
                    $page == $this->get_page_number_for_slot($moveafterslotnumber + 1)) {
898
                // We are moving to the start of a section, so that heading needs
899
                // to be included in the ones that move up.
900
                $headingmovebefore = $moveafterslotnumber + 1;
901
            } else {
902
                $headingmovebefore = $moveafterslotnumber;
903
            }
904
            $headingmovedirection = -1;
905
 
906
        } else if ($moveafterslotnumber < $movingslotnumber - 1) {
907
            // Moving up.
908
            $slotreorder[$movingslotnumber] = $moveafterslotnumber + 1;
909
            for ($i = $moveafterslotnumber + 1; $i < $movingslotnumber; $i++) {
910
                $slotreorder[$i] = $i + 1;
911
            }
912
 
913
            if ($page == $this->get_page_number_for_slot($moveafterslotnumber + 1)) {
914
                // Moving to the start of a section, don't move that section.
915
                $headingmoveafter = $moveafterslotnumber + 1;
916
            } else {
917
                // Moving tot the end of the previous section, so move the heading down too.
918
                $headingmoveafter = $moveafterslotnumber;
919
            }
920
            $headingmovebefore = $movingslotnumber + 1;
921
            $headingmovedirection = 1;
922
        } else {
923
            // Staying in the same place, but possibly changing page/section.
924
            if ($page > $movingslot->page) {
925
                $headingmoveafter = $movingslotnumber;
926
                $headingmovebefore = $movingslotnumber + 2;
927
                $headingmovedirection = -1;
928
            } else if ($page < $movingslot->page) {
929
                $headingmoveafter = $movingslotnumber - 1;
930
                $headingmovebefore = $movingslotnumber + 1;
931
                $headingmovedirection = 1;
932
            } else {
933
                return; // Nothing to do.
934
            }
935
        }
936
 
937
        if ($this->is_only_slot_in_section($movingslotnumber)) {
938
            throw new coding_exception('You cannot remove the last slot in a section.');
939
        }
940
 
941
        $trans = $DB->start_delegated_transaction();
942
 
943
        // Slot has moved record new order.
944
        if ($slotreorder) {
945
            update_field_with_unique_index('quiz_slots', 'slot', $slotreorder,
946
                    ['quizid' => $this->get_quizid()]);
947
        }
948
 
949
        // Page has changed. Record it.
950
        if ($movingslot->page != $page) {
951
            $DB->set_field('quiz_slots', 'page', $page,
952
                    ['id' => $movingslot->id]);
953
        }
954
 
955
        // Update section fist slots.
956
        quiz_update_section_firstslots($this->get_quizid(), $headingmovedirection,
957
                $headingmoveafter, $headingmovebefore);
958
 
959
        // If any pages are now empty, remove them.
960
        $emptypages = $DB->get_fieldset_sql("
961
                SELECT DISTINCT page - 1
962
                  FROM {quiz_slots} slot
963
                 WHERE quizid = ?
964
                   AND page > 1
965
                   AND NOT EXISTS (SELECT 1 FROM {quiz_slots} WHERE quizid = ? AND page = slot.page - 1)
966
              ORDER BY page - 1 DESC
967
                ", [$this->get_quizid(), $this->get_quizid()]);
968
 
969
        foreach ($emptypages as $emptypage) {
970
            $DB->execute("
971
                    UPDATE {quiz_slots}
972
                       SET page = page - 1
973
                     WHERE quizid = ?
974
                       AND page > ?
975
                    ", [$this->get_quizid(), $emptypage]);
976
        }
977
 
978
        $trans->allow_commit();
979
 
980
        // Log slot moved event.
981
        $event = \mod_quiz\event\slot_moved::create([
982
            'context' => $this->quizobj->get_context(),
983
            'objectid' => $idmove,
984
            'other' => [
985
                'quizid' => $this->quizobj->get_quizid(),
986
                'previousslotnumber' => $movingslotnumber,
987
                'afterslotnumber' => $moveafterslotnumber,
988
                'page' => $page
989
             ]
990
        ]);
991
        $event->trigger();
992
    }
993
 
994
    /**
995
     * Refresh page numbering of quiz slots.
996
     * @param stdClass[] $slots (optional) array of slot objects.
997
     * @return stdClass[] array of slot objects.
998
     */
999
    public function refresh_page_numbers($slots = []) {
1000
        global $DB;
1001
        // Get slots ordered by page then slot.
1002
        if (!count($slots)) {
1003
            $slots = $DB->get_records('quiz_slots', ['quizid' => $this->get_quizid()], 'slot, page');
1004
        }
1005
 
1006
        // Loop slots. Start the page number at 1 and increment as required.
1007
        $pagenumbers = ['new' => 0, 'old' => 0];
1008
 
1009
        foreach ($slots as $slot) {
1010
            if ($slot->page !== $pagenumbers['old']) {
1011
                $pagenumbers['old'] = $slot->page;
1012
                ++$pagenumbers['new'];
1013
            }
1014
 
1015
            if ($pagenumbers['new'] == $slot->page) {
1016
                continue;
1017
            }
1018
            $slot->page = $pagenumbers['new'];
1019
        }
1020
 
1021
        return $slots;
1022
    }
1023
 
1024
    /**
1025
     * Refresh page numbering of quiz slots and save to the database.
1026
     *
1027
     * @return stdClass[] array of slot objects.
1028
     */
1029
    public function refresh_page_numbers_and_update_db() {
1030
        global $DB;
1031
        $this->check_can_be_edited();
1032
 
1033
        $slots = $this->refresh_page_numbers();
1034
 
1035
        // Record new page order.
1036
        foreach ($slots as $slot) {
1037
            $DB->set_field('quiz_slots', 'page', $slot->page,
1038
                    ['id' => $slot->id]);
1039
        }
1040
 
1041
        return $slots;
1042
    }
1043
 
1044
    /**
1045
     * Remove a slot from a quiz.
1046
     *
1047
     * @param int $slotnumber The number of the slot to be deleted.
1048
     * @throws coding_exception
1049
     */
1050
    public function remove_slot($slotnumber) {
1051
        global $DB;
1052
 
1053
        $this->check_can_be_edited();
1054
 
1055
        if ($this->is_only_slot_in_section($slotnumber) && $this->get_section_count() > 1) {
1056
            throw new coding_exception('You cannot remove the last slot in a section.');
1057
        }
1058
 
1059
        $slot = $DB->get_record('quiz_slots', ['quizid' => $this->get_quizid(), 'slot' => $slotnumber]);
1060
        if (!$slot) {
1061
            return;
1062
        }
1063
        $maxslot = $DB->get_field_sql('SELECT MAX(slot) FROM {quiz_slots} WHERE quizid = ?', [$this->get_quizid()]);
1064
 
1065
        $trans = $DB->start_delegated_transaction();
1066
        // Delete the reference if it is a question.
1067
        $questionreference = $DB->get_record('question_references',
1068
                ['component' => 'mod_quiz', 'questionarea' => 'slot', 'itemid' => $slot->id]);
1069
        if ($questionreference) {
1070
            $DB->delete_records('question_references', ['id' => $questionreference->id]);
1071
        }
1072
        // Delete the set reference if it is a random question.
1073
        $questionsetreference = $DB->get_record('question_set_references',
1074
                ['component' => 'mod_quiz', 'questionarea' => 'slot', 'itemid' => $slot->id]);
1075
        if ($questionsetreference) {
1076
            $DB->delete_records('question_set_references',
1077
                ['id' => $questionsetreference->id, 'component' => 'mod_quiz', 'questionarea' => 'slot']);
1078
        }
1079
        $DB->delete_records('quiz_slots', ['id' => $slot->id]);
1080
        for ($i = $slot->slot + 1; $i <= $maxslot; $i++) {
1081
            $DB->set_field('quiz_slots', 'slot', $i - 1,
1082
                    ['quizid' => $this->get_quizid(), 'slot' => $i]);
1083
            $this->slotsinorder[$i]->slot = $i - 1;
1084
            $this->slotsinorder[$i - 1] = $this->slotsinorder[$i];
1085
            unset($this->slotsinorder[$i]);
1086
        }
1087
 
1088
        quiz_update_section_firstslots($this->get_quizid(), -1, $slotnumber);
1089
        foreach ($this->sections as $key => $section) {
1090
            if ($section->firstslot > $slotnumber) {
1091
                $this->sections[$key]->firstslot--;
1092
            }
1093
        }
1094
        $this->populate_slots_with_sections();
1095
        $this->populate_question_numbers();
1096
        $this->unset_question($slot->id);
1097
 
1098
        $this->refresh_page_numbers_and_update_db();
1099
 
1100
        $trans->allow_commit();
1101
 
1102
        // Log slot deleted event.
1103
        $event = \mod_quiz\event\slot_deleted::create([
1104
            'context' => $this->quizobj->get_context(),
1105
            'objectid' => $slot->id,
1106
            'other' => [
1107
                'quizid' => $this->get_quizid(),
1108
                'slotnumber' => $slotnumber,
1109
            ]
1110
        ]);
1111
        $event->trigger();
1112
    }
1113
 
1114
    /**
1115
     * Unset the question object after deletion.
1116
     *
1117
     * @param int $slotid
1118
     */
1119
    public function unset_question($slotid) {
1120
        foreach ($this->questions as $key => $question) {
1121
            if ($question->slotid === $slotid) {
1122
                unset($this->questions[$key]);
1123
            }
1124
        }
1125
    }
1126
 
1127
    /**
1128
     * Change the max mark for a slot.
1129
     *
1130
     * Save changes to the question grades in the quiz_slots table and any
1131
     * corresponding question_attempts.
1132
     *
1133
     * It does not update 'sumgrades' in the quiz table.
1134
     *
1135
     * @param stdClass $slot row from the quiz_slots table.
1136
     * @param float $maxmark the new maxmark.
1137
     * @return bool true if the new grade is different from the old one.
1138
     */
1139
    public function update_slot_maxmark($slot, $maxmark) {
1140
        global $DB;
1141
 
1142
        if (abs($maxmark - $slot->maxmark) < 1e-7) {
1143
            // Grade has not changed. Nothing to do.
1144
            return false;
1145
        }
1146
 
1147
        $transaction = $DB->start_delegated_transaction();
1148
        $DB->set_field('quiz_slots', 'maxmark', $maxmark, ['id' => $slot->id]);
1149
        \question_engine::set_max_mark_in_attempts(new qubaids_for_quiz($slot->quizid),
1150
                $slot->slot, $maxmark);
1151
 
1152
        // Log slot mark updated event.
1153
        // We use $num + 0 as a trick to remove the useless 0 digits from decimals.
1154
        $event = slot_mark_updated::create([
1155
            'context' => $this->quizobj->get_context(),
1156
            'objectid' => $slot->id,
1157
            'other' => [
1158
                'quizid' => $this->get_quizid(),
1159
                'previousmaxmark' => $slot->maxmark + 0,
1160
                'newmaxmark' => $maxmark + 0
1161
            ]
1162
        ]);
1163
        $event->trigger();
1164
 
1165
        $this->slotsinorder[$slot->slot]->maxmark = $maxmark;
1166
 
1167
        $transaction->allow_commit();
1168
        return true;
1169
    }
1170
 
1171
    /**
1172
     * Change which grade this slot contributes to, for quizzes with multiple grades.
1173
     *
1174
     * It does not update 'sumgrades' in the quiz table. If this method returns true,
1175
     * it will be necessary to recompute all the quiz grades.
1176
     *
1177
     * @param stdClass $slot row from the quiz_slots table.
1178
     * @param int|null $gradeitemid id of the grade item this slot should contribute to. 0 or null means none.
1179
     * @return bool true if the new $gradeitemid is different from the previous one.
1180
     */
1181
    public function update_slot_grade_item(stdClass $slot, ?int $gradeitemid): bool {
1182
        global $DB;
1183
 
1184
        if ($gradeitemid === 0) {
1185
            $gradeitemid = null;
1186
        }
1187
 
1188
        if ($slot->quizgradeitemid !== null) {
1189
            // Object $slot likely comes from the database, which means int may be
1190
            // represented as a string, which breaks the next test, so fix up.
1191
            $slot->quizgradeitemid = (int) $slot->quizgradeitemid;
1192
        }
1193
 
1194
        if ($gradeitemid === $slot->quizgradeitemid) {
1195
            // Grade has not changed. Nothing to do.
1196
            return false;
1197
        }
1198
 
1199
        $transaction = $DB->start_delegated_transaction();
1200
        $DB->set_field('quiz_slots', 'quizgradeitemid', $gradeitemid, ['id' => $slot->id]);
1201
 
1202
        // Log slot mark updated event.
1203
        slot_grade_item_updated::create([
1204
            'context' => $this->quizobj->get_context(),
1205
            'objectid' => $slot->id,
1206
            'other' => [
1207
                'quizid' => $this->get_quizid(),
1208
                'previousgradeitem' => $slot->quizgradeitemid,
1209
                'newgradeitem' => $gradeitemid,
1210
            ],
1211
        ])->trigger();
1212
 
1213
        $this->slotsinorder[$slot->slot]->quizgradeitemid = $gradeitemid;
1214
 
1215
        $transaction->allow_commit();
1216
        return true;
1217
    }
1218
 
1219
    /**
1220
     * Set whether the question in a particular slot requires the previous one.
1221
     * @param int $slotid id of slot.
1222
     * @param bool $requireprevious if true, set this question to require the previous one.
1223
     */
1224
    public function update_question_dependency($slotid, $requireprevious) {
1225
        global $DB;
1226
        $DB->set_field('quiz_slots', 'requireprevious', $requireprevious, ['id' => $slotid]);
1227
 
1228
        // Log slot require previous event.
1229
        $event = \mod_quiz\event\slot_requireprevious_updated::create([
1230
            'context' => $this->quizobj->get_context(),
1231
            'objectid' => $slotid,
1232
            'other' => [
1233
                'quizid' => $this->get_quizid(),
1234
                'requireprevious' => $requireprevious ? 1 : 0
1235
            ]
1236
        ]);
1237
        $event->trigger();
1238
    }
1239
 
1240
    /**
1241
     * Update the question display number when is set as customised display number or empy string.
1242
     * When the field displaynumber is set to empty string, the automated numbering is used.
1243
     * Log the updated displatnumber field.
1244
     *
1245
     * @param int $slotid id of slot.
1246
     * @param string $displaynumber set to customised string as question number or empty string fo autonumbering.
1247
     */
1248
    public function update_slot_display_number(int $slotid, string $displaynumber): void {
1249
        global $DB;
1250
 
1251
        $DB->set_field('quiz_slots', 'displaynumber', $displaynumber, ['id' => $slotid]);
1252
        $this->populate_structure();
1253
 
1254
        // Log slot displaynumber event (customised question number).
1255
        $event = \mod_quiz\event\slot_displaynumber_updated::create([
1256
                'context' => $this->quizobj->get_context(),
1257
                'objectid' => $slotid,
1258
                'other' => [
1259
                        'quizid' => $this->get_quizid(),
1260
                        'displaynumber' => $displaynumber
1261
                ]
1262
        ]);
1263
        $event->trigger();
1264
    }
1265
 
1266
    /**
1267
     * Add/Remove a pagebreak.
1268
     *
1269
     * Save changes to the slot page relationship in the quiz_slots table and reorders the paging
1270
     * for subsequent slots.
1271
     *
1272
     * @param int $slotid id of slot which we will add/remove the page break before.
1273
     * @param int $type repaginate::LINK or repaginate::UNLINK.
1274
     * @return stdClass[] array of slot objects.
1275
     */
1276
    public function update_page_break($slotid, $type) {
1277
        global $DB;
1278
 
1279
        $this->check_can_be_edited();
1280
 
1281
        $quizslots = $DB->get_records('quiz_slots', ['quizid' => $this->get_quizid()], 'slot');
1282
        $repaginate = new repaginate($this->get_quizid(), $quizslots);
1283
        $repaginate->repaginate_slots($quizslots[$slotid]->slot, $type);
1284
        $slots = $this->refresh_page_numbers_and_update_db();
1285
 
1286
        if ($type == repaginate::LINK) {
1287
            // Log page break created event.
1288
            $event = \mod_quiz\event\page_break_deleted::create([
1289
                'context' => $this->quizobj->get_context(),
1290
                'objectid' => $slotid,
1291
                'other' => [
1292
                    'quizid' => $this->get_quizid(),
1293
                    'slotnumber' => $quizslots[$slotid]->slot
1294
                ]
1295
            ]);
1296
            $event->trigger();
1297
        } else {
1298
            // Log page deleted created event.
1299
            $event = \mod_quiz\event\page_break_created::create([
1300
                'context' => $this->quizobj->get_context(),
1301
                'objectid' => $slotid,
1302
                'other' => [
1303
                    'quizid' => $this->get_quizid(),
1304
                    'slotnumber' => $quizslots[$slotid]->slot
1305
                ]
1306
            ]);
1307
            $event->trigger();
1308
        }
1309
 
1310
        return $slots;
1311
    }
1312
 
1313
    /**
1314
     * Add a section heading on a given page and return the sectionid
1315
     * @param int $pagenumber the number of the page where the section heading begins.
1316
     * @param string|null $heading the heading to add. If not given, a default is used.
1317
     */
1318
    public function add_section_heading($pagenumber, $heading = null) {
1319
        global $DB;
1320
        $section = new stdClass();
1321
        if ($heading !== null) {
1322
            $section->heading = $heading;
1323
        } else {
1324
            $section->heading = get_string('newsectionheading', 'quiz');
1325
        }
1326
        $section->quizid = $this->get_quizid();
1327
        $slotsonpage = $DB->get_records('quiz_slots', ['quizid' => $this->get_quizid(), 'page' => $pagenumber], 'slot DESC');
1328
        $firstslot = end($slotsonpage);
1329
        $section->firstslot = $firstslot->slot;
1330
        $section->shufflequestions = 0;
1331
        $sectionid = $DB->insert_record('quiz_sections', $section);
1332
 
1333
        // Log section break created event.
1334
        $event = \mod_quiz\event\section_break_created::create([
1335
            'context' => $this->quizobj->get_context(),
1336
            'objectid' => $sectionid,
1337
            'other' => [
1338
                'quizid' => $this->get_quizid(),
1339
                'firstslotnumber' => $firstslot->slot,
1340
                'firstslotid' => $firstslot->id,
1341
                'title' => $section->heading,
1342
            ]
1343
        ]);
1344
        $event->trigger();
1345
 
1346
        return $sectionid;
1347
    }
1348
 
1349
    /**
1350
     * Change the heading for a section.
1351
     * @param int $id the id of the section to change.
1352
     * @param string $newheading the new heading for this section.
1353
     */
1354
    public function set_section_heading($id, $newheading) {
1355
        global $DB;
1356
        $section = $DB->get_record('quiz_sections', ['id' => $id], '*', MUST_EXIST);
1357
        $section->heading = $newheading;
1358
        $DB->update_record('quiz_sections', $section);
1359
 
1360
        // Log section title updated event.
1361
        $firstslot = $DB->get_record('quiz_slots', ['quizid' => $this->get_quizid(), 'slot' => $section->firstslot]);
1362
        $event = \mod_quiz\event\section_title_updated::create([
1363
            'context' => $this->quizobj->get_context(),
1364
            'objectid' => $id,
1365
            'other' => [
1366
                'quizid' => $this->get_quizid(),
1367
                'firstslotid' => $firstslot ? $firstslot->id : null,
1368
                'firstslotnumber' => $firstslot ? $firstslot->slot : null,
1369
                'newtitle' => $newheading
1370
            ]
1371
        ]);
1372
        $event->trigger();
1373
    }
1374
 
1375
    /**
1376
     * Change the shuffle setting for a section.
1377
     * @param int $id the id of the section to change.
1378
     * @param bool $shuffle whether this section should be shuffled.
1379
     */
1380
    public function set_section_shuffle($id, $shuffle) {
1381
        global $DB;
1382
        $section = $DB->get_record('quiz_sections', ['id' => $id], '*', MUST_EXIST);
1383
        $section->shufflequestions = $shuffle;
1384
        $DB->update_record('quiz_sections', $section);
1385
 
1386
        // Log section shuffle updated event.
1387
        $event = \mod_quiz\event\section_shuffle_updated::create([
1388
            'context' => $this->quizobj->get_context(),
1389
            'objectid' => $id,
1390
            'other' => [
1391
                'quizid' => $this->get_quizid(),
1392
                'firstslotnumber' => $section->firstslot,
1393
                'shuffle' => $shuffle
1394
            ]
1395
        ]);
1396
        $event->trigger();
1397
    }
1398
 
1399
    /**
1400
     * Remove the section heading with the given id
1401
     * @param int $sectionid the section to remove.
1402
     */
1403
    public function remove_section_heading($sectionid) {
1404
        global $DB;
1405
        $section = $DB->get_record('quiz_sections', ['id' => $sectionid], '*', MUST_EXIST);
1406
        if ($section->firstslot == 1) {
1407
            throw new coding_exception('Cannot remove the first section in a quiz.');
1408
        }
1409
        $DB->delete_records('quiz_sections', ['id' => $sectionid]);
1410
 
1411
        // Log page deleted created event.
1412
        $firstslot = $DB->get_record('quiz_slots', ['quizid' => $this->get_quizid(), 'slot' => $section->firstslot]);
1413
        $event = \mod_quiz\event\section_break_deleted::create([
1414
            'context' => $this->quizobj->get_context(),
1415
            'objectid' => $sectionid,
1416
            'other' => [
1417
                'quizid' => $this->get_quizid(),
1418
                'firstslotid' => $firstslot->id,
1419
                'firstslotnumber' => $firstslot->slot
1420
            ]
1421
        ]);
1422
        $event->trigger();
1423
    }
1424
 
1425
    /**
1426
     * Whether the current user can add random questions to the quiz or not.
1427
     * It is only possible to add a random question if the user has the moodle/question:useall capability
1428
     * on at least one of the contexts related to the one where we are currently editing questions.
1429
     *
1430
     * @return bool
1431
     */
1432
    public function can_add_random_questions() {
1433
        if ($this->canaddrandom === null) {
1434
            $quizcontext = $this->quizobj->get_context();
1435
            $relatedcontexts = new \core_question\local\bank\question_edit_contexts($quizcontext);
1436
            $usablecontexts = $relatedcontexts->having_cap('moodle/question:useall');
1437
 
1438
            $this->canaddrandom = !empty($usablecontexts);
1439
        }
1440
 
1441
        return $this->canaddrandom;
1442
    }
1443
 
1444
    /**
1445
     * Get the grade items defined for this quiz.
1446
     *
1447
     * @return stdClass[] quiz_grade_item rows, indexed by id.
1448
     */
1449
    public function get_grade_items(): array {
1450
        return $this->gradeitems;
1451
    }
1452
 
1453
    /**
1454
     * Check the grade item with the given id belongs to this quiz.
1455
     *
1456
     * @param int $gradeitemid id of a quiz grade item.
1457
     * @throws coding_exception if the grade item does not belong to this quiz.
1458
     */
1459
    public function verify_grade_item_is_ours(int $gradeitemid): void {
1460
        if (!array_key_exists($gradeitemid, $this->gradeitems)) {
1461
            throw new coding_exception('Grade item ' . $gradeitemid .
1462
                    ' does not belong to quiz ' . $this->get_quizid());
1463
        }
1464
    }
1465
 
1466
    /**
1467
     * Is a particular quiz grade item used by any slots?
1468
     *
1469
     * @param int $gradeitemid id of a quiz grade item belonging to this quiz.
1470
     * @return bool true if it is used.
1471
     */
1472
    public function is_grade_item_used(int $gradeitemid): bool {
1473
        $this->verify_grade_item_is_ours($gradeitemid);
1474
 
1475
        foreach ($this->slotsinorder as $slot) {
1476
            if ($slot->quizgradeitemid == $gradeitemid) {
1477
                return true;
1478
            }
1479
        }
1480
        return false;
1481
    }
1482
 
1483
    /**
1484
     * Get the total of marks of all questions assigned to this grade item, formatted for display.
1485
     *
1486
     * @param int $gradeitemid id of a quiz grade item belonging to this quiz.
1487
     * @return string total of marks of all questions assigned to this grade item.
1488
     */
1489
    public function formatted_grade_item_sum_marks(int $gradeitemid): string {
1490
        $this->verify_grade_item_is_ours($gradeitemid);
1491
 
1492
        $summarks = 0;
1493
        foreach ($this->slotsinorder as $slot) {
1494
            if ($slot->quizgradeitemid == $gradeitemid) {
1495
                $summarks += $slot->maxmark;
1496
            }
1497
        }
1498
 
1499
        return quiz_format_grade($this->get_quiz(), $summarks);
1500
    }
1501
 
1502
    /**
1503
     * Create a grade item.
1504
     *
1505
     * The new grade item is added at the end of the order.
1506
     *
1507
     * @param stdClass $gradeitemdata must have property name - updated with the inserted data (sortorder and id).
1508
     */
1509
    public function create_grade_item(stdClass $gradeitemdata): void {
1510
        global $DB;
1511
 
1512
        // Add to the end of the sort order.
1513
        $gradeitemdata->sortorder = $DB->get_field('quiz_grade_items',
1514
                'COALESCE(MAX(sortorder) + 1, 1)',
1515
                ['quizid' => $this->get_quizid()]);
1516
 
1517
        // If name is blank, supply a default.
1518
        if ((string) $gradeitemdata->name === '') {
1519
            $count = 0;
1520
            do {
1521
                $count += 1;
1522
                $gradeitemdata->name = get_string('gradeitemdefaultname', 'quiz', $count);
1523
            } while ($DB->record_exists('quiz_grade_items',
1524
                ['quizid' => $this->get_quizid(), 'name' => $gradeitemdata->name]));
1525
        }
1526
 
1527
        $transaction = $DB->start_delegated_transaction();
1528
 
1529
        // Create the grade item.
1530
        $gradeitemdata->id = $DB->insert_record('quiz_grade_items', $gradeitemdata);
1531
        $this->gradeitems[$gradeitemdata->id] = $DB->get_record(
1532
                'quiz_grade_items', ['id' => $gradeitemdata->id]);
1533
 
1534
        // Log.
1535
        quiz_grade_item_created::create([
1536
            'context' => $this->quizobj->get_context(),
1537
            'objectid' => $gradeitemdata->id,
1538
            'other' => [
1539
                'quizid' => $this->get_quizid(),
1540
            ],
1541
        ])->trigger();
1542
 
1543
        $transaction->allow_commit();
1544
    }
1545
 
1546
    /**
1547
     * Update a grade item.
1548
     *
1549
     * @param stdClass $gradeitemdata must have properties id and name.
1550
     */
1551
    public function update_grade_item(stdClass $gradeitemdata): void {
1552
        global $DB;
1553
 
1554
        $this->verify_grade_item_is_ours($gradeitemdata->id);
1555
 
1556
        $transaction = $DB->start_delegated_transaction();
1557
 
1558
        // Update the grade item.
1559
        $DB->update_record('quiz_grade_items', $gradeitemdata);
1560
        $this->gradeitems[$gradeitemdata->id] = $DB->get_record(
1561
                'quiz_grade_items', ['id' => $gradeitemdata->id]);
1562
 
1563
        // Log.
1564
        quiz_grade_item_updated::create([
1565
            'context' => $this->quizobj->get_context(),
1566
            'objectid' => $gradeitemdata->id,
1567
            'other' => [
1568
                'quizid' => $this->get_quizid(),
1569
            ],
1570
        ])->trigger();
1571
 
1572
        $transaction->allow_commit();
1573
    }
1574
 
1575
    /**
1576
     * Delete a grade item (only if it is not used).
1577
     *
1578
     * @param int $gradeitemid id of the grade item to delete. Must belong to this quiz.
1579
     */
1580
    public function delete_grade_item(int $gradeitemid): void {
1581
        global $DB;
1582
 
1583
        if ($this->is_grade_item_used($gradeitemid)) {
1584
            throw new coding_exception('Cannot delete a quiz grade item which is used.');
1585
        }
1586
 
1587
        $transaction = $DB->start_delegated_transaction();
1588
 
1589
        $DB->delete_records('quiz_grade_items', ['id' => $gradeitemid]);
1590
        unset($this->gradeitems[$gradeitemid]);
1591
 
1592
        // Log.
1593
        quiz_grade_item_deleted::create([
1594
            'context' => $this->quizobj->get_context(),
1595
            'objectid' => $gradeitemid,
1596
            'other' => [
1597
                'quizid' => $this->get_quizid(),
1598
            ],
1599
        ])->trigger();
1600
 
1601
        $transaction->allow_commit();
1602
    }
1603
 
1604
    /**
1605
     * @deprecated since Moodle 4.0 MDL-71573
1606
     */
1607
    public function get_slot_tags_for_slot_id() {
1608
        throw new \coding_exception(__FUNCTION__ . '() has been removed.');
1609
    }
1610
 
1611
    /**
1612
     * Add a random question to the quiz at a given point.
1613
     *
1614
     * @param int $addonpage the page on which to add the question.
1615
     * @param int $number the number of random questions to add.
1616
     * @param array $filtercondition the filter condition. Must contain at least a category filter.
1617
     */
1618
    public function add_random_questions(int $addonpage, int $number, array $filtercondition): void {
1619
        global $DB;
1620
 
1621
        if (!isset($filtercondition['filter']['category'])) {
1622
            throw new \invalid_parameter_exception('$filtercondition must contain at least a category filter.');
1623
        }
1624
        $categoryid = $filtercondition['filter']['category']['values'][0];
1625
 
1626
        $category = $DB->get_record('question_categories', ['id' => $categoryid]);
1627
        if (!$category) {
1628
            new \moodle_exception('invalidcategoryid');
1629
        }
1630
 
1631
        $catcontext = \context::instance_by_id($category->contextid);
1632
        require_capability('moodle/question:useall', $catcontext);
1633
 
1634
        // Create the selected number of random questions.
1635
        for ($i = 0; $i < $number; $i++) {
1636
            // Slot data.
1637
            $randomslotdata = new stdClass();
1638
            $randomslotdata->quizid = $this->get_quizid();
1639
            $randomslotdata->usingcontextid = context_module::instance($this->get_cmid())->id;
1640
            $randomslotdata->questionscontextid = $category->contextid;
1641
            $randomslotdata->maxmark = 1;
1642
 
1643
            $randomslot = new \mod_quiz\local\structure\slot_random($randomslotdata);
1644
            $randomslot->set_quiz($this->get_quiz());
1645
            $randomslot->set_filter_condition(json_encode($filtercondition));
1646
            $randomslot->insert($addonpage);
1647
        }
1648
    }
1649
}