2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Defines the \mod_quiz\structure class.
21 * @copyright 2013 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
29 * Quiz structure class.
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.
37 * @copyright 2014 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 /** @var \quiz the quiz this is the structure of. */
42 protected $quizobj = null;
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.
48 protected $questions = array();
50 /** @var \stdClass[] quiz_slots.id => the quiz_slots rows for this quiz, agumented by sectionid. */
51 protected $slots = array();
53 /** @var \stdClass[] quiz_slots.slot => the quiz_slots rows for this quiz, agumented by sectionid. */
54 protected $slotsinorder = array();
57 * @var \stdClass[] currently a dummy. Holds data that will match the
58 * quiz_sections, once it exists.
60 protected $sections = array();
62 /** @var bool caches the results of can_be_edited. */
63 protected $canbeedited = null;
66 * Create an instance of this class representing an empty quiz.
69 public static function create() {
74 * Create an instance of this class representing the structure of a given quiz.
75 * @param \stdClass $quiz the quiz settings.
78 public static function create_for($quiz) {
79 $structure = self::create();
80 $structure->populate_structure($quiz);
85 * Create an instance of this class representing the structure of a given quiz.
86 * @param \quiz $quizobj the quiz.
89 public static function create_for_quiz($quizobj) {
90 $structure = self::create_for($quizobj->get_quiz());
91 $structure->quizobj = $quizobj;
96 * Whether there are any questions in the quiz.
97 * @return bool true if there is at least one question in the quiz.
99 public function has_questions() {
100 return !empty($this->questions);
104 * Get the number of questions in the quiz.
105 * @return int the number of questions in the quiz.
107 public function get_question_count() {
108 return count($this->questions);
112 * Get the information about the question with this id.
113 * @param int $questionid The question id.
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.
117 public function get_question_by_id($questionid) {
118 return $this->questions[$questionid];
122 * Get the information about the question in a given slot.
123 * @param int $slotnumber the index of the slot in question.
124 * @return \stdClass the data from the questions table, augmented with
125 * question_category.contextid, and the quiz_slots data for the question in this quiz.
127 public function get_question_in_slot($slotnumber) {
128 return $this->questions[$this->slotsinorder[$slotnumber]->questionid];
132 * Get the course module id of the quiz.
133 * @return int the course_modules.id for the quiz.
135 public function get_cmid() {
136 return $this->quizobj->get_cmid();
140 * Get id of the quiz.
141 * @return int the quiz.id for the quiz.
143 public function get_quizid() {
144 return $this->quizobj->get_quizid();
148 * Get the quiz object.
149 * @return \stdClass the quiz settings row from the database.
151 public function get_quiz() {
152 return $this->quizobj->get_quiz();
156 * Whether the question in the quiz are shuffled for each attempt.
157 * @return bool true if the questions are shuffled.
159 public function is_shuffled() {
160 return $this->quizobj->get_quiz()->shufflequestions;
164 * Quizzes can only be repaginated if they have not been attempted, the
165 * questions are not shuffled, and there are two or more questions.
166 * @return bool whether this quiz can be repaginated.
168 public function can_be_repaginated() {
169 return !$this->is_shuffled() && $this->can_be_edited()
170 && $this->get_question_count() >= 2;
174 * Quizzes can only be edited if they have not been attempted.
175 * @return bool whether the quiz can be edited.
177 public function can_be_edited() {
178 if ($this->canbeedited === null) {
179 $this->canbeedited = !quiz_has_attempts($this->quizobj->get_quizid());
181 return $this->canbeedited;
185 * How many questions are allowed per page in the quiz.
186 * This setting controls how frequently extra page-breaks should be inserted
187 * automatically when questions are added to the quiz.
188 * @return int the number of questions that should be on each page of the
191 public function get_questions_per_page() {
192 return $this->quizobj->get_quiz()->questionsperpage;
197 * @return \stdClass[] the slots in this quiz.
199 public function get_slots() {
204 * Is this slot the first one on its page?
205 * @param int $slotnumber the index of the slot in question.
206 * @return bool whether this slot the first one on its page.
208 public function is_first_slot_on_page($slotnumber) {
209 if ($slotnumber == 1) {
212 return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber - 1]->page;
216 * Is this slot the last one on its page?
217 * @param int $slotnumber the index of the slot in question.
218 * @return bool whether this slot the last one on its page.
220 public function is_last_slot_on_page($slotnumber) {
221 if (!isset($this->slotsinorder[$slotnumber + 1])) {
224 return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber + 1]->page;
228 * Is this slot the last one in the quiz?
229 * @param int $slotnumber the index of the slot in question.
230 * @return bool whether this slot the last one in the quiz.
232 public function is_last_slot_in_quiz($slotnumber) {
233 end($this->slotsinorder);
234 return $slotnumber == key($this->slotsinorder);
238 * Get the final slot in the quiz.
239 * @return \stdClass the quiz_slots for for the final slot in the quiz.
241 public function get_last_slot() {
242 return end($this->slotsinorder);
246 * Get a slot by it's id. Throws an exception if it is missing.
247 * @param int $slotid the slot id.
248 * @return \stdClass the requested quiz_slots row.
250 public function get_slot_by_id($slotid) {
251 if (!array_key_exists($slotid, $this->slots)) {
252 throw new \coding_exception('The \'slotid\' could not be found.');
254 return $this->slots[$slotid];
258 * Get all the questions in a section of the quiz.
259 * @param int $sectionid the section id.
260 * @return \stdClass[] of question/slot objects.
262 public function get_questions_in_section($sectionid) {
263 $questions = array();
264 foreach ($this->slotsinorder as $slot) {
265 if ($slot->sectionid == $sectionid) {
266 $questions[] = $this->questions[$slot->questionid];
273 * Get all the sections of the quiz.
274 * @return \stdClass[] the sections in this quiz.
276 public function get_quiz_sections() {
277 return $this->sections;
281 * Get any warnings to show at the top of the edit page.
282 * @return string[] array of strings.
284 public function get_edit_page_warnings() {
287 if (quiz_has_attempts($this->quizobj->get_quizid())) {
288 $reviewlink = quiz_attempt_summary_link_to_reports($this->quizobj->get_quiz(),
289 $this->quizobj->get_cm(), $this->quizobj->get_context());
290 $warnings[] = get_string('cannoteditafterattempts', 'quiz', $reviewlink);
293 if ($this->is_shuffled()) {
294 $updateurl = new \moodle_url('/course/mod.php',
295 array('return' => 'true', 'update' => $this->quizobj->get_cmid(), 'sesskey' => sesskey()));
296 $updatelink = '<a href="'.$updateurl->out().'">' . get_string('updatethis', '',
297 get_string('modulename', 'quiz')) . '</a>';
298 $warnings[] = get_string('shufflequestionsselected', 'quiz', $updatelink);
305 * Get the date information about the current state of the quiz.
306 * @return string[] array of two strings. First a short summary, then a longer
307 * explanation of the current state, e.g. for a tool-tip.
309 public function get_dates_summary() {
311 $quiz = $this->quizobj->get_quiz();
313 // Exact open and close dates for the tool-tip.
315 if ($quiz->timeopen > 0) {
316 if ($timenow > $quiz->timeopen) {
317 $dates[] = get_string('quizopenedon', 'quiz', userdate($quiz->timeopen));
319 $dates[] = get_string('quizwillopen', 'quiz', userdate($quiz->timeopen));
322 if ($quiz->timeclose > 0) {
323 if ($timenow > $quiz->timeclose) {
324 $dates[] = get_string('quizclosed', 'quiz', userdate($quiz->timeclose));
326 $dates[] = get_string('quizcloseson', 'quiz', userdate($quiz->timeclose));
330 $dates[] = get_string('alwaysavailable', 'quiz');
332 $explanation = implode(', ', $dates);
334 // Brief summary on the page.
335 if ($timenow < $quiz->timeopen) {
336 $currentstatus = get_string('quizisclosedwillopen', 'quiz',
337 userdate($quiz->timeopen, get_string('strftimedatetimeshort', 'langconfig')));
338 } else if ($quiz->timeclose && $timenow <= $quiz->timeclose) {
339 $currentstatus = get_string('quizisopenwillclose', 'quiz',
340 userdate($quiz->timeclose, get_string('strftimedatetimeshort', 'langconfig')));
341 } else if ($quiz->timeclose && $timenow > $quiz->timeclose) {
342 $currentstatus = get_string('quizisclosed', 'quiz');
344 $currentstatus = get_string('quizisopen', 'quiz');
347 return array($currentstatus, $explanation);
351 * Set up this class with the structure for a given quiz.
352 * @param \stdClass $quiz the quiz settings.
354 public function populate_structure($quiz) {
357 $slots = $DB->get_records_sql("
358 SELECT slot.id AS slotid, slot.slot, slot.questionid, slot.page, slot.maxmark,
360 FROM {quiz_slots} slot
361 LEFT JOIN {question} q ON q.id = slot.questionid
362 LEFT JOIN {question_categories} qc ON qc.id = q.category
363 WHERE slot.quizid = ?
364 ORDER BY slot.slot", array($quiz->id));
366 $slots = $this->populate_missing_questions($slots);
368 $this->questions = array();
369 $this->slots = array();
370 $this->slotsinorder = array();
371 foreach ($slots as $slotdata) {
372 $this->questions[$slotdata->questionid] = $slotdata;
374 $slot = new \stdClass();
375 $slot->id = $slotdata->slotid;
376 $slot->slot = $slotdata->slot;
377 $slot->quizid = $quiz->id;
378 $slot->page = $slotdata->page;
379 $slot->questionid = $slotdata->questionid;
380 $slot->maxmark = $slotdata->maxmark;
382 $this->slots[$slot->id] = $slot;
383 $this->slotsinorder[$slot->slot] = $slot;
386 $section = new \stdClass();
388 $section->quizid = $quiz->id;
389 $section->heading = '';
390 $section->firstslot = 1;
391 $section->shuffle = false;
392 $this->sections = array(1 => $section);
394 $this->populate_slots_with_sectionids();
395 $this->populate_question_numbers();
399 * Used by populate. Make up fake data for any missing questions.
400 * @param \stdClass[] $slots the data about the slots and questions in the quiz.
401 * @return \stdClass[] updated $slots array.
403 protected function populate_missing_questions($slots) {
404 // Address missing question types.
405 foreach ($slots as $slot) {
406 if ($slot->qtype === null) {
407 // If the questiontype is missing change the question type.
408 $slot->id = $slot->questionid;
410 $slot->qtype = 'missingtype';
411 $slot->name = get_string('missingquestion', 'quiz');
412 $slot->slot = $slot->slot;
414 $slot->questiontext = ' ';
415 $slot->questiontextformat = FORMAT_HTML;
418 } else if (!\question_bank::qtype_exists($slot->qtype)) {
419 $slot->qtype = 'missingtype';
427 * Fill in the section ids for each slot.
429 public function populate_slots_with_sectionids() {
430 $nextsection = reset($this->sections);
431 foreach ($this->slotsinorder as $slot) {
432 if ($slot->slot == $nextsection->firstslot) {
433 $currentsectionid = $nextsection->id;
434 $nextsection = next($this->sections);
436 $nextsection = new \stdClass();
437 $nextsection->firstslot = -1;
441 $slot->sectionid = $currentsectionid;
446 * Number the questions.
448 protected function populate_question_numbers() {
450 foreach ($this->slots as $slot) {
451 $question = $this->questions[$slot->questionid];
452 if ($question->length == 0) {
453 $question->displayednumber = get_string('infoshort', 'quiz');
455 $question->displayednumber = $number;
462 * Move a slot from its current location to a new location.
464 * After callig this method, this class will be in an invalid state, and
465 * should be discarded if you want to manipulate the structure further.
467 * @param int $idmove id of slot to be moved
468 * @param int $idbefore id of slot to come before slot being moved
469 * @param int $page new page number of slot being moved
472 public function move_slot($idmove, $idbefore, $page) {
475 $movingslot = $this->slots[$idmove];
476 if (empty($movingslot)) {
477 throw new moodle_exception('Bad slot ID ' . $idmove);
479 $movingslotnumber = (int) $movingslot->slot;
481 // Empty target slot means move slot to first.
482 if (empty($idbefore)) {
483 $targetslotnumber = 0;
485 $targetslotnumber = (int) $this->slots[$idbefore]->slot;
488 // Work out how things are being moved.
489 $slotreorder = array();
490 if ($targetslotnumber > $movingslotnumber) {
491 $slotreorder[$movingslotnumber] = $targetslotnumber;
492 for ($i = $movingslotnumber; $i < $targetslotnumber; $i++) {
493 $slotreorder[$i + 1] = $i;
495 } else if ($targetslotnumber < $movingslotnumber - 1) {
496 $slotreorder[$movingslotnumber] = $targetslotnumber + 1;
497 for ($i = $targetslotnumber + 1; $i < $movingslotnumber; $i++) {
498 $slotreorder[$i] = $i + 1;
502 $trans = $DB->start_delegated_transaction();
504 // Slot has moved record new order.
506 update_field_with_unique_index('quiz_slots', 'slot', $slotreorder,
507 array('quizid' => $this->get_quizid()));
510 // Page has changed. Record it.
514 if ($movingslot->page != $page) {
515 $DB->set_field('quiz_slots', 'page', $page,
516 array('id' => $movingslot->id));
519 $emptypages = $DB->get_fieldset_sql("
520 SELECT DISTINCT page - 1
521 FROM {quiz_slots} slot
524 AND NOT EXISTS (SELECT 1 FROM {quiz_slots} WHERE quizid = ? AND page = slot.page - 1)
525 ORDER BY page - 1 DESC
526 ", array($this->get_quizid(), $this->get_quizid()));
528 foreach ($emptypages as $page) {
534 ", array($this->get_quizid(), $page));
537 $trans->allow_commit();
541 * Refresh page numbering of quiz slots.
542 * @param \stdClass $quiz the quiz object.
543 * @param \stdClass[] $slots (optional) array of slot objects.
544 * @return \stdClass[] array of slot objects.
546 public function refresh_page_numbers($quiz, $slots=array()) {
548 // Get slots ordered by page then slot.
549 if (!count($slots)) {
550 $slots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id), 'slot, page');
553 // Loop slots. Start Page number at 1 and increment as required.
554 $pagenumbers = array('new' => 0, 'old' => 0);
556 foreach ($slots as $slot) {
557 if ($slot->page !== $pagenumbers['old']) {
558 $pagenumbers['old'] = $slot->page;
559 ++$pagenumbers['new'];
562 if ($pagenumbers['new'] == $slot->page) {
565 $slot->page = $pagenumbers['new'];
572 * Refresh page numbering of quiz slots and save to the database.
573 * @param \stdClass $quiz the quiz object.
574 * @return \stdClass[] array of slot objects.
576 public function refresh_page_numbers_and_update_db($quiz) {
578 $slots = $this->refresh_page_numbers($quiz);
580 // Record new page order.
581 foreach ($slots as $slot) {
582 $DB->set_field('quiz_slots', 'page', $slot->page,
583 array('id' => $slot->id));
590 * Remove a slot from a quiz
591 * @param \stdClass $quiz the quiz object.
592 * @param int $slotnumber The number of the slot to be deleted.
594 public function remove_slot($quiz, $slotnumber) {
597 $slot = $DB->get_record('quiz_slots', array('quizid' => $quiz->id, 'slot' => $slotnumber));
598 $maxslot = $DB->get_field_sql('SELECT MAX(slot) FROM {quiz_slots} WHERE quizid = ?', array($quiz->id));
603 $trans = $DB->start_delegated_transaction();
604 $DB->delete_records('quiz_slots', array('id' => $slot->id));
605 for ($i = $slot->slot + 1; $i <= $maxslot; $i++) {
606 $DB->set_field('quiz_slots', 'slot', $i - 1,
607 array('quizid' => $quiz->id, 'slot' => $i));
610 $qtype = $DB->get_field('question', 'qtype', array('id' => $slot->questionid));
611 if ($qtype === 'random') {
612 // This function automatically checks if the question is in use, and won't delete if it is.
613 question_delete_question($slot->questionid);
616 unset($this->questions[$slot->questionid]);
618 $this->refresh_page_numbers_and_update_db($quiz);
620 $trans->allow_commit();
624 * Change the max mark for a slot.
626 * Saves changes to the question grades in the quiz_slots table and any
627 * corresponding question_attempts.
628 * It does not update 'sumgrades' in the quiz table.
630 * @param \stdClass $slot row from the quiz_slots table.
631 * @param float $maxmark the new maxmark.
632 * @return bool true if the new grade is different from the old one.
634 public function update_slot_maxmark($slot, $maxmark) {
637 if (abs($maxmark - $slot->maxmark) < 1e-7) {
638 // Grade has not changed. Nothing to do.
642 $trans = $DB->start_delegated_transaction();
643 $slot->maxmark = $maxmark;
644 $DB->update_record('quiz_slots', $slot);
645 \question_engine::set_max_mark_in_attempts(new \qubaids_for_quiz($slot->quizid),
646 $slot->slot, $maxmark);
647 $trans->allow_commit();
653 * Add/Remove a pagebreak.
655 * Saves changes to the slot page relationship in the quiz_slots table and reorders the paging
656 * for subsequent slots.
658 * @param \stdClass $quiz the quiz object.
659 * @param int $slotid id of slot.
660 * @param int $type repaginate::LINK or repaginate::UNLINK.
661 * @return \stdClass[] array of slot objects.
663 public function update_page_break($quiz, $slotid, $type) {
666 $quizslots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id), 'slot');
667 $repaginate = new \mod_quiz\repaginate($quiz->id, $quizslots);
668 $repaginate->repaginate_slots($quizslots[$slotid]->slot, $type);
669 $slots = $this->refresh_page_numbers_and_update_db($quiz);