MDL-47465 tool_monitor: Ignore used events
[moodle.git] / mod / quiz / classes / structure.php
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/>.
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  */
25 namespace mod_quiz;
26 defined('MOODLE_INTERNAL') || die();
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  */
40 class structure {
41     /** @var \quiz the quiz this is the structure of. */
42     protected $quizobj = null;
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();
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();
56     /**
57      * @var \stdClass[] currently a dummy. Holds data that will match the
58      * quiz_sections, once it exists.
59      */
60     protected $sections = array();
62     /** @var bool caches the results of can_be_edited. */
63     protected $canbeedited = null;
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     }
73     /**
74      * Create an instance of this class representing the structure of a given quiz.
75      * @param \stdClass $quiz the quiz settings.
76      * @return structure
77      */
78     public static function create_for($quiz) {
79         $structure = self::create();
80         $structure->populate_structure($quiz);
81         return $structure;
82     }
84     /**
85      * Create an instance of this class representing the structure of a given quiz.
86      * @param \quiz $quizobj the quiz.
87      * @return structure
88      */
89     public static function create_for_quiz($quizobj) {
90         $structure = self::create_for($quizobj->get_quiz());
91         $structure->quizobj = $quizobj;
92         return $structure;
93     }
95     /**
96      * Whether there are any questions in the quiz.
97      * @return bool true if there is at least one question in the quiz.
98      */
99     public function has_questions() {
100         return !empty($this->questions);
101     }
103     /**
104      * Get the number of questions in the quiz.
105      * @return int the number of questions in the quiz.
106      */
107     public function get_question_count() {
108         return count($this->questions);
109     }
111     /**
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.
116      */
117     public function get_question_by_id($questionid) {
118         return $this->questions[$questionid];
119     }
121     /**
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.
126      */
127     public function get_question_in_slot($slotnumber) {
128         return $this->questions[$this->slotsinorder[$slotnumber]->questionid];
129     }
131     /**
132      * Get the course module id of the quiz.
133      * @return int the course_modules.id for the quiz.
134      */
135     public function get_cmid() {
136         return $this->quizobj->get_cmid();
137     }
139     /**
140      * Get id of the quiz.
141      * @return int the quiz.id for the quiz.
142      */
143     public function get_quizid() {
144         return $this->quizobj->get_quizid();
145     }
147     /**
148      * Get the quiz object.
149      * @return \stdClass the quiz settings row from the database.
150      */
151     public function get_quiz() {
152         return $this->quizobj->get_quiz();
153     }
155     /**
156      * Whether the question in the quiz are shuffled for each attempt.
157      * @return bool true if the questions are shuffled.
158      */
159     public function is_shuffled() {
160         return $this->quizobj->get_quiz()->shufflequestions;
161     }
163     /**
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.
167      */
168     public function can_be_repaginated() {
169         return !$this->is_shuffled() && $this->can_be_edited()
170                 && $this->get_question_count() >= 2;
171     }
173     /**
174      * Quizzes can only be edited if they have not been attempted.
175      * @return bool whether the quiz can be edited.
176      */
177     public function can_be_edited() {
178         if ($this->canbeedited === null) {
179             $this->canbeedited = !quiz_has_attempts($this->quizobj->get_quizid());
180         }
181         return $this->canbeedited;
182     }
184     /**
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
189      * quiz by default.
190      */
191     public function get_questions_per_page() {
192         return $this->quizobj->get_quiz()->questionsperpage;
193     }
195     /**
196      * Get quiz slots.
197      * @return \stdClass[] the slots in this quiz.
198      */
199     public function get_slots() {
200         return $this->slots;
201     }
203     /**
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.
207      */
208     public function is_first_slot_on_page($slotnumber) {
209         if ($slotnumber == 1) {
210             return true;
211         }
212         return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber - 1]->page;
213     }
215     /**
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.
219      */
220     public function is_last_slot_on_page($slotnumber) {
221         if (!isset($this->slotsinorder[$slotnumber + 1])) {
222             return true;
223         }
224         return $this->slotsinorder[$slotnumber]->page != $this->slotsinorder[$slotnumber + 1]->page;
225     }
227     /**
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.
231      */
232     public function is_last_slot_in_quiz($slotnumber) {
233         end($this->slotsinorder);
234         return $slotnumber == key($this->slotsinorder);
235     }
237     /**
238      * Get the final slot in the quiz.
239      * @return \stdClass the quiz_slots for for the final slot in the quiz.
240      */
241     public function get_last_slot() {
242         return end($this->slotsinorder);
243     }
245     /**
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.
249      */
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.');
253         }
254         return $this->slots[$slotid];
255     }
257     /**
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.
261      */
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];
267             }
268         }
269         return $questions;
270     }
272     /**
273      * Get all the sections of the quiz.
274      * @return \stdClass[] the sections in this quiz.
275      */
276     public function get_quiz_sections() {
277         return $this->sections;
278     }
280     /**
281      * Get any warnings to show at the top of the edit page.
282      * @return string[] array of strings.
283      */
284     public function get_edit_page_warnings() {
285         $warnings = array();
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);
291         }
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);
299         }
301         return $warnings;
302     }
304     /**
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.
308      */
309     public function get_dates_summary() {
310         $timenow = time();
311         $quiz = $this->quizobj->get_quiz();
313         // Exact open and close dates for the tool-tip.
314         $dates = array();
315         if ($quiz->timeopen > 0) {
316             if ($timenow > $quiz->timeopen) {
317                 $dates[] = get_string('quizopenedon', 'quiz', userdate($quiz->timeopen));
318             } else {
319                 $dates[] = get_string('quizwillopen', 'quiz', userdate($quiz->timeopen));
320             }
321         }
322         if ($quiz->timeclose > 0) {
323             if ($timenow > $quiz->timeclose) {
324                 $dates[] = get_string('quizclosed', 'quiz', userdate($quiz->timeclose));
325             } else {
326                 $dates[] = get_string('quizcloseson', 'quiz', userdate($quiz->timeclose));
327             }
328         }
329         if (empty($dates)) {
330             $dates[] = get_string('alwaysavailable', 'quiz');
331         }
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');
343         } else {
344             $currentstatus = get_string('quizisopen', 'quiz');
345         }
347         return array($currentstatus, $explanation);
348     }
350     /**
351      * Set up this class with the structure for a given quiz.
352      * @param \stdClass $quiz the quiz settings.
353      */
354     public function populate_structure($quiz) {
355         global $DB;
357         $slots = $DB->get_records_sql("
358                 SELECT slot.id AS slotid, slot.slot, slot.questionid, slot.page, slot.maxmark,
359                        q.*, qc.contextid
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;
384         }
386         $section = new \stdClass();
387         $section->id = 1;
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();
396     }
398     /**
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.
402      */
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;
409                 $slot->category = 0;
410                 $slot->qtype = 'missingtype';
411                 $slot->name = get_string('missingquestion', 'quiz');
412                 $slot->slot = $slot->slot;
413                 $slot->maxmark = 0;
414                 $slot->questiontext = ' ';
415                 $slot->questiontextformat = FORMAT_HTML;
416                 $slot->length = 1;
418             } else if (!\question_bank::qtype_exists($slot->qtype)) {
419                 $slot->qtype = 'missingtype';
420             }
421         }
423         return $slots;
424     }
426     /**
427      * Fill in the section ids for each slot.
428      */
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);
435                 if (!$nextsection) {
436                     $nextsection = new \stdClass();
437                     $nextsection->firstslot = -1;
438                 }
439             }
441             $slot->sectionid = $currentsectionid;
442         }
443     }
445     /**
446      * Number the questions.
447      */
448     protected function populate_question_numbers() {
449         $number = 1;
450         foreach ($this->slots as $slot) {
451             $question = $this->questions[$slot->questionid];
452             if ($question->length == 0) {
453                 $question->displayednumber = get_string('infoshort', 'quiz');
454             } else {
455                 $question->displayednumber = $number;
456                 $number += 1;
457             }
458         }
459     }
461     /**
462      * Move a slot from its current location to a new location.
463      *
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.
466      *
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
470      * @return void
471      */
472     public function move_slot($idmove, $idbefore, $page) {
473         global $DB;
475         $movingslot = $this->slots[$idmove];
476         if (empty($movingslot)) {
477             throw new moodle_exception('Bad slot ID ' . $idmove);
478         }
479         $movingslotnumber = (int) $movingslot->slot;
481         // Empty target slot means move slot to first.
482         if (empty($idbefore)) {
483             $targetslotnumber = 0;
484         } else {
485             $targetslotnumber = (int) $this->slots[$idbefore]->slot;
486         }
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;
494             }
495         } else if ($targetslotnumber < $movingslotnumber - 1) {
496             $slotreorder[$movingslotnumber] = $targetslotnumber + 1;
497             for ($i = $targetslotnumber + 1; $i < $movingslotnumber; $i++) {
498                 $slotreorder[$i] = $i + 1;
499             }
500         }
502         $trans = $DB->start_delegated_transaction();
504         // Slot has moved record new order.
505         if ($slotreorder) {
506             update_field_with_unique_index('quiz_slots', 'slot', $slotreorder,
507                     array('quizid' => $this->get_quizid()));
508         }
510         // Page has changed. Record it.
511         if (!$page) {
512             $page = 1;
513         }
514         if ($movingslot->page != $page) {
515             $DB->set_field('quiz_slots', 'page', $page,
516                     array('id' => $movingslot->id));
517         }
519         $emptypages = $DB->get_fieldset_sql("
520                 SELECT DISTINCT page - 1
521                   FROM {quiz_slots} slot
522                  WHERE quizid = ?
523                    AND page > 1
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) {
529             $DB->execute("
530                     UPDATE {quiz_slots}
531                        SET page = page - 1
532                      WHERE quizid = ?
533                        AND page > ?
534                     ", array($this->get_quizid(), $page));
535         }
537         $trans->allow_commit();
538     }
540     /**
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.
545      */
546     public function refresh_page_numbers($quiz, $slots=array()) {
547         global $DB;
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');
551         }
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'];
560             }
562             if ($pagenumbers['new'] == $slot->page) {
563                 continue;
564             }
565             $slot->page = $pagenumbers['new'];
566         }
568         return $slots;
569     }
571     /**
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.
575      */
576     public function refresh_page_numbers_and_update_db($quiz) {
577         global $DB;
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));
584         }
586         return $slots;
587     }
589     /**
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.
593      */
594     public function remove_slot($quiz, $slotnumber) {
595         global $DB;
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));
599         if (!$slot) {
600             return;
601         }
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));
608         }
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);
614         }
616         unset($this->questions[$slot->questionid]);
618         $this->refresh_page_numbers_and_update_db($quiz);
620         $trans->allow_commit();
621     }
623     /**
624      * Change the max mark for a slot.
625      *
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.
629      *
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.
633      */
634     public function update_slot_maxmark($slot, $maxmark) {
635         global $DB;
637         if (abs($maxmark - $slot->maxmark) < 1e-7) {
638             // Grade has not changed. Nothing to do.
639             return false;
640         }
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();
649         return true;
650     }
652     /**
653      * Add/Remove a pagebreak.
654      *
655      * Saves changes to the slot page relationship in the quiz_slots table and reorders the paging
656      * for subsequent slots.
657      *
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.
662      */
663     public function update_page_break($quiz, $slotid, $type) {
664         global $DB;
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);
671         return $slots;
672     }