MDL-20636 converstion of questionlib.php and base questiontype.php, plus other cheang...
[moodle.git] / question / type / questionbase.php
CommitLineData
d1b7e03d
TH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18
19/**
20 * This file defines the class {@link question_definition} and its subclasses.
21 *
22 * @package moodlecore
23 * @subpackage questiontypes
24 * @copyright 2009 The Open University
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28
29/**
30 * The definition of a question of a particular type.
31 *
32 * This class is a close match to the question table in the database.
33 * Definitions of question of a particular type normally subclass one of the
34 * more specific classes {@link question_with_responses},
35 * {@link question_graded_automatically} or {@link question_information_item}.
36 *
37 * @copyright 2009 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40abstract class question_definition {
41 /** @var integer id of the question in the datase, or null if this question
42 * is not in the database. */
43 public $id;
44
45 /** @var integer question category id. */
46 public $category;
47
48 /** @var integer parent question id. */
49 public $parent = 0;
50
51 /** @var question_type the question type this question is. */
52 public $qtype;
53
54 /** @var string question name. */
55 public $name;
56
57 /** @var string question text. */
58 public $questiontext;
59
60 /** @var integer question test format. */
61 public $questiontextformat;
62
63 /** @var string question general feedback. */
64 public $generalfeedback;
65
66 /** @var number what this quetsion is marked out of, by default. */
67 public $defaultmark = 1;
68
69 /** @var integer How many question numbers this question consumes. */
70 public $length = 1;
71
72 /** @var number penalty factor of this question. */
73 public $penalty = 0;
74
75 /** @var string unique identifier of this question. */
76 public $stamp;
77
78 /** @var string unique identifier of this version of this question. */
79 public $version;
80
81 /** @var boolean whethre this question has been deleted/hidden in the question bank. */
82 public $hidden = 0;
83
84 /** @var integer timestamp when this question was created. */
85 public $timecreated;
86
87 /** @var integer timestamp when this question was modified. */
88 public $timemodified;
89
90 /** @var integer userid of the use who created this question. */
91 public $createdby;
92
93 /** @var integer userid of the use who modified this question. */
94 public $modifiedby;
95
96 /** @var array of question_hints. */
97 public $hints = array();
98
99 /**
100 * Constructor. Normally to get a question, you call
101 * {@link question_bank::load_question()}, but questions can be created
102 * directly, for example in unit test code.
103 * @return unknown_type
104 */
105 public function __construct() {
106 }
107
108 /**
109 * @return the name of the question type (for example multichoice) that this
110 * question is.
111 */
112 public function get_type_name() {
113 return $this->qtype->name();
114 }
115
116 /**
117 * Creat the appropriate behaviour for an attempt at this quetsion,
118 * given the desired (archetypal) behaviour.
119 *
120 * This default implementation will suit most normal graded questions.
121 *
122 * If your question is of a patricular type, then it may need to do something
123 * different. For example, if your question can only be graded manually, then
124 * it should probably return a manualgraded behaviour, irrespective of
125 * what is asked for.
126 *
127 * If your question wants to do somthing especially complicated is some situations,
128 * then you may wish to return a particular behaviour related to the
129 * one asked for. For example, you migth want to return a
130 * qbehaviour_interactive_adapted_for_myqtype.
131 *
132 * @param question_attempt $qa the attempt we are creating an behaviour for.
133 * @param string $preferredbehaviour the requested type of behaviour.
134 * @return question_behaviour the new behaviour object.
135 */
136 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
137 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
138 }
139
140 /**
141 * Initialise the first step of an attempt at this quetsion.
142 *
143 * For example, the multiple choice question type uses this method to
144 * randomly shuffle the choices, if that option has been set in the question.
145 * It then stores that order by calling $step->set_qt_var(...).
146 *
147 * @param question_attempt_step $step the step to be initialised.
148 */
149 public function init_first_step(question_attempt_step $step) {
150 }
151
152 /**
153 * Generate a brief, plain-text, summary of this question. This is used by
154 * various reports. This should show the particular variant of the question
155 * as presented to students. For example, the calculated quetsion type would
156 * fill in the particular numbers that were presented to the student.
157 * This method will return null if such a summary is not possible, or
158 * inappropriate.
159 * @return string|null a plain text summary of this question.
160 */
161 public function get_question_summary() {
162 return html_to_text($this->format_questiontext(), 0, false);
163 }
164
165 /**
166 * Some questions can return a negative mark if the student gets it wrong.
167 *
168 * This method returns the lowest mark the question can return, on the
169 * fraction scale. that is, where the maximum possible mark is 1.0.
170 *
171 * @return number minimum fraction this question will ever return.
172 */
173 public function get_min_fraction() {
174 return 0;
175 }
176
177 /**
178 * Given a response, rest the parts that are wrong.
179 * @param array $response a response
180 * @return array a cleaned up response with the wrong bits reset.
181 */
182 public function clear_wrong_from_response(array $response) {
183 return array();
184 }
185
186 /**
187 * Return the number of subparts of this response that are right.
188 * @param array $response a response
189 * @return array with two elements, the number of correct subparts, and
190 * the total number of subparts.
191 */
192 public function get_num_parts_right(array $response) {
193 return array(null, null);
194 }
195
196 /**
197 * @return qtype_renderer the renderer to use for outputting this question.
198 */
199 public function get_renderer() {
200 return renderer_factory::get_renderer('qtype_' . $this->qtype->name());
201 }
202
203 /**
204 * What data may be included in the form submission when a student submits
205 * this question in its current state?
206 *
207 * This information is used in calls to optional_param. The parameter name
208 * has {@link question_attempt::get_field_prefix()} automatically prepended.
209 *
210 * @return array|string variable name => PARAM_... constant, or, as a special case
211 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
212 * meaning take all the raw submitted data belonging to this question.
213 */
214 public abstract function get_expected_data();
215
216 /**
217 * What data would need to be submitted to get this question correct.
218 * If there is more than one correct answer, this method should just
219 * return one possibility.
220 *
221 * @return array parameter name => value.
222 */
223 public abstract function get_correct_response();
224
225 /**
226 * Apply {@link format_text()} to some content with appropriate settings for
227 * this question.
228 *
229 * @param string $text some content that needs to be output.
230 * @param boolean $clean Whether the HTML needs to be cleaned. Generally,
231 * parts of the question do not need to be cleaned, and student input does.
232 * @return string the text formatted for output by format_text.
233 */
234 public function format_text($text, $clean = false) {
235 $formatoptions = new stdClass;
236 $formatoptions->noclean = !$clean;
237 $formatoptions->para = false;
238
239 return format_text($text, $this->questiontextformat, $formatoptions);
240 }
241
242 /** @return the result of applying {@link format_text()} to the question text. */
243 public function format_questiontext() {
244 return $this->format_text($this->questiontext);
245 }
246
247 /** @return the result of applying {@link format_text()} to the general feedback. */
248 public function format_generalfeedback() {
249 return $this->format_text($this->generalfeedback);
250 }
251}
252
253
254/**
255 * This class represents a 'question' that actually does not allow the student
256 * to respond, like the description 'question' type.
257 *
258 * @copyright 2009 The Open University
259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
260 */
261class question_information_item extends question_definition {
262 public function __construct() {
263 parent::__construct();
264 $this->defaultmark = 0;
265 $this->penalty = 0;
266 $this->length = 0;
267 }
268
269 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
270 question_engine::load_behaviour_class('informationitem');
271 return new qbehaviour_informationitem($qa, $preferredbehaviour);
272 }
273
274 public function get_expected_data() {
275 return array();
276 }
277
278 public function get_correct_response() {
279 return array();
280 }
281
282 public function get_question_summary() {
283 return null;
284 }
285}
286
287
288/**
289 * Interface that a {@link question_definition} must implement to be usable by
290 * the manual graded behaviour.
291 *
292 * @copyright 2009 The Open University
293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
294 */
295interface question_manually_gradable {
296 /**
297 * Used by many of the behaviours, to work out whether the student's
298 * response to the question is complete. That is, whether the question attempt
299 * should move to the COMPLETE or INCOMPLETE state.
300 *
301 * @param array $response responses, as returned by {@link question_attempt_step::get_qt_data()}.
302 * @return boolean whether this response is a complete answer to this question.
303 */
304 public function is_complete_response(array $response);
305
306 /**
307 * Use by many of the behaviours to determine whether the student's
308 * response has changed. This is normally used to determine that a new set
309 * of responses can safely be discarded.
310 *
311 * @param array $prevresponse the responses previously recorded for this question,
312 * as returned by {@link question_attempt_step::get_qt_data()}
313 * @param array $newresponse the new responses, in the same format.
314 * @return boolean whether the two sets of responses are the same - that is
315 * whether the new set of responses can safely be discarded.
316 */
317 public function is_same_response(array $prevresponse, array $newresponse);
318
319 /**
320 * Produce a plain text summary of a response.
321 * @param $response a response, as might be passed to {@link grade_response()}.
322 * @return string a plain text summary of that response, that could be used in reports.
323 */
324 public function summarise_response(array $response);
325
326 /**
327 * Categorise the student's response according to the categories defined by
328 * get_possible_responses.
329 * @param $response a response, as might be passed to {@link grade_response()}.
330 * @return array subpartid => {@link question_classified_response} objects.
331 * returns an empty array if no analysis is possible.
332 */
333 public function classify_response(array $response);
334}
335
336
337/**
338 * This class is used in the return value from
339 * {@link question_manually_gradable::classify_response()}.
340 *
341 * @copyright 2010 The Open University
342 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
343 */
344class question_classified_response {
345 /**
346 * @var string the classification of this response the student gave to this
347 * part of the question. Must match one of the responseclasses returned by
348 * {@link question_type::get_possible_responses()}.
349 */
350 public $responseclassid;
351 /** @var string the actual response the student gave to this part. */
352 public $response;
353 /** @var number the fraction this part of the response earned. */
354 public $fraction;
355 /**
356 * Constructor, just an easy way to set the fields.
357 * @param string $responseclassid see the field descriptions above.
358 * @param string $response see the field descriptions above.
359 * @param number $fraction see the field descriptions above.
360 */
361 public function __construct($responseclassid, $response, $fraction) {
362 $this->responseclassid = $responseclassid;
363 $this->response = $response;
364 $this->fraction = $fraction;
365 }
366
367 public static function no_response() {
368 return new question_classified_response(null, null, null);
369 }
370}
371
372
373/**
374 * Interface that a {@link question_definition} must implement to be usable by
375 * the various automatic grading behaviours.
376 *
377 * @copyright 2009 The Open University
378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
379 */
380interface question_automatically_gradable extends question_manually_gradable {
381 /**
382 * Use by many of the behaviours to determine whether the student
383 * has provided enough of an answer for the question to be graded automatically,
384 * or whether it must be considered aborted.
385 *
386 * @param array $response responses, as returned by {@link question_attempt_step::get_qt_data()}.
387 * @return boolean whether this response can be graded.
388 */
389 public function is_gradable_response(array $response);
390
391 /**
392 * In situations where is_gradable_response() returns false, this method
393 * should generate a description of what the problem is.
394 * @return string the message.
395 */
396 public function get_validation_error(array $response);
397
398 /**
399 * Grade a response to the question, returning a fraction between get_min_fraction() and 1.0,
400 * and the corresponding state CORRECT, PARTIALLY_CORRECT or INCORRECT.
401 * @param array $response responses, as returned by {@link question_attempt_step::get_qt_data()}.
402 * @return array (number, integer) the fraction, and the state.
403 */
404 public function grade_response(array $response);
405
406 /**
407 * Get one of the question hints. The question_attempt is passed in case
408 * the question type wants to do something complex. For example, the
409 * multiple choice with multiple responses question type will turn off most
410 * of the hint options if the student has selected too many opitions.
411 * @param integer $hintnumber Which hint to display. Indexed starting from 0
412 * @param question_attempt $qa The question_attempt.
413 */
414 public function get_hint($hintnumber, question_attempt $qa);
415
416 /**
417 * Generate a brief, plain-text, summary of the correct answer to this question.
418 * This is used by various reports, and can also be useful when testing.
419 * This method will return null if such a summary is not possible, or
420 * inappropriate.
421 * @return string|null a plain text summary of the right answer to this question.
422 */
423 public function get_right_answer_summary();
424}
425
426
427/**
428 * Interface that a {@link question_definition} must implement to be usable by
429 * the interactivecountback behaviour.
430 *
431 * @copyright 2010 The Open University
432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
433 */
434interface question_automatically_gradable_with_countback extends question_automatically_gradable {
435 /**
436 * Work out a final grade for this attempt, taking into account all the
437 * tries the student made.
438 * @param array $responses the response for each try. Each element of this
439 * array is a response array, as would be passed to {@link grade_response()}.
440 * There may be between 1 and $totaltries responses.
441 * @param integer $totaltries The maximum number of tries allowed.
442 * @return numeric the fraction that should be awarded for this
443 * sequence of response.
444 */
445 public function compute_final_grade($responses, $totaltries);
446}
447
448
449/**
450 * This class represents a real question. That is, one that is not a
451 * {@link question_information_item}.
452 *
453 * @copyright 2009 The Open University
454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
455 */
456abstract class question_with_responses extends question_definition
457 implements question_manually_gradable {
458 function classify_response(array $response) {
459 return array();
460 }
461}
462
463
464/**
465 * This class represents a question that can be graded automatically.
466 *
467 * @copyright 2009 The Open University
468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
469 */
470abstract class question_graded_automatically extends question_with_responses
471 implements question_automatically_gradable {
472 /** @var Some question types have the option to show the number of sub-parts correct. */
473 public $shownumcorrect = false;
474
475 public function is_gradable_response(array $response) {
476 return $this->is_complete_response($response);
477 }
478
479 public function get_right_answer_summary() {
480 $correctresponse = $this->get_correct_response();
481 if (empty($correctresponse)) {
482 return null;
483 }
484 return $this->summarise_response($correctresponse);
485 }
486
487 public function get_hint($hintnumber, question_attempt $qa) {
488 if (!isset($this->hints[$hintnumber])) {
489 return null;
490 }
491 return $this->hints[$hintnumber];
492 }
493}
494
495
496/**
497 * This class represents a question that can be graded automatically with
498 * countback grading in interactive mode.
499 *
500 * @copyright 2010 The Open University
501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
502 */
503abstract class question_graded_automatically_with_countback
504 extends question_graded_automatically
505 implements question_automatically_gradable_with_countback {
506
507 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
508 if ($preferredbehaviour == 'interactive') {
509 return question_engine::make_behaviour('interactivecountback', $qa, $preferredbehaviour);
510 }
511 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
512 }
513}
514
515
516/**
517 * This class represents a question that can be graded automatically by using
518 * a {@link question_grading_strategy}.
519 *
520 * @copyright 2009 The Open University
521 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
522 */
523abstract class question_graded_by_strategy extends question_graded_automatically {
524 /** @var question_grading_strategy the strategy to use for grading. */
525 protected $gradingstrategy;
526
527 /** @param question_grading_strategy $strategy the strategy to use for grading. */
528 public function __construct(question_grading_strategy $strategy) {
529 parent::__construct();
530 $this->gradingstrategy = $strategy;
531 }
532
533 public function get_correct_response() {
534 $answer = $this->get_correct_answer();
535 if (!$answer) {
536 return array();
537 }
538
539 return array('answer' => $answer->answer);
540 }
541
542 /**
543 * Get an answer that contains the feedback and fraction that should be
544 * awarded for this resonse.
545 * @param array $response a response.
546 * @return question_answer the matching answer.
547 */
548 public function get_matching_answer(array $response) {
549 return $this->gradingstrategy->grade($response);
550 }
551
552 /**
553 * @return question_answer an answer that contains the a response that would
554 * get full marks.
555 */
556 public function get_correct_answer() {
557 return $this->gradingstrategy->get_correct_answer();
558 }
559
560 public function grade_response(array $response) {
561 $answer = $this->get_matching_answer($response);
562 if ($answer) {
563 return array($answer->fraction, question_state::graded_state_for_fraction($answer->fraction));
564 } else {
565 return array(0, question_state::$gradedwrong);
566 }
567 }
568
569 public function classify_response(array $response) {
570 if (empty($response['answer'])) {
571 return array($this->id => question_classified_response::no_response());
572 }
573
574 $ans = $this->get_matching_answer($response);
575 if (!$ans) {
576 return array($this->id => question_classified_response::no_response());
577 }
578 return array($this->id => new question_classified_response(
579 $ans->id, $response['answer'], $ans->fraction));
580 }
581}
582
583
584/**
585 * Class to represent a question answer, loaded from the question_answers table
586 * in the database.
587 *
588 * @copyright 2009 The Open University
589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
590 */
591class question_answer {
592 /** @var string the answer. */
593 public $answer;
594
595 /** @var number the fraction this answer is worth. */
596 public $fraction;
597
598 /** @var string the feedback for this answer. */
599 public $feedback;
600
601 /**
602 * Constructor.
603 * @param string $answer the answer.
604 * @param number $fraction the fraction this answer is worth.
605 * @param string $feedback the feedback for this answer.
606 */
607 public function __construct($answer, $fraction, $feedback) {
608 $this->answer = $answer;
609 $this->fraction = $fraction;
610 $this->feedback = $feedback;
611 }
612}
613
614
615/**
616 * Class to represent a hint associated with a question.
617 * Used by iteractive mode, etc. A question has an array of these.
618 *
619 * @copyright 2010 The Open University
620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
621 */
622class question_hint {
623 /** @var The feedback hint to be shown. */
624 public $hint;
625
626 /**
627 * Constructor.
628 * @param string $hint The hint text
629 */
630 public function __construct($hint) {
631 $this->hint = $hint;
632 }
633
634 /**
635 * Create a basic hint from a row loaded from the question_hints table in the database.
636 * @param object $row with $row->hint set.
637 * @return question_hint
638 */
639 public static function load_from_record($row) {
640 return new question_hint($row->hint);
641 }
642
643 /**
644 * Adjust this display options according to the hint settings.
645 * @param question_display_options $options
646 */
647 public function adjust_display_options(question_display_options $options) {
648 // Do nothing.
649 }
650}
651
652
653/**
654 * An extension of {@link question_hint} for questions like match and multiple
655 * choice with multile answers, where there are options for whether to show the
656 * number of parts right at each stage, and to reset the wrong parts.
657 *
658 * @copyright 2010 The Open University
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
660 */
661class question_hint_with_parts extends question_hint {
662 /** @var boolean option to show the number of sub-parts of the question that were right. */
663 public $shownumcorrect;
664
665 /** @var boolean option to clear the parts of the question that were wrong on retry. */
666 public $clearwrong;
667
668 /**
669 * Constructor.
670 * @param string $hint The hint text
671 * @param boolean $shownumcorrect whether the number of right parts should be shown
672 * @param boolean $clearwrong whether the wrong parts should be reset.
673 */
674 public function __construct($hint, $shownumcorrect, $clearwrong) {
675 parent::__construct($hint);
676 $this->shownumcorrect = $shownumcorrect;
677 $this->clearwrong = $clearwrong;
678 }
679
680 /**
681 * Create a basic hint from a row loaded from the question_hints table in the database.
682 * @param object $row with $row->hint, ->shownumcorrect and ->clearwrong set.
683 * @return question_hint_with_parts
684 */
685 public static function load_from_record($row) {
686 return new question_hint_with_parts($row->hint, $row->shownumcorrect, $row->clearwrong);
687 }
688
689 public function adjust_display_options(question_display_options $options) {
690 parent::adjust_display_options($options);
691 if ($this->clearwrong) {
692 $options->clearwrong = true;
693 }
694 $options->numpartscorrect = $this->shownumcorrect;
695 }
696}
697
698
699/**
700 * This question_grading_strategy interface. Used to share grading code between
701 * questions that that subclass {@link question_graded_by_strategy}.
702 *
703 * @copyright 2009 The Open University
704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
705 */
706interface question_grading_strategy {
707 /**
708 * Return a question answer that describes the outcome (fraction and feeback)
709 * for a particular respons.
710 * @param array $response the response.
711 * @return question_answer the answer describing the outcome.
712 */
713 public function grade(array $response);
714
715 /**
716 * @return question_answer an answer that contains the a response that would
717 * get full marks.
718 */
719 public function get_correct_answer();
720}
721
722
723/**
724 * This interface defines the methods that a {@link question_definition} must
725 * implement if it is to be graded by the
726 * {@link question_first_matching_answer_grading_strategy}.
727 *
728 * @copyright 2009 The Open University
729 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
730 */
731interface question_response_answer_comparer {
732 /** @return array of {@link question_answers}. */
733 public function get_answers();
734
735 /**
736 * @param array $response the response.
737 * @param question_answer $answer an answer.
738 * @return boolean whether the response matches the answer.
739 */
740 public function compare_response_with_answer(array $response, question_answer $answer);
741}
742
743
744/**
745 * This grading strategy is used by question types like shortanswer an numerical.
746 * It gets a list of possible answers from the question, and returns the first one
747 * that matches the given response. It returns the first answer with fraction 1.0
748 * when asked for the correct answer.
749 *
750 * @copyright 2009 The Open University
751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
752 */
753class question_first_matching_answer_grading_strategy implements question_grading_strategy {
754 /**
755 * @var question_response_answer_comparer (presumably also a
756 * {@link question_definition}) the question we are doing the grading for.
757 */
758 protected $question;
759
760 /**
761 * @param question_response_answer_comparer $question (presumably also a
762 * {@link question_definition}) the question we are doing the grading for.
763 */
764 public function __construct(question_response_answer_comparer $question) {
765 $this->question = $question;
766 }
767
768 public function grade(array $response) {
769 foreach ($this->question->get_answers() as $aid => $answer) {
770 if ($this->question->compare_response_with_answer($response, $answer)) {
771 $answer->id = $aid;
772 return $answer;
773 }
774 }
775 return null;
776 }
777
778 public function get_correct_answer() {
779 foreach ($this->question->get_answers() as $answer) {
780 $state = question_state::graded_state_for_fraction($answer->fraction);
781 if ($state == question_state::$gradedright) {
782 return $answer;
783 }
784 }
785 return null;
786 }
787}