MDL-52791 quiz editing: handle unknown question types
[moodle.git] / mod / quiz / classes / structure.php
CommitLineData
e1a2d0d9
CC
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/**
18 * Defines the \mod_quiz\structure class.
19 *
20 * @package mod_quiz
21 * @copyright 2013 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace mod_quiz;
26defined('MOODLE_INTERNAL') || die();
27
28/**
29 * Quiz structure class.
30 *
31 * The structure of the quiz. That is, which questions it is built up
32 * from. This is used on the Edit quiz page (edit.php) and also when
33 * starting an attempt at the quiz (startattempt.php). Once an attempt
34 * has been started, then the attempt holds the specific set of questions
35 * that that student should answer, and we no longer use this class.
36 *
37 * @copyright 2014 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40class structure {
41 /** @var \quiz the quiz this is the structure of. */
42 protected $quizobj = null;
43
44 /**
45 * @var \stdClass[] the questions in this quiz. Contains the row from the questions
46 * table, with the data from the quiz_slots table added, and also question_categories.contextid.
47 */
48 protected $questions = array();
49
50 /** @var \stdClass[] quiz_slots.id => the quiz_slots rows for this quiz, agumented by sectionid. */
51 protected $slots = array();
52
53 /** @var \stdClass[] quiz_slots.slot => the quiz_slots rows for this quiz, agumented by sectionid. */
54 protected $slotsinorder = array();
55
56 /**
57 * @var \stdClass[] currently a dummy. Holds data that will match the
58 * quiz_sections, once it exists.
59 */
60 protected $sections = array();
61
62 /** @var bool caches the results of can_be_edited. */
63 protected $canbeedited = null;
64
65 /**
66 * Create an instance of this class representing an empty quiz.
67 * @return structure
68 */
69 public static function create() {
70 return new self();
71 }
72
e1a2d0d9
CC
73 /**
74 * Create an instance of this class representing the structure of a given quiz.
75 * @param \quiz $quizobj the quiz.
76 * @return structure
77 */
78 public static function create_for_quiz($quizobj) {
58413f61 79 $structure = self::create();
e1a2d0d9 80 $structure->quizobj = $quizobj;
58413f61 81 $structure->populate_structure($quizobj->get_quiz());
e1a2d0d9
CC
82 return $structure;
83 }
84
85 /**
86 * Whether there are any questions in the quiz.
87 * @return bool true if there is at least one question in the quiz.
88 */
89 public function has_questions() {
90 return !empty($this->questions);
91 }
92
93 /**
94 * Get the number of questions in the quiz.
95 * @return int the number of questions in the quiz.
96 */
97 public function get_question_count() {
98 return count($this->questions);
99 }
100
101 /**
102 * Get the information about the question with this id.
103 * @param int $questionid The question id.
104 * @return \stdClass the data from the questions table, augmented with
105 * question_category.contextid, and the quiz_slots data for the question in this quiz.
106 */
107 public function get_question_by_id($questionid) {
108 return $this->questions[$questionid];
109 }
110
111 /**
112 * Get the information about the question in a given slot.
113 * @param int $slotnumber the index of the slot in question.
114 * @return \stdClass the data from the questions table, augmented with
115 * question_category.contextid, and the quiz_slots data for the question in this quiz.
116 */
117 public function get_question_in_slot($slotnumber) {
118 return $this->questions[$this->slotsinorder[$slotnumber]->questionid];
119 }
120
441d284a
TH
121 /**
122 * Get the displayed question number (or 'i') for a given slot.
123 * @param int $slotnumber the index of the slot in question.
124 * @return string the question number ot display for this slot.
125 */
126 public function get_displayed_number_for_slot($slotnumber) {
127 return $this->slotsinorder[$slotnumber]->displayednumber;
128 }
129
130 /**
131 * Get the page a given slot is on.
132 * @param int $slotnumber the index of the slot in question.
133 * @return int the page number of the page that slot is on.
134 */
135 public function get_page_number_for_slot($slotnumber) {
136 return $this->slotsinorder[$slotnumber]->page;
137 }
138
139 /**
140 * Get the slot id of a given slot slot.
141 * @param int $slotnumber the index of the slot in question.
142 * @return int the page number of the page that slot is on.
143 */
144 public function get_slot_id_for_slot($slotnumber) {
145 return $this->slotsinorder[$slotnumber]->id;
146 }
147
148 /**
149 * Get the question type in a given slot.
150 * @param int $slotnumber the index of the slot in question.
151 * @return string the question type (e.g. multichoice).
152 */
153 public function get_question_type_for_slot($slotnumber) {
154 return $this->questions[$this->slotsinorder[$slotnumber]->questionid]->qtype;
155 }
156
157 /**
158 * Whether it would be possible, given the question types, etc. for the
159 * question in the given slot to require that the previous question had been
160 * answered before this one is displayed.
161 * @param int $slotnumber the index of the slot in question.
162 * @return bool can this question require the previous one.
163 */
164 public function can_question_depend_on_previous_slot($slotnumber) {
165 return $slotnumber > 1 && $this->can_finish_during_the_attempt($slotnumber - 1);
166 }
167
168 /**
169 * Whether it is possible for another question to depend on this one finishing.
170 * Note that the answer is not exact, because of random questions, and sometimes
171 * questions cannot be depended upon because of quiz options.
172 * @param int $slotnumber the index of the slot in question.
173 * @return bool can this question finish naturally during the attempt?
174 */
175 public function can_finish_during_the_attempt($slotnumber) {
5d949702
K
176 if ($this->quizobj->get_navigation_method() == QUIZ_NAVMETHOD_SEQ) {
177 return false;
178 }
179
180 if ($this->slotsinorder[$slotnumber]->section->shufflequestions) {
441d284a
TH
181 return false;
182 }
183
fdd62966 184 if (in_array($this->get_question_type_for_slot($slotnumber), array('random', 'missingtype'))) {
d4572c17
TH
185 return \question_engine::can_questions_finish_during_the_attempt(
186 $this->quizobj->get_quiz()->preferredbehaviour);
441d284a
TH
187 }
188
189 if (isset($this->slotsinorder[$slotnumber]->canfinish)) {
190 return $this->slotsinorder[$slotnumber]->canfinish;
191 }
192
fdd62966
TH
193 try {
194 $quba = \question_engine::make_questions_usage_by_activity('mod_quiz', $this->quizobj->get_context());
195 $tempslot = $quba->add_question(\question_bank::load_question(
196 $this->slotsinorder[$slotnumber]->questionid));
197 $quba->set_preferred_behaviour($this->quizobj->get_quiz()->preferredbehaviour);
198 $quba->start_all_questions();
441d284a 199
fdd62966
TH
200 $this->slotsinorder[$slotnumber]->canfinish = $quba->can_question_finish_during_attempt($tempslot);
201 return $this->slotsinorder[$slotnumber]->canfinish;
202 } catch (\Exception $e) {
203 // If the question fails to start, this should not block editing.
204 return false;
205 }
441d284a
TH
206 }
207
208 /**
209 * Whether it would be possible, given the question types, etc. for the
210 * question in the given slot to require that the previous question had been
211 * answered before this one is displayed.
212 * @param int $slotnumber the index of the slot in question.
213 * @return bool can this question require the previous one.
214 */
215 public function is_question_dependent_on_previous_slot($slotnumber) {
216 return $this->slotsinorder[$slotnumber]->requireprevious;
217 }
218
219 /**
220 * Is a particular question in this attempt a real question, or something like a description.
221 * @param int $slotnumber the index of the slot in question.
222 * @return bool whether that question is a real question.
223 */
224 public function is_real_question($slotnumber) {
225 return $this->get_question_in_slot($slotnumber)->length != 0;
226 }
227
228 /**
229 * Get the course id that the quiz belongs to.
230 * @return int the course.id for the quiz.
231 */
232 public function get_courseid() {
233 return $this->quizobj->get_courseid();
234 }
235
e1a2d0d9
CC
236 /**
237 * Get the course module id of the quiz.
238 * @return int the course_modules.id for the quiz.
239 */
240 public function get_cmid() {
241 return $this->quizobj->get_cmid();
242 }
243
244 /**
245 * Get id of the quiz.
246 * @return int the quiz.id for the quiz.
247 */
248 public function get_quizid() {
249 return $this->quizobj->get_quizid();
250 }
251
252 /**
253 * Get the quiz object.
254 * @return \stdClass the quiz settings row from the database.
255 */
256 public function get_quiz() {
257 return $this->quizobj->get_quiz();
258 }
259
e1a2d0d9
CC
260 /**
261 * Quizzes can only be repaginated if they have not been attempted, the
262 * questions are not shuffled, and there are two or more questions.
263 * @return bool whether this quiz can be repaginated.
264 */
265 public function can_be_repaginated() {
5d949702 266 return $this->can_be_edited() && $this->get_question_count() >= 2;
e1a2d0d9
CC
267 }
268
269 /**
270 * Quizzes can only be edited if they have not been attempted.
271 * @return bool whether the quiz can be edited.
272 */
273 public function can_be_edited() {
274 if ($this->canbeedited === null) {
275 $this->canbeedited = !quiz_has_attempts($this->quizobj->get_quizid());
276 }
277 return $this->canbeedited;
278 }
279
6870a6b8
TH
280 /**
281 * This quiz can only be edited if they have not been attempted.
282 * Throw an exception if this is not the case.
283 */
284 public function check_can_be_edited() {
285 if (!$this->can_be_edited()) {
286 $reportlink = quiz_attempt_summary_link_to_reports($this->get_quiz(),
287 $this->quizobj->get_cm(), $this->quizobj->get_context());
288 throw new \moodle_exception('cannoteditafterattempts', 'quiz',
289 new \moodle_url('/mod/quiz/edit.php', array('cmid' => $this->get_cmid())), $reportlink);
290 }
291 }
292
e1a2d0d9
CC
293 /**
294 * How many questions are allowed per page in the quiz.
295 * This setting controls how frequently extra page-breaks should be inserted
296 * automatically when questions are added to the quiz.
297 * @return int the number of questions that should be on each page of the
298 * quiz by default.
299 */
300 public function get_questions_per_page() {
301 return $this->quizobj->get_quiz()->questionsperpage;
302 }
303
304 /**
305 * Get quiz slots.
306 * @return \stdClass[] the slots in this quiz.
307 */
308 public function get_slots() {
309 return $this->slots;
310 }
311
312 /**
313 * Is this slot the first one on its page?
314 * @param int $slotnumber the index of the slot in question.
315 * @return bool whether this slot the first one on its page.
316 */
317 public function is_first_slot_on_page($slotnumber) {
318 if ($slotnumber == 1) {
319 return true;
320 }
321 return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber - 1]->page;
322 }
323
324 /**
325 * Is this slot the last one on its page?
326 * @param int $slotnumber the index of the slot in question.
327 * @return bool whether this slot the last one on its page.
328 */
329 public function is_last_slot_on_page($slotnumber) {
330 if (!isset($this->slotsinorder[$slotnumber + 1])) {
331 return true;
332 }
333 return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber + 1]->page;
334 }
335
5d949702
K
336 /**
337 * Is this slot the last one in its section?
338 * @param int $slotnumber the index of the slot in question.
339 * @return bool whether this slot the last one on its section.
340 */
341 public function is_last_slot_in_section($slotnumber) {
342 return $slotnumber == $this->slotsinorder[$slotnumber]->section->lastslot;
343 }
344
345 /**
346 * Is this slot the only one in its section?
347 * @param int $slotnumber the index of the slot in question.
348 * @return bool whether this slot the only one on its section.
349 */
350 public function is_only_slot_in_section($slotnumber) {
351 return $this->slotsinorder[$slotnumber]->section->firstslot ==
352 $this->slotsinorder[$slotnumber]->section->lastslot;
353 }
354
e1a2d0d9
CC
355 /**
356 * Is this slot the last one in the quiz?
357 * @param int $slotnumber the index of the slot in question.
358 * @return bool whether this slot the last one in the quiz.
359 */
360 public function is_last_slot_in_quiz($slotnumber) {
361 end($this->slotsinorder);
362 return $slotnumber == key($this->slotsinorder);
363 }
364
5d949702
K
365 /**
366 * Is this the first section in the quiz?
367 * @param \stdClass $section the quiz_sections row.
368 * @return bool whether this is first section in the quiz.
369 */
370 public function is_first_section($section) {
371 return $section->firstslot == 1;
372 }
373
374 /**
375 * Is this the last section in the quiz?
376 * @param \stdClass $section the quiz_sections row.
377 * @return bool whether this is first section in the quiz.
378 */
379 public function is_last_section($section) {
380 return $section->id == end($this->sections)->id;
381 }
382
383 /**
384 * Does this section only contain one slot?
385 * @param \stdClass $section the quiz_sections row.
386 * @return bool whether this section contains only one slot.
387 */
388 public function is_only_one_slot_in_section($section) {
389 return $section->firstslot == $section->lastslot;
390 }
391
e1a2d0d9
CC
392 /**
393 * Get the final slot in the quiz.
394 * @return \stdClass the quiz_slots for for the final slot in the quiz.
395 */
396 public function get_last_slot() {
397 return end($this->slotsinorder);
398 }
399
400 /**
401 * Get a slot by it's id. Throws an exception if it is missing.
402 * @param int $slotid the slot id.
403 * @return \stdClass the requested quiz_slots row.
404 */
405 public function get_slot_by_id($slotid) {
406 if (!array_key_exists($slotid, $this->slots)) {
407 throw new \coding_exception('The \'slotid\' could not be found.');
408 }
409 return $this->slots[$slotid];
410 }
411
5d949702
K
412 /**
413 * Check whether adding a section heading is possible
414 * @param int $pagenumber the number of the page.
415 * @return boolean
416 */
417 public function can_add_section_heading($pagenumber) {
418 // There is a default section heading on this page,
419 // do not show adding new section heading in the Add menu.
420 if ($pagenumber == 1) {
421 return false;
422 }
423 // Get an array of firstslots.
424 $firstslots = array();
425 foreach ($this->sections as $section) {
426 $firstslots[] = $section->firstslot;
427 }
428 foreach ($this->slotsinorder as $slot) {
429 if ($slot->page == $pagenumber) {
430 if (in_array($slot->slot, $firstslots)) {
431 return false;
432 }
433 }
434 }
435 // Do not show the adding section heading on the last add menu.
436 if ($pagenumber == 0) {
437 return false;
438 }
439 return true;
440 }
441
e1a2d0d9 442 /**
441d284a 443 * Get all the slots in a section of the quiz.
e1a2d0d9 444 * @param int $sectionid the section id.
441d284a 445 * @return int[] slot numbers.
e1a2d0d9 446 */
441d284a
TH
447 public function get_slots_in_section($sectionid) {
448 $slots = array();
e1a2d0d9 449 foreach ($this->slotsinorder as $slot) {
5d949702 450 if ($slot->section->id == $sectionid) {
441d284a 451 $slots[] = $slot->slot;
e1a2d0d9
CC
452 }
453 }
441d284a 454 return $slots;
e1a2d0d9
CC
455 }
456
457 /**
458 * Get all the sections of the quiz.
459 * @return \stdClass[] the sections in this quiz.
460 */
5d949702 461 public function get_sections() {
e1a2d0d9
CC
462 return $this->sections;
463 }
464
5d949702
K
465 /**
466 * Get a particular section by id.
467 * @return \stdClass the section.
468 */
469 public function get_section_by_id($sectionid) {
470 return $this->sections[$sectionid];
471 }
472
441d284a
TH
473 /**
474 * Get the overall quiz grade formatted for display.
475 * @return string the maximum grade for this quiz.
476 */
477 public function formatted_quiz_grade() {
478 return quiz_format_grade($this->get_quiz(), $this->get_quiz()->grade);
479 }
480
481 /**
482 * Get the maximum mark for a question, formatted for display.
483 * @param int $slotnumber the index of the slot in question.
484 * @return string the maximum mark for the question in this slot.
485 */
486 public function formatted_question_grade($slotnumber) {
487 return quiz_format_question_grade($this->get_quiz(), $this->slotsinorder[$slotnumber]->maxmark);
488 }
489
490 /**
491 * Get the number of decimal places for displyaing overall quiz grades or marks.
492 * @return int the number of decimal places.
493 */
494 public function get_decimal_places_for_grades() {
495 return $this->get_quiz()->decimalpoints;
496 }
497
498 /**
499 * Get the number of decimal places for displyaing question marks.
500 * @return int the number of decimal places.
501 */
502 public function get_decimal_places_for_question_marks() {
503 return quiz_get_grade_format($this->get_quiz());
504 }
505
e1a2d0d9
CC
506 /**
507 * Get any warnings to show at the top of the edit page.
508 * @return string[] array of strings.
509 */
510 public function get_edit_page_warnings() {
511 $warnings = array();
512
513 if (quiz_has_attempts($this->quizobj->get_quizid())) {
514 $reviewlink = quiz_attempt_summary_link_to_reports($this->quizobj->get_quiz(),
515 $this->quizobj->get_cm(), $this->quizobj->get_context());
516 $warnings[] = get_string('cannoteditafterattempts', 'quiz', $reviewlink);
517 }
518
e1a2d0d9
CC
519 return $warnings;
520 }
521
522 /**
523 * Get the date information about the current state of the quiz.
524 * @return string[] array of two strings. First a short summary, then a longer
525 * explanation of the current state, e.g. for a tool-tip.
526 */
527 public function get_dates_summary() {
528 $timenow = time();
529 $quiz = $this->quizobj->get_quiz();
530
531 // Exact open and close dates for the tool-tip.
532 $dates = array();
533 if ($quiz->timeopen > 0) {
534 if ($timenow > $quiz->timeopen) {
535 $dates[] = get_string('quizopenedon', 'quiz', userdate($quiz->timeopen));
536 } else {
537 $dates[] = get_string('quizwillopen', 'quiz', userdate($quiz->timeopen));
538 }
539 }
540 if ($quiz->timeclose > 0) {
541 if ($timenow > $quiz->timeclose) {
542 $dates[] = get_string('quizclosed', 'quiz', userdate($quiz->timeclose));
543 } else {
544 $dates[] = get_string('quizcloseson', 'quiz', userdate($quiz->timeclose));
545 }
546 }
547 if (empty($dates)) {
548 $dates[] = get_string('alwaysavailable', 'quiz');
549 }
550 $explanation = implode(', ', $dates);
551
552 // Brief summary on the page.
553 if ($timenow < $quiz->timeopen) {
554 $currentstatus = get_string('quizisclosedwillopen', 'quiz',
555 userdate($quiz->timeopen, get_string('strftimedatetimeshort', 'langconfig')));
556 } else if ($quiz->timeclose && $timenow <= $quiz->timeclose) {
557 $currentstatus = get_string('quizisopenwillclose', 'quiz',
558 userdate($quiz->timeclose, get_string('strftimedatetimeshort', 'langconfig')));
559 } else if ($quiz->timeclose && $timenow > $quiz->timeclose) {
560 $currentstatus = get_string('quizisclosed', 'quiz');
561 } else {
562 $currentstatus = get_string('quizisopen', 'quiz');
563 }
564
565 return array($currentstatus, $explanation);
566 }
567
568 /**
569 * Set up this class with the structure for a given quiz.
570 * @param \stdClass $quiz the quiz settings.
571 */
572 public function populate_structure($quiz) {
573 global $DB;
574
575 $slots = $DB->get_records_sql("
576 SELECT slot.id AS slotid, slot.slot, slot.questionid, slot.page, slot.maxmark,
f7785e42 577 slot.requireprevious, q.*, qc.contextid
e1a2d0d9
CC
578 FROM {quiz_slots} slot
579 LEFT JOIN {question} q ON q.id = slot.questionid
580 LEFT JOIN {question_categories} qc ON qc.id = q.category
581 WHERE slot.quizid = ?
582 ORDER BY slot.slot", array($quiz->id));
583
584 $slots = $this->populate_missing_questions($slots);
585
586 $this->questions = array();
587 $this->slots = array();
588 $this->slotsinorder = array();
589 foreach ($slots as $slotdata) {
590 $this->questions[$slotdata->questionid] = $slotdata;
591
592 $slot = new \stdClass();
593 $slot->id = $slotdata->slotid;
594 $slot->slot = $slotdata->slot;
595 $slot->quizid = $quiz->id;
596 $slot->page = $slotdata->page;
597 $slot->questionid = $slotdata->questionid;
598 $slot->maxmark = $slotdata->maxmark;
f7785e42 599 $slot->requireprevious = $slotdata->requireprevious;
e1a2d0d9
CC
600
601 $this->slots[$slot->id] = $slot;
602 $this->slotsinorder[$slot->slot] = $slot;
603 }
604
5d949702
K
605 // Get quiz sections in ascending order of the firstslot.
606 $this->sections = $DB->get_records('quiz_sections', array('quizid' => $quiz->id), 'firstslot ASC');
607 $this->populate_slots_with_sections();
e1a2d0d9
CC
608 $this->populate_question_numbers();
609 }
610
611 /**
612 * Used by populate. Make up fake data for any missing questions.
613 * @param \stdClass[] $slots the data about the slots and questions in the quiz.
614 * @return \stdClass[] updated $slots array.
615 */
616 protected function populate_missing_questions($slots) {
617 // Address missing question types.
618 foreach ($slots as $slot) {
619 if ($slot->qtype === null) {
620 // If the questiontype is missing change the question type.
621 $slot->id = $slot->questionid;
622 $slot->category = 0;
623 $slot->qtype = 'missingtype';
624 $slot->name = get_string('missingquestion', 'quiz');
625 $slot->slot = $slot->slot;
626 $slot->maxmark = 0;
f7785e42 627 $slot->requireprevious = 0;
e1a2d0d9
CC
628 $slot->questiontext = ' ';
629 $slot->questiontextformat = FORMAT_HTML;
630 $slot->length = 1;
631
632 } else if (!\question_bank::qtype_exists($slot->qtype)) {
633 $slot->qtype = 'missingtype';
634 }
635 }
636
637 return $slots;
638 }
639
640 /**
641 * Fill in the section ids for each slot.
642 */
5d949702
K
643 public function populate_slots_with_sections() {
644 $sections = array_values($this->sections);
645 foreach ($sections as $i => $section) {
646 if (isset($sections[$i + 1])) {
647 $section->lastslot = $sections[$i + 1]->firstslot - 1;
648 } else {
649 $section->lastslot = count($this->slotsinorder);
650 }
651 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
652 $this->slotsinorder[$slot]->section = $section;
e1a2d0d9 653 }
e1a2d0d9
CC
654 }
655 }
656
657 /**
658 * Number the questions.
659 */
660 protected function populate_question_numbers() {
661 $number = 1;
662 foreach ($this->slots as $slot) {
441d284a
TH
663 if ($this->questions[$slot->questionid]->length == 0) {
664 $slot->displayednumber = get_string('infoshort', 'quiz');
e1a2d0d9 665 } else {
441d284a 666 $slot->displayednumber = $number;
e1a2d0d9
CC
667 $number += 1;
668 }
669 }
670 }
671
672 /**
673 * Move a slot from its current location to a new location.
674 *
675 * After callig this method, this class will be in an invalid state, and
676 * should be discarded if you want to manipulate the structure further.
677 *
678 * @param int $idmove id of slot to be moved
5d949702 679 * @param int $idmoveafter id of slot to come before slot being moved
e1a2d0d9 680 * @param int $page new page number of slot being moved
5d949702
K
681 * @param bool $insection if the question is moving to a place where a new
682 * section starts, include it in that section.
e1a2d0d9
CC
683 * @return void
684 */
5d949702 685 public function move_slot($idmove, $idmoveafter, $page) {
e1a2d0d9
CC
686 global $DB;
687
6870a6b8
TH
688 $this->check_can_be_edited();
689
e1a2d0d9
CC
690 $movingslot = $this->slots[$idmove];
691 if (empty($movingslot)) {
5d949702 692 throw new \moodle_exception('Bad slot ID ' . $idmove);
e1a2d0d9
CC
693 }
694 $movingslotnumber = (int) $movingslot->slot;
695
696 // Empty target slot means move slot to first.
5d949702
K
697 if (empty($idmoveafter)) {
698 $moveafterslotnumber = 0;
e1a2d0d9 699 } else {
5d949702
K
700 $moveafterslotnumber = (int) $this->slots[$idmoveafter]->slot;
701 }
702
703 // Check the target page number is OK.
704 if ($page == 0) {
705 $page = 1;
706 }
707 if (($moveafterslotnumber > 0 && $page < $this->get_page_number_for_slot($moveafterslotnumber)) ||
708 $page < 1) {
709 throw new \coding_exception('The target page number is too small.');
710 } else if (!$this->is_last_slot_in_quiz($moveafterslotnumber) &&
711 $page > $this->get_page_number_for_slot($moveafterslotnumber + 1)) {
712 throw new \coding_exception('The target page number is too large.');
713 }
714
715 // If the action came in as moving a slot to itself, normalise this to
716 // moving the slot to after the previosu slot.
717 if ($moveafterslotnumber == $movingslotnumber) {
718 $moveafterslotnumber = $moveafterslotnumber - 1;
e1a2d0d9
CC
719 }
720
721 // Work out how things are being moved.
722 $slotreorder = array();
5d949702
K
723 if ($moveafterslotnumber > $movingslotnumber) {
724 // Moving down.
725 $slotreorder[$movingslotnumber] = $moveafterslotnumber;
726 for ($i = $movingslotnumber; $i < $moveafterslotnumber; $i++) {
e1a2d0d9
CC
727 $slotreorder[$i + 1] = $i;
728 }
5d949702
K
729
730 $headingmoveafter = $movingslotnumber;
731 if ($this->is_last_slot_in_quiz($moveafterslotnumber) ||
732 $page == $this->get_page_number_for_slot($moveafterslotnumber + 1)) {
733 // We are moving to the start of a section, so that heading needs
734 // to be included in the ones that move up.
735 $headingmovebefore = $moveafterslotnumber + 1;
736 } else {
737 $headingmovebefore = $moveafterslotnumber;
738 }
739 $headingmovedirection = -1;
740
741 } else if ($moveafterslotnumber < $movingslotnumber - 1) {
742 // Moving up.
743 $slotreorder[$movingslotnumber] = $moveafterslotnumber + 1;
744 for ($i = $moveafterslotnumber + 1; $i < $movingslotnumber; $i++) {
e1a2d0d9
CC
745 $slotreorder[$i] = $i + 1;
746 }
5d949702
K
747
748 if ($page == $this->get_page_number_for_slot($moveafterslotnumber + 1)) {
749 // Moving to the start of a section, don't move that section.
750 $headingmoveafter = $moveafterslotnumber + 1;
751 } else {
752 // Moving tot the end of the previous section, so move the heading down too.
753 $headingmoveafter = $moveafterslotnumber;
754 }
755 $headingmovebefore = $movingslotnumber + 1;
756 $headingmovedirection = 1;
757 } else {
758 // Staying in the same place, but possibly changing page/section.
759 if ($page > $movingslot->page) {
760 $headingmoveafter = $movingslotnumber;
761 $headingmovebefore = $movingslotnumber + 2;
762 $headingmovedirection = -1;
763 } else {
764 $headingmoveafter = $movingslotnumber - 1;
765 $headingmovebefore = $movingslotnumber + 1;
766 $headingmovedirection = 1;
767 }
768 }
769
770 if ($this->is_only_slot_in_section($movingslotnumber)) {
771 throw new \coding_exception('You cannot remove the last slot in a section.');
e1a2d0d9
CC
772 }
773
774 $trans = $DB->start_delegated_transaction();
775
776 // Slot has moved record new order.
777 if ($slotreorder) {
778 update_field_with_unique_index('quiz_slots', 'slot', $slotreorder,
779 array('quizid' => $this->get_quizid()));
780 }
781
782 // Page has changed. Record it.
e1a2d0d9
CC
783 if ($movingslot->page != $page) {
784 $DB->set_field('quiz_slots', 'page', $page,
785 array('id' => $movingslot->id));
786 }
787
5d949702
K
788 // Update section fist slots.
789 $DB->execute("
790 UPDATE {quiz_sections}
791 SET firstslot = firstslot + ?
792 WHERE quizid = ?
793 AND firstslot > ?
794 AND firstslot < ?
795 ", array($headingmovedirection, $this->get_quizid(),
796 $headingmoveafter, $headingmovebefore));
797
798 // If any pages are now empty, remove them.
e1a2d0d9
CC
799 $emptypages = $DB->get_fieldset_sql("
800 SELECT DISTINCT page - 1
801 FROM {quiz_slots} slot
802 WHERE quizid = ?
803 AND page > 1
804 AND NOT EXISTS (SELECT 1 FROM {quiz_slots} WHERE quizid = ? AND page = slot.page - 1)
805 ORDER BY page - 1 DESC
806 ", array($this->get_quizid(), $this->get_quizid()));
807
808 foreach ($emptypages as $page) {
809 $DB->execute("
810 UPDATE {quiz_slots}
811 SET page = page - 1
812 WHERE quizid = ?
813 AND page > ?
814 ", array($this->get_quizid(), $page));
815 }
816
817 $trans->allow_commit();
818 }
819
820 /**
821 * Refresh page numbering of quiz slots.
e1a2d0d9
CC
822 * @param \stdClass[] $slots (optional) array of slot objects.
823 * @return \stdClass[] array of slot objects.
824 */
5d949702 825 public function refresh_page_numbers($slots = array()) {
e1a2d0d9
CC
826 global $DB;
827 // Get slots ordered by page then slot.
828 if (!count($slots)) {
5d949702 829 $slots = $DB->get_records('quiz_slots', array('quizid' => $this->get_quizid()), 'slot, page');
e1a2d0d9
CC
830 }
831
832 // Loop slots. Start Page number at 1 and increment as required.
833 $pagenumbers = array('new' => 0, 'old' => 0);
834
835 foreach ($slots as $slot) {
836 if ($slot->page !== $pagenumbers['old']) {
837 $pagenumbers['old'] = $slot->page;
838 ++$pagenumbers['new'];
839 }
840
841 if ($pagenumbers['new'] == $slot->page) {
842 continue;
843 }
844 $slot->page = $pagenumbers['new'];
845 }
846
847 return $slots;
848 }
849
850 /**
851 * Refresh page numbering of quiz slots and save to the database.
852 * @param \stdClass $quiz the quiz object.
853 * @return \stdClass[] array of slot objects.
854 */
5d949702 855 public function refresh_page_numbers_and_update_db() {
e1a2d0d9 856 global $DB;
6870a6b8
TH
857 $this->check_can_be_edited();
858
5d949702 859 $slots = $this->refresh_page_numbers();
e1a2d0d9
CC
860
861 // Record new page order.
862 foreach ($slots as $slot) {
863 $DB->set_field('quiz_slots', 'page', $slot->page,
864 array('id' => $slot->id));
865 }
866
867 return $slots;
868 }
869
870 /**
871 * Remove a slot from a quiz
e1a2d0d9
CC
872 * @param int $slotnumber The number of the slot to be deleted.
873 */
5d949702 874 public function remove_slot($slotnumber) {
e1a2d0d9
CC
875 global $DB;
876
6870a6b8
TH
877 $this->check_can_be_edited();
878
5d949702
K
879 if ($this->is_only_slot_in_section($slotnumber)) {
880 throw new \coding_exception('You cannot remove the last slot in a section.');
881 }
882
883 $slot = $DB->get_record('quiz_slots', array('quizid' => $this->get_quizid(), 'slot' => $slotnumber));
e1a2d0d9
CC
884 if (!$slot) {
885 return;
886 }
5d949702 887 $maxslot = $DB->get_field_sql('SELECT MAX(slot) FROM {quiz_slots} WHERE quizid = ?', array($this->get_quizid()));
e1a2d0d9
CC
888
889 $trans = $DB->start_delegated_transaction();
890 $DB->delete_records('quiz_slots', array('id' => $slot->id));
891 for ($i = $slot->slot + 1; $i <= $maxslot; $i++) {
892 $DB->set_field('quiz_slots', 'slot', $i - 1,
5d949702 893 array('quizid' => $this->get_quizid(), 'slot' => $i));
e1a2d0d9
CC
894 }
895
896 $qtype = $DB->get_field('question', 'qtype', array('id' => $slot->questionid));
897 if ($qtype === 'random') {
898 // This function automatically checks if the question is in use, and won't delete if it is.
899 question_delete_question($slot->questionid);
900 }
901
5d949702
K
902 $DB->execute("
903 UPDATE {quiz_sections}
904 SET firstslot = firstslot - 1
905 WHERE quizid = ?
906 AND firstslot > ?
907 ", array($this->get_quizid(), $slotnumber));
6375e98c
CC
908 unset($this->questions[$slot->questionid]);
909
5d949702 910 $this->refresh_page_numbers_and_update_db();
e1a2d0d9
CC
911
912 $trans->allow_commit();
913 }
914
915 /**
916 * Change the max mark for a slot.
917 *
918 * Saves changes to the question grades in the quiz_slots table and any
919 * corresponding question_attempts.
920 * It does not update 'sumgrades' in the quiz table.
921 *
922 * @param \stdClass $slot row from the quiz_slots table.
923 * @param float $maxmark the new maxmark.
924 * @return bool true if the new grade is different from the old one.
925 */
926 public function update_slot_maxmark($slot, $maxmark) {
927 global $DB;
928
929 if (abs($maxmark - $slot->maxmark) < 1e-7) {
930 // Grade has not changed. Nothing to do.
931 return false;
932 }
933
934 $trans = $DB->start_delegated_transaction();
935 $slot->maxmark = $maxmark;
936 $DB->update_record('quiz_slots', $slot);
937 \question_engine::set_max_mark_in_attempts(new \qubaids_for_quiz($slot->quizid),
938 $slot->slot, $maxmark);
939 $trans->allow_commit();
940
941 return true;
942 }
943
f7785e42 944 /**
441d284a
TH
945 * Set whether the question in a particular slot requires the previous one.
946 * @param int $slotid id of slot.
947 * @param bool $requireprevious if true, set this question to require the previous one.
f7785e42 948 */
441d284a 949 public function update_question_dependency($slotid, $requireprevious) {
f7785e42 950 global $DB;
441d284a 951 $DB->set_field('quiz_slots', 'requireprevious', $requireprevious, array('id' => $slotid));
f7785e42
K
952 }
953
e1a2d0d9
CC
954 /**
955 * Add/Remove a pagebreak.
956 *
957 * Saves changes to the slot page relationship in the quiz_slots table and reorders the paging
958 * for subsequent slots.
959 *
e1a2d0d9
CC
960 * @param int $slotid id of slot.
961 * @param int $type repaginate::LINK or repaginate::UNLINK.
962 * @return \stdClass[] array of slot objects.
963 */
5d949702 964 public function update_page_break($slotid, $type) {
e1a2d0d9
CC
965 global $DB;
966
6870a6b8
TH
967 $this->check_can_be_edited();
968
5d949702
K
969 $quizslots = $DB->get_records('quiz_slots', array('quizid' => $this->get_quizid()), 'slot');
970 $repaginate = new \mod_quiz\repaginate($this->get_quizid(), $quizslots);
e1a2d0d9 971 $repaginate->repaginate_slots($quizslots[$slotid]->slot, $type);
5d949702 972 $slots = $this->refresh_page_numbers_and_update_db();
e1a2d0d9
CC
973
974 return $slots;
975 }
5d949702
K
976
977 /**
978 * Add a section heading on a given page and return the sectionid
979 * @param int $pagenumber the number of the page where the section heading begins.
980 * @param string $heading the heading to add.
981 */
982 public function add_section_heading($pagenumber, $heading = 'Section heading ...') {
983 global $DB;
984 $section = new \stdClass();
985 $section->heading = $heading;
986 $section->quizid = $this->get_quizid();
987 $slotsonpage = $DB->get_records('quiz_slots', array('quizid' => $this->get_quizid(), 'page' => $pagenumber), 'slot DESC');
988 $section->firstslot = end($slotsonpage)->slot;
989 $section->shufflequestions = 0;
990 return $DB->insert_record('quiz_sections', $section);
991 }
992
993 /**
994 * Change the heading for a section.
995 * @param int $id the id of the section to change.
996 * @param string $newheading the new heading for this section.
997 */
998 public function set_section_heading($id, $newheading) {
999 global $DB;
1000 $section = $DB->get_record('quiz_sections', array('id' => $id), '*', MUST_EXIST);
1001 $section->heading = $newheading;
1002 $DB->update_record('quiz_sections', $section);
1003 }
1004
1005 /**
1006 * Change the shuffle setting for a section.
1007 * @param int $id the id of the section to change.
1008 * @param bool $shuffle whether this section should be shuffled.
1009 */
1010 public function set_section_shuffle($id, $shuffle) {
1011 global $DB;
1012 $section = $DB->get_record('quiz_sections', array('id' => $id), '*', MUST_EXIST);
1013 $section->shufflequestions = $shuffle;
1014 $DB->update_record('quiz_sections', $section);
1015 }
1016
1017 /**
1018 * Remove the section heading with the given id
1019 * @param int $sectionid the section to remove.
1020 */
1021 public function remove_section_heading($sectionid) {
1022 global $DB;
1023 $section = $DB->get_record('quiz_sections', array('id' => $sectionid), '*', MUST_EXIST);
1024 if ($section->firstslot == 1) {
1025 throw new \coding_exception('Cannot remove the first section in a quiz.');
1026 }
1027 $DB->delete_records('quiz_sections', array('id' => $sectionid));
1028 }
e1a2d0d9 1029}