MDL-41311 tool_generator: remove legacy code
[moodle.git] / question / type / questionbase.php
blob448d200f5bc279e3b3daa1e36971ad98e518a638
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.
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 * This file defines the class {@link question_definition} and its subclasses.
20 * The type hierarchy is quite complex. Here is a summary:
21 * - question_definition
22 * - question_information_item
23 * - question_with_responses implements question_manually_gradable
24 * - question_graded_automatically implements question_automatically_gradable
25 * - question_graded_automatically_with_countback implements question_automatically_gradable_with_countback
26 * - question_graded_by_strategy
28 * Other classes:
29 * - question_classified_response
30 * - question_answer
31 * - question_hint
32 * - question_hint_with_parts
33 * - question_first_matching_answer_grading_strategy implements question_grading_strategy
35 * Other interfaces:
36 * - question_response_answer_comparer
38 * @package moodlecore
39 * @subpackage questiontypes
40 * @copyright 2009 The Open University
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 defined('MOODLE_INTERNAL') || die();
48 /**
49 * The definition of a question of a particular type.
51 * This class is a close match to the question table in the database.
52 * Definitions of question of a particular type normally subclass one of the
53 * more specific classes {@link question_with_responses},
54 * {@link question_graded_automatically} or {@link question_information_item}.
56 * @copyright 2009 The Open University
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 abstract class question_definition {
60 /** @var integer id of the question in the datase, or null if this question
61 * is not in the database. */
62 public $id;
64 /** @var integer question category id. */
65 public $category;
67 /** @var integer question context id. */
68 public $contextid;
70 /** @var integer parent question id. */
71 public $parent = 0;
73 /** @var question_type the question type this question is. */
74 public $qtype;
76 /** @var string question name. */
77 public $name;
79 /** @var string question text. */
80 public $questiontext;
82 /** @var integer question test format. */
83 public $questiontextformat;
85 /** @var string question general feedback. */
86 public $generalfeedback;
88 /** @var integer question test format. */
89 public $generalfeedbackformat;
91 /** @var number what this quetsion is marked out of, by default. */
92 public $defaultmark = 1;
94 /** @var integer How many question numbers this question consumes. */
95 public $length = 1;
97 /** @var number penalty factor of this question. */
98 public $penalty = 0;
100 /** @var string unique identifier of this question. */
101 public $stamp;
103 /** @var string unique identifier of this version of this question. */
104 public $version;
106 /** @var boolean whethre this question has been deleted/hidden in the question bank. */
107 public $hidden = 0;
109 /** @var integer timestamp when this question was created. */
110 public $timecreated;
112 /** @var integer timestamp when this question was modified. */
113 public $timemodified;
115 /** @var integer userid of the use who created this question. */
116 public $createdby;
118 /** @var integer userid of the use who modified this question. */
119 public $modifiedby;
121 /** @var array of question_hints. */
122 public $hints = array();
125 * Constructor. Normally to get a question, you call
126 * {@link question_bank::load_question()}, but questions can be created
127 * directly, for example in unit test code.
128 * @return unknown_type
130 public function __construct() {
134 * @return the name of the question type (for example multichoice) that this
135 * question is.
137 public function get_type_name() {
138 return $this->qtype->name();
142 * Creat the appropriate behaviour for an attempt at this quetsion,
143 * given the desired (archetypal) behaviour.
145 * This default implementation will suit most normal graded questions.
147 * If your question is of a patricular type, then it may need to do something
148 * different. For example, if your question can only be graded manually, then
149 * it should probably return a manualgraded behaviour, irrespective of
150 * what is asked for.
152 * If your question wants to do somthing especially complicated is some situations,
153 * then you may wish to return a particular behaviour related to the
154 * one asked for. For example, you migth want to return a
155 * qbehaviour_interactive_adapted_for_myqtype.
157 * @param question_attempt $qa the attempt we are creating an behaviour for.
158 * @param string $preferredbehaviour the requested type of behaviour.
159 * @return question_behaviour the new behaviour object.
161 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
162 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
166 * Start a new attempt at this question, storing any information that will
167 * be needed later in the step.
169 * This is where the question can do any initialisation required on a
170 * per-attempt basis. For example, this is where the multiple choice
171 * question type randomly shuffles the choices (if that option is set).
173 * Any information about how the question has been set up for this attempt
174 * should be stored in the $step, by calling $step->set_qt_var(...).
176 * @param question_attempt_step The first step of the {@link question_attempt}
177 * being started. Can be used to store state.
178 * @param int $varant which variant of this question to start. Will be between
179 * 1 and {@link get_num_variants()} inclusive.
181 public function start_attempt(question_attempt_step $step, $variant) {
185 * When an in-progress {@link question_attempt} is re-loaded from the
186 * database, this method is called so that the question can re-initialise
187 * its internal state as needed by this attempt.
189 * For example, the multiple choice question type needs to set the order
190 * of the choices to the order that was set up when start_attempt was called
191 * originally. All the information required to do this should be in the
192 * $step object, which is the first step of the question_attempt being loaded.
194 * @param question_attempt_step The first step of the {@link question_attempt}
195 * being loaded.
197 public function apply_attempt_state(question_attempt_step $step) {
201 * Generate a brief, plain-text, summary of this question. This is used by
202 * various reports. This should show the particular variant of the question
203 * as presented to students. For example, the calculated quetsion type would
204 * fill in the particular numbers that were presented to the student.
205 * This method will return null if such a summary is not possible, or
206 * inappropriate.
207 * @return string|null a plain text summary of this question.
209 public function get_question_summary() {
210 return $this->html_to_text($this->questiontext, $this->questiontextformat);
214 * @return int the number of vaiants that this question has.
216 public function get_num_variants() {
217 return 1;
221 * @return string that can be used to seed the pseudo-random selection of a
222 * variant.
224 public function get_variants_selection_seed() {
225 return $this->stamp;
229 * Some questions can return a negative mark if the student gets it wrong.
231 * This method returns the lowest mark the question can return, on the
232 * fraction scale. that is, where the maximum possible mark is 1.0.
234 * @return number minimum fraction this question will ever return.
236 public function get_min_fraction() {
237 return 0;
241 * Given a response, rest the parts that are wrong.
242 * @param array $response a response
243 * @return array a cleaned up response with the wrong bits reset.
245 public function clear_wrong_from_response(array $response) {
246 return array();
250 * Return the number of subparts of this response that are right.
251 * @param array $response a response
252 * @return array with two elements, the number of correct subparts, and
253 * the total number of subparts.
255 public function get_num_parts_right(array $response) {
256 return array(null, null);
260 * @param moodle_page the page we are outputting to.
261 * @return qtype_renderer the renderer to use for outputting this question.
263 public function get_renderer(moodle_page $page) {
264 return $page->get_renderer($this->qtype->plugin_name());
268 * What data may be included in the form submission when a student submits
269 * this question in its current state?
271 * This information is used in calls to optional_param. The parameter name
272 * has {@link question_attempt::get_field_prefix()} automatically prepended.
274 * @return array|string variable name => PARAM_... constant, or, as a special case
275 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
276 * meaning take all the raw submitted data belonging to this question.
278 public abstract function get_expected_data();
281 * What data would need to be submitted to get this question correct.
282 * If there is more than one correct answer, this method should just
283 * return one possibility. If it is not possible to compute a correct
284 * response, this method should return null.
286 * @return array|null parameter name => value.
288 public abstract function get_correct_response();
292 * Passed an array of data representing a student response this function transforms the array to a response array as would be
293 * returned from the html form for this question instance.
295 * In most cases the array will just be returned as is. Some question types will need to transform the keys of the array in
296 * as the meaning of the keys in the html form is deliberately obfuscated so that someone looking at the html does not get an
297 * advantage.
299 * @param array $simulatedresponse an array of data representing a student response
300 * @return array a response array as would be returned from the html form (but without prefixes)
302 public function prepare_simulated_post_data($simulatedresponse) {
303 return $simulatedresponse;
307 * Apply {@link format_text()} to some content with appropriate settings for
308 * this question.
310 * @param string $text some content that needs to be output.
311 * @param int $format the FORMAT_... constant.
312 * @param question_attempt $qa the question attempt.
313 * @param string $component used for rewriting file area URLs.
314 * @param string $filearea used for rewriting file area URLs.
315 * @param bool $clean Whether the HTML needs to be cleaned. Generally,
316 * parts of the question do not need to be cleaned, and student input does.
317 * @return string the text formatted for output by format_text.
319 public function format_text($text, $format, $qa, $component, $filearea, $itemid,
320 $clean = false) {
321 $formatoptions = new stdClass();
322 $formatoptions->noclean = !$clean;
323 $formatoptions->para = false;
324 $text = $qa->rewrite_pluginfile_urls($text, $component, $filearea, $itemid);
325 return format_text($text, $format, $formatoptions);
329 * Convert some part of the question text to plain text. This might be used,
330 * for example, by get_response_summary().
331 * @param string $text The HTML to reduce to plain text.
332 * @param int $format the FORMAT_... constant.
333 * @return string the equivalent plain text.
335 public function html_to_text($text, $format) {
336 return question_utils::to_plain_text($text, $format);
339 /** @return the result of applying {@link format_text()} to the question text. */
340 public function format_questiontext($qa) {
341 return $this->format_text($this->questiontext, $this->questiontextformat,
342 $qa, 'question', 'questiontext', $this->id);
345 /** @return the result of applying {@link format_text()} to the general feedback. */
346 public function format_generalfeedback($qa) {
347 return $this->format_text($this->generalfeedback, $this->generalfeedbackformat,
348 $qa, 'question', 'generalfeedback', $this->id);
352 * Checks whether the users is allow to be served a particular file.
353 * @param question_attempt $qa the question attempt being displayed.
354 * @param question_display_options $options the options that control display of the question.
355 * @param string $component the name of the component we are serving files for.
356 * @param string $filearea the name of the file area.
357 * @param array $args the remaining bits of the file path.
358 * @param bool $forcedownload whether the user must be forced to download the file.
359 * @return bool true if the user can access this file.
361 public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
362 if ($component == 'question' && $filearea == 'questiontext') {
363 // Question text always visible.
364 return true;
366 } else if ($component == 'question' && $filearea == 'generalfeedback') {
367 return $options->generalfeedback;
369 } else {
370 // Unrecognised component or filearea.
371 return false;
378 * This class represents a 'question' that actually does not allow the student
379 * to respond, like the description 'question' type.
381 * @copyright 2009 The Open University
382 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
384 class question_information_item extends question_definition {
385 public function __construct() {
386 parent::__construct();
387 $this->defaultmark = 0;
388 $this->penalty = 0;
389 $this->length = 0;
392 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
393 question_engine::load_behaviour_class('informationitem');
394 return new qbehaviour_informationitem($qa, $preferredbehaviour);
397 public function get_expected_data() {
398 return array();
401 public function get_correct_response() {
402 return array();
405 public function get_question_summary() {
406 return null;
412 * Interface that a {@link question_definition} must implement to be usable by
413 * the manual graded behaviour.
415 * @copyright 2009 The Open University
416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
418 interface question_manually_gradable {
420 * Used by many of the behaviours, to work out whether the student's
421 * response to the question is complete. That is, whether the question attempt
422 * should move to the COMPLETE or INCOMPLETE state.
424 * @param array $response responses, as returned by
425 * {@link question_attempt_step::get_qt_data()}.
426 * @return bool whether this response is a complete answer to this question.
428 public function is_complete_response(array $response);
431 * Use by many of the behaviours to determine whether the student's
432 * response has changed. This is normally used to determine that a new set
433 * of responses can safely be discarded.
435 * @param array $prevresponse the responses previously recorded for this question,
436 * as returned by {@link question_attempt_step::get_qt_data()}
437 * @param array $newresponse the new responses, in the same format.
438 * @return bool whether the two sets of responses are the same - that is
439 * whether the new set of responses can safely be discarded.
441 public function is_same_response(array $prevresponse, array $newresponse);
444 * Produce a plain text summary of a response.
445 * @param $response a response, as might be passed to {@link grade_response()}.
446 * @return string a plain text summary of that response, that could be used in reports.
448 public function summarise_response(array $response);
451 * Categorise the student's response according to the categories defined by
452 * get_possible_responses.
453 * @param $response a response, as might be passed to {@link grade_response()}.
454 * @return array subpartid => {@link question_classified_response} objects.
455 * returns an empty array if no analysis is possible.
457 public function classify_response(array $response);
462 * This class is used in the return value from
463 * {@link question_manually_gradable::classify_response()}.
465 * @copyright 2010 The Open University
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 class question_classified_response {
470 * @var string the classification of this response the student gave to this
471 * part of the question. Must match one of the responseclasses returned by
472 * {@link question_type::get_possible_responses()}.
474 public $responseclassid;
475 /** @var string the actual response the student gave to this part. */
476 public $response;
477 /** @var number the fraction this part of the response earned. */
478 public $fraction;
480 * Constructor, just an easy way to set the fields.
481 * @param string $responseclassid see the field descriptions above.
482 * @param string $response see the field descriptions above.
483 * @param number $fraction see the field descriptions above.
485 public function __construct($responseclassid, $response, $fraction) {
486 $this->responseclassid = $responseclassid;
487 $this->response = $response;
488 $this->fraction = $fraction;
491 public static function no_response() {
492 return new question_classified_response(null, get_string('noresponse', 'question'), null);
498 * Interface that a {@link question_definition} must implement to be usable by
499 * the various automatic grading behaviours.
501 * @copyright 2009 The Open University
502 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
504 interface question_automatically_gradable extends question_manually_gradable {
506 * Use by many of the behaviours to determine whether the student
507 * has provided enough of an answer for the question to be graded automatically,
508 * or whether it must be considered aborted.
510 * @param array $response responses, as returned by
511 * {@link question_attempt_step::get_qt_data()}.
512 * @return bool whether this response can be graded.
514 public function is_gradable_response(array $response);
517 * In situations where is_gradable_response() returns false, this method
518 * should generate a description of what the problem is.
519 * @return string the message.
521 public function get_validation_error(array $response);
524 * Grade a response to the question, returning a fraction between
525 * get_min_fraction() and 1.0, and the corresponding {@link question_state}
526 * right, partial or wrong.
527 * @param array $response responses, as returned by
528 * {@link question_attempt_step::get_qt_data()}.
529 * @return array (number, integer) the fraction, and the state.
531 public function grade_response(array $response);
534 * Get one of the question hints. The question_attempt is passed in case
535 * the question type wants to do something complex. For example, the
536 * multiple choice with multiple responses question type will turn off most
537 * of the hint options if the student has selected too many opitions.
538 * @param int $hintnumber Which hint to display. Indexed starting from 0
539 * @param question_attempt $qa The question_attempt.
541 public function get_hint($hintnumber, question_attempt $qa);
544 * Generate a brief, plain-text, summary of the correct answer to this question.
545 * This is used by various reports, and can also be useful when testing.
546 * This method will return null if such a summary is not possible, or
547 * inappropriate.
548 * @return string|null a plain text summary of the right answer to this question.
550 public function get_right_answer_summary();
555 * Interface that a {@link question_definition} must implement to be usable by
556 * the interactivecountback behaviour.
558 * @copyright 2010 The Open University
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
561 interface question_automatically_gradable_with_countback extends question_automatically_gradable {
563 * Work out a final grade for this attempt, taking into account all the
564 * tries the student made.
565 * @param array $responses the response for each try. Each element of this
566 * array is a response array, as would be passed to {@link grade_response()}.
567 * There may be between 1 and $totaltries responses.
568 * @param int $totaltries The maximum number of tries allowed.
569 * @return numeric the fraction that should be awarded for this
570 * sequence of response.
572 public function compute_final_grade($responses, $totaltries);
577 * This class represents a real question. That is, one that is not a
578 * {@link question_information_item}.
580 * @copyright 2009 The Open University
581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
583 abstract class question_with_responses extends question_definition
584 implements question_manually_gradable {
585 public function classify_response(array $response) {
586 return array();
592 * This class represents a question that can be graded automatically.
594 * @copyright 2009 The Open University
595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
597 abstract class question_graded_automatically extends question_with_responses
598 implements question_automatically_gradable {
599 /** @var Some question types have the option to show the number of sub-parts correct. */
600 public $shownumcorrect = false;
602 public function is_gradable_response(array $response) {
603 return $this->is_complete_response($response);
606 public function get_right_answer_summary() {
607 $correctresponse = $this->get_correct_response();
608 if (empty($correctresponse)) {
609 return null;
611 return $this->summarise_response($correctresponse);
615 * Check a request for access to a file belonging to a combined feedback field.
616 * @param question_attempt $qa the question attempt being displayed.
617 * @param question_display_options $options the options that control display of the question.
618 * @param string $filearea the name of the file area.
619 * @return bool whether access to the file should be allowed.
621 protected function check_combined_feedback_file_access($qa, $options, $filearea) {
622 $state = $qa->get_state();
624 if (!$state->is_finished()) {
625 $response = $qa->get_last_qt_data();
626 if (!$this->is_gradable_response($response)) {
627 return false;
629 list($notused, $state) = $this->grade_response($response);
632 return $options->feedback && $state->get_feedback_class() . 'feedback' == $filearea;
636 * Check a request for access to a file belonging to a hint.
637 * @param question_attempt $qa the question attempt being displayed.
638 * @param question_display_options $options the options that control display of the question.
639 * @param array $args the remaining bits of the file path.
640 * @return bool whether access to the file should be allowed.
642 protected function check_hint_file_access($qa, $options, $args) {
643 if (!$options->feedback) {
644 return false;
646 $hint = $qa->get_applicable_hint();
647 $hintid = reset($args); // Itemid is hint id.
648 return $hintid == $hint->id;
651 public function get_hint($hintnumber, question_attempt $qa) {
652 if (!isset($this->hints[$hintnumber])) {
653 return null;
655 return $this->hints[$hintnumber];
658 public function format_hint(question_hint $hint, question_attempt $qa) {
659 return $this->format_text($hint->hint, $hint->hintformat, $qa,
660 'question', 'hint', $hint->id);
666 * This class represents a question that can be graded automatically with
667 * countback grading in interactive mode.
669 * @copyright 2010 The Open University
670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
672 abstract class question_graded_automatically_with_countback
673 extends question_graded_automatically
674 implements question_automatically_gradable_with_countback {
676 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
677 if ($preferredbehaviour == 'interactive') {
678 return question_engine::make_behaviour('interactivecountback',
679 $qa, $preferredbehaviour);
681 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
687 * This class represents a question that can be graded automatically by using
688 * a {@link question_grading_strategy}.
690 * @copyright 2009 The Open University
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 abstract class question_graded_by_strategy extends question_graded_automatically {
694 /** @var question_grading_strategy the strategy to use for grading. */
695 protected $gradingstrategy;
697 /** @param question_grading_strategy $strategy the strategy to use for grading. */
698 public function __construct(question_grading_strategy $strategy) {
699 parent::__construct();
700 $this->gradingstrategy = $strategy;
703 public function get_correct_response() {
704 $answer = $this->get_correct_answer();
705 if (!$answer) {
706 return array();
709 return array('answer' => $answer->answer);
713 * Get an answer that contains the feedback and fraction that should be
714 * awarded for this resonse.
715 * @param array $response a response.
716 * @return question_answer the matching answer.
718 public function get_matching_answer(array $response) {
719 return $this->gradingstrategy->grade($response);
723 * @return question_answer an answer that contains the a response that would
724 * get full marks.
726 public function get_correct_answer() {
727 return $this->gradingstrategy->get_correct_answer();
730 public function grade_response(array $response) {
731 $answer = $this->get_matching_answer($response);
732 if ($answer) {
733 return array($answer->fraction,
734 question_state::graded_state_for_fraction($answer->fraction));
735 } else {
736 return array(0, question_state::$gradedwrong);
740 public function classify_response(array $response) {
741 if (empty($response['answer'])) {
742 return array($this->id => question_classified_response::no_response());
745 $ans = $this->get_matching_answer($response);
746 if (!$ans) {
747 return array($this->id => new question_classified_response(
748 0, $response['answer'], 0));
751 return array($this->id => new question_classified_response(
752 $ans->id, $response['answer'], $ans->fraction));
758 * Class to represent a question answer, loaded from the question_answers table
759 * in the database.
761 * @copyright 2009 The Open University
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class question_answer {
765 /** @var integer the answer id. */
766 public $id;
768 /** @var string the answer. */
769 public $answer;
771 /** @var integer one of the FORMAT_... constans. */
772 public $answerformat = FORMAT_PLAIN;
774 /** @var number the fraction this answer is worth. */
775 public $fraction;
777 /** @var string the feedback for this answer. */
778 public $feedback;
780 /** @var integer one of the FORMAT_... constans. */
781 public $feedbackformat;
784 * Constructor.
785 * @param int $id the answer.
786 * @param string $answer the answer.
787 * @param number $fraction the fraction this answer is worth.
788 * @param string $feedback the feedback for this answer.
789 * @param int $feedbackformat the format of the feedback.
791 public function __construct($id, $answer, $fraction, $feedback, $feedbackformat) {
792 $this->id = $id;
793 $this->answer = $answer;
794 $this->fraction = $fraction;
795 $this->feedback = $feedback;
796 $this->feedbackformat = $feedbackformat;
802 * Class to represent a hint associated with a question.
803 * Used by iteractive mode, etc. A question has an array of these.
805 * @copyright 2010 The Open University
806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
808 class question_hint {
809 /** @var integer The hint id. */
810 public $id;
811 /** @var string The feedback hint to be shown. */
812 public $hint;
813 /** @var integer The corresponding text FORMAT_... type. */
814 public $hintformat;
817 * Constructor.
818 * @param int the hint id from the database.
819 * @param string $hint The hint text
820 * @param int the corresponding text FORMAT_... type.
822 public function __construct($id, $hint, $hintformat) {
823 $this->id = $id;
824 $this->hint = $hint;
825 $this->hintformat = $hintformat;
829 * Create a basic hint from a row loaded from the question_hints table in the database.
830 * @param object $row with $row->hint set.
831 * @return question_hint
833 public static function load_from_record($row) {
834 return new question_hint($row->id, $row->hint, $row->hintformat);
838 * Adjust this display options according to the hint settings.
839 * @param question_display_options $options
841 public function adjust_display_options(question_display_options $options) {
842 // Do nothing.
848 * An extension of {@link question_hint} for questions like match and multiple
849 * choice with multile answers, where there are options for whether to show the
850 * number of parts right at each stage, and to reset the wrong parts.
852 * @copyright 2010 The Open University
853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
855 class question_hint_with_parts extends question_hint {
856 /** @var boolean option to show the number of sub-parts of the question that were right. */
857 public $shownumcorrect;
859 /** @var boolean option to clear the parts of the question that were wrong on retry. */
860 public $clearwrong;
863 * Constructor.
864 * @param int the hint id from the database.
865 * @param string $hint The hint text
866 * @param int the corresponding text FORMAT_... type.
867 * @param bool $shownumcorrect whether the number of right parts should be shown
868 * @param bool $clearwrong whether the wrong parts should be reset.
870 public function __construct($id, $hint, $hintformat, $shownumcorrect, $clearwrong) {
871 parent::__construct($id, $hint, $hintformat);
872 $this->shownumcorrect = $shownumcorrect;
873 $this->clearwrong = $clearwrong;
877 * Create a basic hint from a row loaded from the question_hints table in the database.
878 * @param object $row with $row->hint, ->shownumcorrect and ->clearwrong set.
879 * @return question_hint_with_parts
881 public static function load_from_record($row) {
882 return new question_hint_with_parts($row->id, $row->hint, $row->hintformat,
883 $row->shownumcorrect, $row->clearwrong);
886 public function adjust_display_options(question_display_options $options) {
887 parent::adjust_display_options($options);
888 if ($this->clearwrong) {
889 $options->clearwrong = true;
891 $options->numpartscorrect = $this->shownumcorrect;
897 * This question_grading_strategy interface. Used to share grading code between
898 * questions that that subclass {@link question_graded_by_strategy}.
900 * @copyright 2009 The Open University
901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
903 interface question_grading_strategy {
905 * Return a question answer that describes the outcome (fraction and feeback)
906 * for a particular respons.
907 * @param array $response the response.
908 * @return question_answer the answer describing the outcome.
910 public function grade(array $response);
913 * @return question_answer an answer that contains the a response that would
914 * get full marks.
916 public function get_correct_answer();
921 * This interface defines the methods that a {@link question_definition} must
922 * implement if it is to be graded by the
923 * {@link question_first_matching_answer_grading_strategy}.
925 * @copyright 2009 The Open University
926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
928 interface question_response_answer_comparer {
929 /** @return array of {@link question_answers}. */
930 public function get_answers();
933 * @param array $response the response.
934 * @param question_answer $answer an answer.
935 * @return bool whether the response matches the answer.
937 public function compare_response_with_answer(array $response, question_answer $answer);
942 * This grading strategy is used by question types like shortanswer an numerical.
943 * It gets a list of possible answers from the question, and returns the first one
944 * that matches the given response. It returns the first answer with fraction 1.0
945 * when asked for the correct answer.
947 * @copyright 2009 The Open University
948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
950 class question_first_matching_answer_grading_strategy implements question_grading_strategy {
952 * @var question_response_answer_comparer (presumably also a
953 * {@link question_definition}) the question we are doing the grading for.
955 protected $question;
958 * @param question_response_answer_comparer $question (presumably also a
959 * {@link question_definition}) the question we are doing the grading for.
961 public function __construct(question_response_answer_comparer $question) {
962 $this->question = $question;
965 public function grade(array $response) {
966 foreach ($this->question->get_answers() as $aid => $answer) {
967 if ($this->question->compare_response_with_answer($response, $answer)) {
968 $answer->id = $aid;
969 return $answer;
972 return null;
975 public function get_correct_answer() {
976 foreach ($this->question->get_answers() as $answer) {
977 $state = question_state::graded_state_for_fraction($answer->fraction);
978 if ($state == question_state::$gradedright) {
979 return $answer;
982 return null;