MDL-40543 convert from simulated responses
[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     }
128     public function make_html_inline($html) {
129         $html = preg_replace('~\s*<p>\s*~u', '', $html);
130         $html = preg_replace('~\s*</p>\s*~u', '<br />', $html);
131         $html = preg_replace('~(<br\s*/?>)+$~u', '', $html);
132         return trim($html);
133     }
137 /**
138  * Represents a multiple choice question where only one choice should be selected.
139  *
140  * @copyright  2009 The Open University
141  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
142  */
143 class qtype_multichoice_single_question extends qtype_multichoice_base {
144     public function get_renderer(moodle_page $page) {
145         return $page->get_renderer('qtype_multichoice', 'single');
146     }
148     public function get_min_fraction() {
149         $minfraction = 0;
150         foreach ($this->answers as $ans) {
151             $minfraction = min($minfraction, $ans->fraction);
152         }
153         return $minfraction;
154     }
156     /**
157      * Return an array of the question type variables that could be submitted
158      * as part of a question of this type, with their types, so they can be
159      * properly cleaned.
160      * @return array variable name => PARAM_... constant.
161      */
162     public function get_expected_data() {
163         return array('answer' => PARAM_INT);
164     }
166     public function summarise_response(array $response) {
167         if (!array_key_exists('answer', $response) ||
168                 !array_key_exists($response['answer'], $this->order)) {
169             return null;
170         }
171         $ansid = $this->order[$response['answer']];
172         return $this->html_to_text($this->answers[$ansid]->answer,
173                 $this->answers[$ansid]->answerformat);
174     }
176     public function classify_response(array $response) {
177         if (!array_key_exists('answer', $response) ||
178                 !array_key_exists($response['answer'], $this->order)) {
179             return array($this->id => question_classified_response::no_response());
180         }
181         $choiceid = $this->order[$response['answer']];
182         $ans = $this->answers[$choiceid];
183         return array($this->id => new question_classified_response($choiceid,
184                 $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction));
185     }
187     public function get_correct_response() {
188         foreach ($this->order as $key => $answerid) {
189             if (question_state::graded_state_for_fraction(
190                     $this->answers[$answerid]->fraction)->is_correct()) {
191                 return array('answer' => $key);
192             }
193         }
194         return array();
195     }
198     public function prepare_simulated_post_data($simulatedresponse) {
199         $ansnumbertoanswerid = array_keys($this->answers);
200         $ansid = $ansnumbertoanswerid[$simulatedresponse['answer']];
201         return array('answer' => array_search($ansid, $this->order));
202     }
204     public function is_same_response(array $prevresponse, array $newresponse) {
205         return question_utils::arrays_same_at_key($prevresponse, $newresponse, 'answer');
206     }
208     public function is_complete_response(array $response) {
209         return array_key_exists('answer', $response) && $response['answer'] !== '';
210     }
212     public function is_gradable_response(array $response) {
213         return $this->is_complete_response($response);
214     }
216     public function grade_response(array $response) {
217         if (array_key_exists('answer', $response) &&
218                 array_key_exists($response['answer'], $this->order)) {
219             $fraction = $this->answers[$this->order[$response['answer']]]->fraction;
220         } else {
221             $fraction = 0;
222         }
223         return array($fraction, question_state::graded_state_for_fraction($fraction));
224     }
226     public function get_validation_error(array $response) {
227         if ($this->is_gradable_response($response)) {
228             return '';
229         }
230         return get_string('pleaseselectananswer', 'qtype_multichoice');
231     }
233     public function get_response(question_attempt $qa) {
234         return $qa->get_last_qt_var('answer', -1);
235     }
237     public function is_choice_selected($response, $value) {
238         return (string) $response === (string) $value;
239     }
243 /**
244  * Represents a multiple choice question where multiple choices can be selected.
245  *
246  * @copyright  2009 The Open University
247  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
248  */
249 class qtype_multichoice_multi_question extends qtype_multichoice_base {
250     public function get_renderer(moodle_page $page) {
251         return $page->get_renderer('qtype_multichoice', 'multi');
252     }
254     public function get_min_fraction() {
255         return 0;
256     }
258     public function clear_wrong_from_response(array $response) {
259         foreach ($this->order as $key => $ans) {
260             if (array_key_exists($this->field($key), $response) &&
261                     question_state::graded_state_for_fraction(
262                     $this->answers[$ans]->fraction)->is_incorrect()) {
263                 $response[$this->field($key)] = 0;
264             }
265         }
266         return $response;
267     }
269     public function get_num_parts_right(array $response) {
270         $numright = 0;
271         foreach ($this->order as $key => $ans) {
272             $fieldname = $this->field($key);
273             if (!array_key_exists($fieldname, $response) || !$response[$fieldname]) {
274                 continue;
275             }
277             if (!question_state::graded_state_for_fraction(
278                     $this->answers[$ans]->fraction)->is_incorrect()) {
279                 $numright += 1;
280             }
281         }
282         return array($numright, count($this->order));
283     }
285     /**
286      * @param int $key choice number
287      * @return string the question-type variable name.
288      */
289     protected function field($key) {
290         return 'choice' . $key;
291     }
293     public function get_expected_data() {
294         $expected = array();
295         foreach ($this->order as $key => $notused) {
296             $expected[$this->field($key)] = PARAM_BOOL;
297         }
298         return $expected;
299     }
301     public function summarise_response(array $response) {
302         $selectedchoices = array();
303         foreach ($this->order as $key => $ans) {
304             $fieldname = $this->field($key);
305             if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
306                 $selectedchoices[] = $this->html_to_text($this->answers[$ans]->answer,
307                         $this->answers[$ans]->answerformat);
308             }
309         }
310         if (empty($selectedchoices)) {
311             return null;
312         }
313         return implode('; ', $selectedchoices);
314     }
316     public function classify_response(array $response) {
317         $selectedchoices = array();
318         foreach ($this->order as $key => $ansid) {
319             $fieldname = $this->field($key);
320             if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
321                 $selectedchoices[$ansid] = 1;
322             }
323         }
324         $choices = array();
325         foreach ($this->answers as $ansid => $ans) {
326             if (isset($selectedchoices[$ansid])) {
327                 $choices[$ansid] = new question_classified_response($ansid,
328                         $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction);
329             }
330         }
331         return $choices;
332     }
334     public function get_correct_response() {
335         $response = array();
336         foreach ($this->order as $key => $ans) {
337             if (!question_state::graded_state_for_fraction(
338                     $this->answers[$ans]->fraction)->is_incorrect()) {
339                 $response[$this->field($key)] = 1;
340             }
341         }
342         return $response;
343     }
345     public function prepare_simulated_post_data($simulatedresponse) {
346         $postdata = array();
347         $ansidtochoiceno = array_flip($this->order);
348         ksort($ansidtochoiceno, SORT_NUMERIC);
349         $ansnotochoiceno = array_values($ansidtochoiceno);
350         foreach ($simulatedresponse as $ansno => $checked) {
351             $postdata[$this->field($ansnotochoiceno[$ansno])] = $checked;
352         }
353         return $postdata;
354     }
356     public function is_same_response(array $prevresponse, array $newresponse) {
357         foreach ($this->order as $key => $notused) {
358             $fieldname = $this->field($key);
359             if (!question_utils::arrays_same_at_key_integer($prevresponse, $newresponse, $fieldname)) {
360                 return false;
361             }
362         }
363         return true;
364     }
366     public function is_complete_response(array $response) {
367         foreach ($this->order as $key => $notused) {
368             if (!empty($response[$this->field($key)])) {
369                 return true;
370             }
371         }
372         return false;
373     }
375     public function is_gradable_response(array $response) {
376         return $this->is_complete_response($response);
377     }
379     /**
380      * @param array $response responses, as returned by
381      *      {@link question_attempt_step::get_qt_data()}.
382      * @return int the number of choices that were selected. in this response.
383      */
384     public function get_num_selected_choices(array $response) {
385         $numselected = 0;
386         foreach ($response as $key => $value) {
387             if (!empty($value)) {
388                 $numselected += 1;
389             }
390         }
391         return $numselected;
392     }
394     /**
395      * @return int the number of choices that are correct.
396      */
397     public function get_num_correct_choices() {
398         $numcorrect = 0;
399         foreach ($this->answers as $ans) {
400             if (!question_state::graded_state_for_fraction($ans->fraction)->is_incorrect()) {
401                 $numcorrect += 1;
402             }
403         }
404         return $numcorrect;
405     }
407     public function grade_response(array $response) {
408         $fraction = 0;
409         foreach ($this->order as $key => $ansid) {
410             if (!empty($response[$this->field($key)])) {
411                 $fraction += $this->answers[$ansid]->fraction;
412             }
413         }
414         $fraction = min(max(0, $fraction), 1.0);
415         return array($fraction, question_state::graded_state_for_fraction($fraction));
416     }
418     public function get_validation_error(array $response) {
419         if ($this->is_gradable_response($response)) {
420             return '';
421         }
422         return get_string('pleaseselectatleastoneanswer', 'qtype_multichoice');
423     }
425     /**
426      * Disable those hint settings that we don't want when the student has selected
427      * more choices than the number of right choices. This avoids giving the game away.
428      * @param question_hint_with_parts $hint a hint.
429      */
430     protected function disable_hint_settings_when_too_many_selected(
431             question_hint_with_parts $hint) {
432         $hint->clearwrong = false;
433     }
435     public function get_hint($hintnumber, question_attempt $qa) {
436         $hint = parent::get_hint($hintnumber, $qa);
437         if (is_null($hint)) {
438             return $hint;
439         }
441         if ($this->get_num_selected_choices($qa->get_last_qt_data()) >
442                 $this->get_num_correct_choices()) {
443             $hint = clone($hint);
444             $this->disable_hint_settings_when_too_many_selected($hint);
445         }
446         return $hint;
447     }
449     public function get_response(question_attempt $qa) {
450         return $qa->get_last_qt_data();
451     }
453     public function is_choice_selected($response, $value) {
454         return !empty($response['choice' . $value]);
455     }