MDL-50028 qtype_match: fix correct answer display
[moodle.git] / question / type / multichoice / question.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  * Multiple choice question definition classes.
19  *
20  * @package    qtype
21  * @subpackage multichoice
22  * @copyright  2009 The Open University
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 defined('MOODLE_INTERNAL') || die();
30 /**
31  * Base class for multiple choice questions. The parts that are common to
32  * single select and multiple select.
33  *
34  * @copyright  2009 The Open University
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 abstract class qtype_multichoice_base extends question_graded_automatically {
38     const LAYOUT_DROPDOWN = 0;
39     const LAYOUT_VERTICAL = 1;
40     const LAYOUT_HORIZONTAL = 2;
42     public $answers;
44     public $shuffleanswers;
45     public $answernumbering;
46     public $layout = self::LAYOUT_VERTICAL;
48     public $correctfeedback;
49     public $correctfeedbackformat;
50     public $partiallycorrectfeedback;
51     public $partiallycorrectfeedbackformat;
52     public $incorrectfeedback;
53     public $incorrectfeedbackformat;
55     protected $order = null;
57     public function start_attempt(question_attempt_step $step, $variant) {
58         $this->order = array_keys($this->answers);
59         if ($this->shuffleanswers) {
60             shuffle($this->order);
61         }
62         $step->set_qt_var('_order', implode(',', $this->order));
63     }
65     public function apply_attempt_state(question_attempt_step $step) {
66         $this->order = explode(',', $step->get_qt_var('_order'));
67     }
69     public function get_question_summary() {
70         $question = $this->html_to_text($this->questiontext, $this->questiontextformat);
71         $choices = array();
72         foreach ($this->order as $ansid) {
73             $choices[] = $this->html_to_text($this->answers[$ansid]->answer,
74                     $this->answers[$ansid]->answerformat);
75         }
76         return $question . ': ' . implode('; ', $choices);
77     }
79     public function get_order(question_attempt $qa) {
80         $this->init_order($qa);
81         return $this->order;
82     }
84     protected function init_order(question_attempt $qa) {
85         if (is_null($this->order)) {
86             $this->order = explode(',', $qa->get_step(0)->get_qt_var('_order'));
87         }
88     }
90     public abstract function get_response(question_attempt $qa);
92     public abstract function is_choice_selected($response, $value);
94     public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
95         if ($component == 'question' && in_array($filearea,
96                 array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'))) {
97             return $this->check_combined_feedback_file_access($qa, $options, $filearea);
99         } else if ($component == 'question' && $filearea == 'answer') {
100             $answerid = reset($args); // Itemid is answer id.
101             return  in_array($answerid, $this->order);
103         } else if ($component == 'question' && $filearea == 'answerfeedback') {
104             $answerid = reset($args); // Itemid is answer id.
105             $response = $this->get_response($qa);
106             $isselected = false;
107             foreach ($this->order as $value => $ansid) {
108                 if ($ansid == $answerid) {
109                     $isselected = $this->is_choice_selected($response, $value);
110                     break;
111                 }
112             }
113             // Param $options->suppresschoicefeedback is a hack specific to the
114             // oumultiresponse question type. It would be good to refactor to
115             // avoid refering to it here.
116             return $options->feedback && empty($options->suppresschoicefeedback) &&
117                     $isselected;
119         } else if ($component == 'question' && $filearea == 'hint') {
120             return $this->check_hint_file_access($qa, $options, $args);
122         } else {
123             return parent::check_file_access($qa, $options, $component, $filearea,
124                     $args, $forcedownload);
125         }
126     }
130 /**
131  * Represents a multiple choice question where only one choice should be selected.
132  *
133  * @copyright  2009 The Open University
134  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
135  */
136 class qtype_multichoice_single_question extends qtype_multichoice_base {
137     public function get_renderer(moodle_page $page) {
138         return $page->get_renderer('qtype_multichoice', 'single');
139     }
141     public function get_min_fraction() {
142         $minfraction = 0;
143         foreach ($this->answers as $ans) {
144             $minfraction = min($minfraction, $ans->fraction);
145         }
146         return $minfraction;
147     }
149     /**
150      * Return an array of the question type variables that could be submitted
151      * as part of a question of this type, with their types, so they can be
152      * properly cleaned.
153      * @return array variable name => PARAM_... constant.
154      */
155     public function get_expected_data() {
156         return array('answer' => PARAM_INT);
157     }
159     public function summarise_response(array $response) {
160         if (!array_key_exists('answer', $response) ||
161                 !array_key_exists($response['answer'], $this->order)) {
162             return null;
163         }
164         $ansid = $this->order[$response['answer']];
165         return $this->html_to_text($this->answers[$ansid]->answer,
166                 $this->answers[$ansid]->answerformat);
167     }
169     public function classify_response(array $response) {
170         if (!array_key_exists('answer', $response) ||
171                 !array_key_exists($response['answer'], $this->order)) {
172             return array($this->id => question_classified_response::no_response());
173         }
174         $choiceid = $this->order[$response['answer']];
175         $ans = $this->answers[$choiceid];
176         return array($this->id => new question_classified_response($choiceid,
177                 $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction));
178     }
180     public function get_correct_response() {
181         foreach ($this->order as $key => $answerid) {
182             if (question_state::graded_state_for_fraction(
183                     $this->answers[$answerid]->fraction)->is_correct()) {
184                 return array('answer' => $key);
185             }
186         }
187         return array();
188     }
190     public function prepare_simulated_post_data($simulatedresponse) {
191         $ansid = 0;
192         foreach ($this->answers as $answer) {
193             if (clean_param($answer->answer, PARAM_NOTAGS) == $simulatedresponse['answer']) {
194                 $ansid = $answer->id;
195             }
196         }
197         if ($ansid) {
198             return array('answer' => array_search($ansid, $this->order));
199         } else {
200             return array();
201         }
202     }
204     public function get_student_response_values_for_simulation($postdata) {
205         if (!isset($postdata['answer'])) {
206             return array();
207         } else {
208             $answer = $this->answers[$this->order[$postdata['answer']]];
209             return array('answer' => clean_param($answer->answer, PARAM_NOTAGS));
210         }
211     }
213     public function is_same_response(array $prevresponse, array $newresponse) {
214         return question_utils::arrays_same_at_key($prevresponse, $newresponse, 'answer');
215     }
217     public function is_complete_response(array $response) {
218         return array_key_exists('answer', $response) && $response['answer'] !== '';
219     }
221     public function is_gradable_response(array $response) {
222         return $this->is_complete_response($response);
223     }
225     public function grade_response(array $response) {
226         if (array_key_exists('answer', $response) &&
227                 array_key_exists($response['answer'], $this->order)) {
228             $fraction = $this->answers[$this->order[$response['answer']]]->fraction;
229         } else {
230             $fraction = 0;
231         }
232         return array($fraction, question_state::graded_state_for_fraction($fraction));
233     }
235     public function get_validation_error(array $response) {
236         if ($this->is_gradable_response($response)) {
237             return '';
238         }
239         return get_string('pleaseselectananswer', 'qtype_multichoice');
240     }
242     public function get_response(question_attempt $qa) {
243         return $qa->get_last_qt_var('answer', -1);
244     }
246     public function is_choice_selected($response, $value) {
247         return (string) $response === (string) $value;
248     }
252 /**
253  * Represents a multiple choice question where multiple choices can be selected.
254  *
255  * @copyright  2009 The Open University
256  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
257  */
258 class qtype_multichoice_multi_question extends qtype_multichoice_base {
259     public function get_renderer(moodle_page $page) {
260         return $page->get_renderer('qtype_multichoice', 'multi');
261     }
263     public function get_min_fraction() {
264         return 0;
265     }
267     public function clear_wrong_from_response(array $response) {
268         foreach ($this->order as $key => $ans) {
269             if (array_key_exists($this->field($key), $response) &&
270                     question_state::graded_state_for_fraction(
271                     $this->answers[$ans]->fraction)->is_incorrect()) {
272                 $response[$this->field($key)] = 0;
273             }
274         }
275         return $response;
276     }
278     public function get_num_parts_right(array $response) {
279         $numright = 0;
280         foreach ($this->order as $key => $ans) {
281             $fieldname = $this->field($key);
282             if (!array_key_exists($fieldname, $response) || !$response[$fieldname]) {
283                 continue;
284             }
286             if (!question_state::graded_state_for_fraction(
287                     $this->answers[$ans]->fraction)->is_incorrect()) {
288                 $numright += 1;
289             }
290         }
291         return array($numright, count($this->order));
292     }
294     /**
295      * @param int $key choice number
296      * @return string the question-type variable name.
297      */
298     protected function field($key) {
299         return 'choice' . $key;
300     }
302     public function get_expected_data() {
303         $expected = array();
304         foreach ($this->order as $key => $notused) {
305             $expected[$this->field($key)] = PARAM_BOOL;
306         }
307         return $expected;
308     }
310     public function summarise_response(array $response) {
311         $selectedchoices = array();
312         foreach ($this->order as $key => $ans) {
313             $fieldname = $this->field($key);
314             if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
315                 $selectedchoices[] = $this->html_to_text($this->answers[$ans]->answer,
316                         $this->answers[$ans]->answerformat);
317             }
318         }
319         if (empty($selectedchoices)) {
320             return null;
321         }
322         return implode('; ', $selectedchoices);
323     }
325     public function classify_response(array $response) {
326         $selectedchoices = array();
327         foreach ($this->order as $key => $ansid) {
328             $fieldname = $this->field($key);
329             if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
330                 $selectedchoices[$ansid] = 1;
331             }
332         }
333         $choices = array();
334         foreach ($this->answers as $ansid => $ans) {
335             if (isset($selectedchoices[$ansid])) {
336                 $choices[$ansid] = new question_classified_response($ansid,
337                         $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction);
338             }
339         }
340         return $choices;
341     }
343     public function get_correct_response() {
344         $response = array();
345         foreach ($this->order as $key => $ans) {
346             if (!question_state::graded_state_for_fraction(
347                     $this->answers[$ans]->fraction)->is_incorrect()) {
348                 $response[$this->field($key)] = 1;
349             }
350         }
351         return $response;
352     }
354     public function prepare_simulated_post_data($simulatedresponse) {
355         $postdata = array();
356         foreach ($simulatedresponse as $ans => $checked) {
357             foreach ($this->answers as $ansid => $answer) {
358                 if (clean_param($answer->answer, PARAM_NOTAGS) == $ans) {
359                     $fieldno = array_search($ansid, $this->order);
360                     $postdata[$this->field($fieldno)] = $checked;
361                     break;
362                 }
363             }
364         }
365         return $postdata;
366     }
368     public function get_student_response_values_for_simulation($postdata) {
369         $simulatedresponse = array();
370         foreach ($this->order as $fieldno => $ansid) {
371             if (isset($postdata[$this->field($fieldno)])) {
372                 $checked = $postdata[$this->field($fieldno)];
373                 $simulatedresponse[clean_param($this->answers[$ansid]->answer, PARAM_NOTAGS)] = $checked;
374             }
375         }
376         ksort($simulatedresponse);
377         return $simulatedresponse;
378     }
380     public function is_same_response(array $prevresponse, array $newresponse) {
381         foreach ($this->order as $key => $notused) {
382             $fieldname = $this->field($key);
383             if (!question_utils::arrays_same_at_key_integer($prevresponse, $newresponse, $fieldname)) {
384                 return false;
385             }
386         }
387         return true;
388     }
390     public function is_complete_response(array $response) {
391         foreach ($this->order as $key => $notused) {
392             if (!empty($response[$this->field($key)])) {
393                 return true;
394             }
395         }
396         return false;
397     }
399     public function is_gradable_response(array $response) {
400         return $this->is_complete_response($response);
401     }
403     /**
404      * @param array $response responses, as returned by
405      *      {@link question_attempt_step::get_qt_data()}.
406      * @return int the number of choices that were selected. in this response.
407      */
408     public function get_num_selected_choices(array $response) {
409         $numselected = 0;
410         foreach ($response as $key => $value) {
411             // Response keys starting with _ are internal values like _order, so ignore them.
412             if (!empty($value) && $key[0] != '_') {
413                 $numselected += 1;
414             }
415         }
416         return $numselected;
417     }
419     /**
420      * @return int the number of choices that are correct.
421      */
422     public function get_num_correct_choices() {
423         $numcorrect = 0;
424         foreach ($this->answers as $ans) {
425             if (!question_state::graded_state_for_fraction($ans->fraction)->is_incorrect()) {
426                 $numcorrect += 1;
427             }
428         }
429         return $numcorrect;
430     }
432     public function grade_response(array $response) {
433         $fraction = 0;
434         foreach ($this->order as $key => $ansid) {
435             if (!empty($response[$this->field($key)])) {
436                 $fraction += $this->answers[$ansid]->fraction;
437             }
438         }
439         $fraction = min(max(0, $fraction), 1.0);
440         return array($fraction, question_state::graded_state_for_fraction($fraction));
441     }
443     public function get_validation_error(array $response) {
444         if ($this->is_gradable_response($response)) {
445             return '';
446         }
447         return get_string('pleaseselectatleastoneanswer', 'qtype_multichoice');
448     }
450     /**
451      * Disable those hint settings that we don't want when the student has selected
452      * more choices than the number of right choices. This avoids giving the game away.
453      * @param question_hint_with_parts $hint a hint.
454      */
455     protected function disable_hint_settings_when_too_many_selected(
456             question_hint_with_parts $hint) {
457         $hint->clearwrong = false;
458     }
460     public function get_hint($hintnumber, question_attempt $qa) {
461         $hint = parent::get_hint($hintnumber, $qa);
462         if (is_null($hint)) {
463             return $hint;
464         }
466         if ($this->get_num_selected_choices($qa->get_last_qt_data()) >
467                 $this->get_num_correct_choices()) {
468             $hint = clone($hint);
469             $this->disable_hint_settings_when_too_many_selected($hint);
470         }
471         return $hint;
472     }
474     public function get_response(question_attempt $qa) {
475         return $qa->get_last_qt_data();
476     }
478     public function is_choice_selected($response, $value) {
479         return !empty($response['choice' . $value]);
480     }