2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
29 * - question_classified_response
32 * - question_hint_with_parts
33 * - question_first_matching_answer_grading_strategy implements question_grading_strategy
36 * - question_response_answer_comparer
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();
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. */
64 /** @var integer question category id. */
67 /** @var integer question context id. */
70 /** @var integer parent question id. */
73 /** @var question_type the question type this question is. */
76 /** @var string question name. */
79 /** @var string question text. */
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. */
97 /** @var number penalty factor of this question. */
100 /** @var string unique identifier of this question. */
103 /** @var string unique identifier of this version of this question. */
106 /** @var boolean whethre this question has been deleted/hidden in the question bank. */
109 /** @var string question idnumber. */
112 /** @var integer timestamp when this question was created. */
115 /** @var integer timestamp when this question was modified. */
116 public $timemodified;
118 /** @var integer userid of the use who created this question. */
121 /** @var integer userid of the use who modified this question. */
124 /** @var array of question_hints. */
125 public $hints = array();
128 * Constructor. Normally to get a question, you call
129 * {@link question_bank::load_question()}, but questions can be created
130 * directly, for example in unit test code.
131 * @return unknown_type
133 public function __construct() {
137 * @return the name of the question type (for example multichoice) that this
140 public function get_type_name() {
141 return $this->qtype
->name();
145 * Creat the appropriate behaviour for an attempt at this quetsion,
146 * given the desired (archetypal) behaviour.
148 * This default implementation will suit most normal graded questions.
150 * If your question is of a patricular type, then it may need to do something
151 * different. For example, if your question can only be graded manually, then
152 * it should probably return a manualgraded behaviour, irrespective of
155 * If your question wants to do somthing especially complicated is some situations,
156 * then you may wish to return a particular behaviour related to the
157 * one asked for. For example, you migth want to return a
158 * qbehaviour_interactive_adapted_for_myqtype.
160 * @param question_attempt $qa the attempt we are creating a behaviour for.
161 * @param string $preferredbehaviour the requested type of behaviour.
162 * @return question_behaviour the new behaviour object.
164 public function make_behaviour(question_attempt
$qa, $preferredbehaviour) {
165 return question_engine
::make_archetypal_behaviour($preferredbehaviour, $qa);
169 * Start a new attempt at this question, storing any information that will
170 * be needed later in the step.
172 * This is where the question can do any initialisation required on a
173 * per-attempt basis. For example, this is where the multiple choice
174 * question type randomly shuffles the choices (if that option is set).
176 * Any information about how the question has been set up for this attempt
177 * should be stored in the $step, by calling $step->set_qt_var(...).
179 * @param question_attempt_step The first step of the {@link question_attempt}
180 * being started. Can be used to store state.
181 * @param int $varant which variant of this question to start. Will be between
182 * 1 and {@link get_num_variants()} inclusive.
184 public function start_attempt(question_attempt_step
$step, $variant) {
188 * When an in-progress {@link question_attempt} is re-loaded from the
189 * database, this method is called so that the question can re-initialise
190 * its internal state as needed by this attempt.
192 * For example, the multiple choice question type needs to set the order
193 * of the choices to the order that was set up when start_attempt was called
194 * originally. All the information required to do this should be in the
195 * $step object, which is the first step of the question_attempt being loaded.
197 * @param question_attempt_step The first step of the {@link question_attempt}
200 public function apply_attempt_state(question_attempt_step
$step) {
204 * Generate a brief, plain-text, summary of this question. This is used by
205 * various reports. This should show the particular variant of the question
206 * as presented to students. For example, the calculated quetsion type would
207 * fill in the particular numbers that were presented to the student.
208 * This method will return null if such a summary is not possible, or
210 * @return string|null a plain text summary of this question.
212 public function get_question_summary() {
213 return $this->html_to_text($this->questiontext
, $this->questiontextformat
);
217 * @return int the number of vaiants that this question has.
219 public function get_num_variants() {
224 * @return string that can be used to seed the pseudo-random selection of a
227 public function get_variants_selection_seed() {
232 * Some questions can return a negative mark if the student gets it wrong.
234 * This method returns the lowest mark the question can return, on the
235 * fraction scale. that is, where the maximum possible mark is 1.0.
237 * @return float minimum fraction this question will ever return.
239 public function get_min_fraction() {
244 * Some questions can return a mark greater than the maximum.
246 * This method returns the lowest highest the question can return, on the
247 * fraction scale. that is, where the nominal maximum mark is 1.0.
249 * @return float maximum fraction this question will ever return.
251 public function get_max_fraction() {
256 * Given a response, rest the parts that are wrong.
257 * @param array $response a response
258 * @return array a cleaned up response with the wrong bits reset.
260 public function clear_wrong_from_response(array $response) {
265 * Return the number of subparts of this response that are right.
266 * @param array $response a response
267 * @return array with two elements, the number of correct subparts, and
268 * the total number of subparts.
270 public function get_num_parts_right(array $response) {
271 return array(null, null);
275 * @param moodle_page the page we are outputting to.
276 * @return qtype_renderer the renderer to use for outputting this question.
278 public function get_renderer(moodle_page
$page) {
279 return $page->get_renderer($this->qtype
->plugin_name());
283 * What data may be included in the form submission when a student submits
284 * this question in its current state?
286 * This information is used in calls to optional_param. The parameter name
287 * has {@link question_attempt::get_field_prefix()} automatically prepended.
289 * @return array|string variable name => PARAM_... constant, or, as a special case
290 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
291 * meaning take all the raw submitted data belonging to this question.
293 public abstract function get_expected_data();
296 * What data would need to be submitted to get this question correct.
297 * If there is more than one correct answer, this method should just
298 * return one possibility. If it is not possible to compute a correct
299 * response, this method should return null.
301 * @return array|null parameter name => value.
303 public abstract function get_correct_response();
307 * Takes an array of values representing a student response represented in a way that is understandable by a human and
308 * transforms that to the response as the POST values returned from the HTML form that takes the student response during a
309 * student attempt. Primarily this is used when reading csv values from a file of student responses in order to be able to
310 * simulate the student interaction with a quiz.
312 * In most cases the array will just be returned as is. Some question types will need to transform the keys of the array,
313 * as the meaning of the keys in the html form is deliberately obfuscated so that someone looking at the html does not get an
314 * advantage. The values that represent the response might also be changed in order to more meaningful to a human.
316 * See the examples of question types that have overridden this in core and also see the csv files of simulated student
317 * responses used in unit tests in :
318 * - mod/quiz/tests/fixtures/stepsXX.csv
319 * - mod/quiz/report/responses/tests/fixtures/steps00.csv
320 * - mod/quiz/report/statistics/tests/fixtures/stepsXX.csv
322 * Also see {@link https://github.com/jamiepratt/moodle-quiz_simulate}, a quiz report plug in for uploading and downloading
323 * student responses as csv files.
325 * @param array $simulatedresponse an array of data representing a student response
326 * @return array a response array as would be returned from the html form (but without prefixes)
328 public function prepare_simulated_post_data($simulatedresponse) {
329 return $simulatedresponse;
333 * Does the opposite of {@link prepare_simulated_post_data}.
335 * This takes a student response (the POST values returned from the HTML form that takes the student response during a
336 * student attempt) it then represents it in a way that is understandable by a human.
338 * Primarily this is used when creating a file of csv from real student responses in order later to be able to
339 * simulate the same student interaction with a quiz later.
341 * @param string[] $realresponse the response array as was returned from the form during a student attempt (without prefixes).
342 * @return string[] an array of data representing a student response.
344 public function get_student_response_values_for_simulation($realresponse) {
345 return $realresponse;
349 * Apply {@link format_text()} to some content with appropriate settings for
352 * @param string $text some content that needs to be output.
353 * @param int $format the FORMAT_... constant.
354 * @param question_attempt $qa the question attempt.
355 * @param string $component used for rewriting file area URLs.
356 * @param string $filearea used for rewriting file area URLs.
357 * @param bool $clean Whether the HTML needs to be cleaned. Generally,
358 * parts of the question do not need to be cleaned, and student input does.
359 * @return string the text formatted for output by format_text.
361 public function format_text($text, $format, $qa, $component, $filearea, $itemid,
363 $formatoptions = new stdClass();
364 $formatoptions->noclean
= !$clean;
365 $formatoptions->para
= false;
366 $text = $qa->rewrite_pluginfile_urls($text, $component, $filearea, $itemid);
367 return format_text($text, $format, $formatoptions);
371 * Convert some part of the question text to plain text. This might be used,
372 * for example, by get_response_summary().
373 * @param string $text The HTML to reduce to plain text.
374 * @param int $format the FORMAT_... constant.
375 * @return string the equivalent plain text.
377 public function html_to_text($text, $format) {
378 return question_utils
::to_plain_text($text, $format);
381 /** @return the result of applying {@link format_text()} to the question text. */
382 public function format_questiontext($qa) {
383 return $this->format_text($this->questiontext
, $this->questiontextformat
,
384 $qa, 'question', 'questiontext', $this->id
);
387 /** @return the result of applying {@link format_text()} to the general feedback. */
388 public function format_generalfeedback($qa) {
389 return $this->format_text($this->generalfeedback
, $this->generalfeedbackformat
,
390 $qa, 'question', 'generalfeedback', $this->id
);
394 * Take some HTML that should probably already be a single line, like a
395 * multiple choice choice, or the corresponding feedback, and make it so that
396 * it is suitable to go in a place where the HTML must be inline, like inside a <p> tag.
397 * @param string $html to HTML to fix up.
398 * @return string the fixed HTML.
400 public function make_html_inline($html) {
401 $html = preg_replace('~\s*<p>\s*~u', '', $html);
402 $html = preg_replace('~\s*</p>\s*~u', '<br />', $html);
403 $html = preg_replace('~(<br\s*/?>)+$~u', '', $html);
408 * Checks whether the users is allow to be served a particular file.
409 * @param question_attempt $qa the question attempt being displayed.
410 * @param question_display_options $options the options that control display of the question.
411 * @param string $component the name of the component we are serving files for.
412 * @param string $filearea the name of the file area.
413 * @param array $args the remaining bits of the file path.
414 * @param bool $forcedownload whether the user must be forced to download the file.
415 * @return bool true if the user can access this file.
417 public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
418 if ($component == 'question' && $filearea == 'questiontext') {
419 // Question text always visible, but check it is the right question id.
420 return $args[0] == $this->id
;
422 } else if ($component == 'question' && $filearea == 'generalfeedback') {
423 return $options->generalfeedback
&& $args[0] == $this->id
;
426 // Unrecognised component or filearea.
432 * Return the question settings that define this question as structured data.
434 * This is used by external systems such as the Moodle mobile app, which want to display the question themselves,
435 * rather than using the renderer provided.
437 * This method should only return the data that the student is allowed to see or know, given the current state of
438 * the question. For example, do not include the 'General feedback' until the student has completed the question,
439 * and even then, only include it if the question_display_options say it should be visible.
441 * But, within those rules, it is recommended that you return all the settings for the question,
442 * to give maximum flexibility to the external system providing its own rendering of the question.
444 * @param question_attempt $qa the current attempt for which we are exporting the settings.
445 * @param question_display_options $options the question display options which say which aspects of the question
447 * @return mixed structure representing the question settings. In web services, this will be JSON-encoded.
449 public function get_question_definition_for_external_rendering(question_attempt
$qa, question_display_options
$options) {
451 debugging('This question does not implement the get_question_definition_for_external_rendering() method yet.',
459 * This class represents a 'question' that actually does not allow the student
460 * to respond, like the description 'question' type.
462 * @copyright 2009 The Open University
463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
465 class question_information_item
extends question_definition
{
466 public function __construct() {
467 parent
::__construct();
468 $this->defaultmark
= 0;
473 public function make_behaviour(question_attempt
$qa, $preferredbehaviour) {
474 return question_engine
::make_behaviour('informationitem', $qa, $preferredbehaviour);
477 public function get_expected_data() {
481 public function get_correct_response() {
485 public function get_question_summary() {
492 * Interface that a {@link question_definition} must implement to be usable by
493 * the manual graded behaviour.
495 * @copyright 2009 The Open University
496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
498 interface question_manually_gradable
{
500 * Use by many of the behaviours to determine whether the student
501 * has provided enough of an answer for the question to be graded automatically,
502 * or whether it must be considered aborted.
504 * @param array $response responses, as returned by
505 * {@link question_attempt_step::get_qt_data()}.
506 * @return bool whether this response can be graded.
508 public function is_gradable_response(array $response);
511 * Used by many of the behaviours, to work out whether the student's
512 * response to the question is complete. That is, whether the question attempt
513 * should move to the COMPLETE or INCOMPLETE state.
515 * @param array $response responses, as returned by
516 * {@link question_attempt_step::get_qt_data()}.
517 * @return bool whether this response is a complete answer to this question.
519 public function is_complete_response(array $response);
522 * Use by many of the behaviours to determine whether the student's
523 * response has changed. This is normally used to determine that a new set
524 * of responses can safely be discarded.
526 * @param array $prevresponse the responses previously recorded for this question,
527 * as returned by {@link question_attempt_step::get_qt_data()}
528 * @param array $newresponse the new responses, in the same format.
529 * @return bool whether the two sets of responses are the same - that is
530 * whether the new set of responses can safely be discarded.
532 public function is_same_response(array $prevresponse, array $newresponse);
535 * Produce a plain text summary of a response.
536 * @param array $response a response, as might be passed to {@link grade_response()}.
537 * @return string a plain text summary of that response, that could be used in reports.
539 public function summarise_response(array $response);
542 * If possible, construct a response that could have lead to the given
543 * response summary. This is basically the opposite of {@link summarise_response()}
544 * but it is intended only to be used for testing.
546 * @param string $summary a string, which might have come from summarise_response
547 * @return array a response that could have lead to that.
549 public function un_summarise_response(string $summary);
552 * Categorise the student's response according to the categories defined by
553 * get_possible_responses.
554 * @param $response a response, as might be passed to {@link grade_response()}.
555 * @return array subpartid => {@link question_classified_response} objects.
556 * returns an empty array if no analysis is possible.
558 public function classify_response(array $response);
563 * This class is used in the return value from
564 * {@link question_manually_gradable::classify_response()}.
566 * @copyright 2010 The Open University
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
569 class question_classified_response
{
571 * @var string the classification of this response the student gave to this
572 * part of the question. Must match one of the responseclasses returned by
573 * {@link question_type::get_possible_responses()}.
575 public $responseclassid;
576 /** @var string the actual response the student gave to this part. */
578 /** @var number the fraction this part of the response earned. */
581 * Constructor, just an easy way to set the fields.
582 * @param string $responseclassid see the field descriptions above.
583 * @param string $response see the field descriptions above.
584 * @param number $fraction see the field descriptions above.
586 public function __construct($responseclassid, $response, $fraction) {
587 $this->responseclassid
= $responseclassid;
588 $this->response
= $response;
589 $this->fraction
= $fraction;
592 public static function no_response() {
593 return new question_classified_response(null, get_string('noresponse', 'question'), null);
599 * Interface that a {@link question_definition} must implement to be usable by
600 * the various automatic grading behaviours.
602 * @copyright 2009 The Open University
603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
605 interface question_automatically_gradable
extends question_manually_gradable
{
607 * In situations where is_gradable_response() returns false, this method
608 * should generate a description of what the problem is.
609 * @return string the message.
611 public function get_validation_error(array $response);
614 * Grade a response to the question, returning a fraction between
615 * get_min_fraction() and get_max_fraction(), and the corresponding {@link question_state}
616 * right, partial or wrong.
617 * @param array $response responses, as returned by
618 * {@link question_attempt_step::get_qt_data()}.
619 * @return array (float, integer) the fraction, and the state.
621 public function grade_response(array $response);
624 * Get one of the question hints. The question_attempt is passed in case
625 * the question type wants to do something complex. For example, the
626 * multiple choice with multiple responses question type will turn off most
627 * of the hint options if the student has selected too many opitions.
628 * @param int $hintnumber Which hint to display. Indexed starting from 0
629 * @param question_attempt $qa The question_attempt.
631 public function get_hint($hintnumber, question_attempt
$qa);
634 * Generate a brief, plain-text, summary of the correct answer to this question.
635 * This is used by various reports, and can also be useful when testing.
636 * This method will return null if such a summary is not possible, or
638 * @return string|null a plain text summary of the right answer to this question.
640 public function get_right_answer_summary();
645 * Interface that a {@link question_definition} must implement to be usable by
646 * the interactivecountback behaviour.
648 * @copyright 2010 The Open University
649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
651 interface question_automatically_gradable_with_countback
extends question_automatically_gradable
{
653 * Work out a final grade for this attempt, taking into account all the
654 * tries the student made.
655 * @param array $responses the response for each try. Each element of this
656 * array is a response array, as would be passed to {@link grade_response()}.
657 * There may be between 1 and $totaltries responses.
658 * @param int $totaltries The maximum number of tries allowed.
659 * @return numeric the fraction that should be awarded for this
660 * sequence of response.
662 public function compute_final_grade($responses, $totaltries);
667 * This class represents a real question. That is, one that is not a
668 * {@link question_information_item}.
670 * @copyright 2009 The Open University
671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
673 abstract class question_with_responses
extends question_definition
674 implements question_manually_gradable
{
675 public function classify_response(array $response) {
679 public function is_gradable_response(array $response) {
680 return $this->is_complete_response($response);
683 public function un_summarise_response(string $summary) {
684 throw new coding_exception('This question type (' . get_class($this) .
685 ' does not implement the un_summarise_response testing method.');
691 * This class represents a question that can be graded automatically.
693 * @copyright 2009 The Open University
694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
696 abstract class question_graded_automatically
extends question_with_responses
697 implements question_automatically_gradable
{
698 /** @var Some question types have the option to show the number of sub-parts correct. */
699 public $shownumcorrect = false;
701 public function get_right_answer_summary() {
702 $correctresponse = $this->get_correct_response();
703 if (empty($correctresponse)) {
706 return $this->summarise_response($correctresponse);
710 * Check a request for access to a file belonging to a combined feedback field.
711 * @param question_attempt $qa the question attempt being displayed.
712 * @param question_display_options $options the options that control display of the question.
713 * @param string $filearea the name of the file area.
714 * @param array $args the remaining bits of the file path.
715 * @return bool whether access to the file should be allowed.
717 protected function check_combined_feedback_file_access($qa, $options, $filearea, $args = null) {
718 $state = $qa->get_state();
720 if ($args === null) {
721 debugging('You must pass $args as the fourth argument to check_combined_feedback_file_access.',
723 $args = array($this->id
); // Fake it for now, so the rest of this method works.
726 if (!$state->is_finished()) {
727 $response = $qa->get_last_qt_data();
728 if (!$this->is_gradable_response($response)) {
731 list($notused, $state) = $this->grade_response($response);
734 return $options->feedback
&& $state->get_feedback_class() . 'feedback' == $filearea &&
735 $args[0] == $this->id
;
739 * Check a request for access to a file belonging to a hint.
740 * @param question_attempt $qa the question attempt being displayed.
741 * @param question_display_options $options the options that control display of the question.
742 * @param array $args the remaining bits of the file path.
743 * @return bool whether access to the file should be allowed.
745 protected function check_hint_file_access($qa, $options, $args) {
746 if (!$options->feedback
) {
749 $hint = $qa->get_applicable_hint();
750 $hintid = reset($args); // Itemid is hint id.
751 return $hintid == $hint->id
;
754 public function get_hint($hintnumber, question_attempt
$qa) {
755 if (!isset($this->hints
[$hintnumber])) {
758 return $this->hints
[$hintnumber];
761 public function format_hint(question_hint
$hint, question_attempt
$qa) {
762 return $this->format_text($hint->hint
, $hint->hintformat
, $qa,
763 'question', 'hint', $hint->id
);
769 * This class represents a question that can be graded automatically with
770 * countback grading in interactive mode.
772 * @copyright 2010 The Open University
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 abstract class question_graded_automatically_with_countback
776 extends question_graded_automatically
777 implements question_automatically_gradable_with_countback
{
779 public function make_behaviour(question_attempt
$qa, $preferredbehaviour) {
780 if ($preferredbehaviour == 'interactive') {
781 return question_engine
::make_behaviour('interactivecountback',
782 $qa, $preferredbehaviour);
784 return question_engine
::make_archetypal_behaviour($preferredbehaviour, $qa);
790 * This class represents a question that can be graded automatically by using
791 * a {@link question_grading_strategy}.
793 * @copyright 2009 The Open University
794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
796 abstract class question_graded_by_strategy
extends question_graded_automatically
{
797 /** @var question_grading_strategy the strategy to use for grading. */
798 protected $gradingstrategy;
800 /** @param question_grading_strategy $strategy the strategy to use for grading. */
801 public function __construct(question_grading_strategy
$strategy) {
802 parent
::__construct();
803 $this->gradingstrategy
= $strategy;
806 public function get_correct_response() {
807 $answer = $this->get_correct_answer();
812 return array('answer' => $answer->answer
);
816 * Get an answer that contains the feedback and fraction that should be
817 * awarded for this resonse.
818 * @param array $response a response.
819 * @return question_answer the matching answer.
821 public function get_matching_answer(array $response) {
822 return $this->gradingstrategy
->grade($response);
826 * @return question_answer an answer that contains the a response that would
829 public function get_correct_answer() {
830 return $this->gradingstrategy
->get_correct_answer();
833 public function grade_response(array $response) {
834 $answer = $this->get_matching_answer($response);
836 return array($answer->fraction
,
837 question_state
::graded_state_for_fraction($answer->fraction
));
839 return array(0, question_state
::$gradedwrong);
843 public function classify_response(array $response) {
844 if (empty($response['answer'])) {
845 return array($this->id
=> question_classified_response
::no_response());
848 $ans = $this->get_matching_answer($response);
850 return array($this->id
=> new question_classified_response(
851 0, $response['answer'], 0));
854 return array($this->id
=> new question_classified_response(
855 $ans->id
, $response['answer'], $ans->fraction
));
861 * Class to represent a question answer, loaded from the question_answers table
864 * @copyright 2009 The Open University
865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
867 class question_answer
{
868 /** @var integer the answer id. */
871 /** @var string the answer. */
874 /** @var integer one of the FORMAT_... constans. */
875 public $answerformat = FORMAT_PLAIN
;
877 /** @var number the fraction this answer is worth. */
880 /** @var string the feedback for this answer. */
883 /** @var integer one of the FORMAT_... constans. */
884 public $feedbackformat;
888 * @param int $id the answer.
889 * @param string $answer the answer.
890 * @param number $fraction the fraction this answer is worth.
891 * @param string $feedback the feedback for this answer.
892 * @param int $feedbackformat the format of the feedback.
894 public function __construct($id, $answer, $fraction, $feedback, $feedbackformat) {
896 $this->answer
= $answer;
897 $this->fraction
= $fraction;
898 $this->feedback
= $feedback;
899 $this->feedbackformat
= $feedbackformat;
905 * Class to represent a hint associated with a question.
906 * Used by iteractive mode, etc. A question has an array of these.
908 * @copyright 2010 The Open University
909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
911 class question_hint
{
912 /** @var integer The hint id. */
914 /** @var string The feedback hint to be shown. */
916 /** @var integer The corresponding text FORMAT_... type. */
921 * @param int the hint id from the database.
922 * @param string $hint The hint text
923 * @param int the corresponding text FORMAT_... type.
925 public function __construct($id, $hint, $hintformat) {
928 $this->hintformat
= $hintformat;
932 * Create a basic hint from a row loaded from the question_hints table in the database.
933 * @param object $row with $row->hint set.
934 * @return question_hint
936 public static function load_from_record($row) {
937 return new question_hint($row->id
, $row->hint
, $row->hintformat
);
941 * Adjust this display options according to the hint settings.
942 * @param question_display_options $options
944 public function adjust_display_options(question_display_options
$options) {
951 * An extension of {@link question_hint} for questions like match and multiple
952 * choice with multile answers, where there are options for whether to show the
953 * number of parts right at each stage, and to reset the wrong parts.
955 * @copyright 2010 The Open University
956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
958 class question_hint_with_parts
extends question_hint
{
959 /** @var boolean option to show the number of sub-parts of the question that were right. */
960 public $shownumcorrect;
962 /** @var boolean option to clear the parts of the question that were wrong on retry. */
967 * @param int the hint id from the database.
968 * @param string $hint The hint text
969 * @param int the corresponding text FORMAT_... type.
970 * @param bool $shownumcorrect whether the number of right parts should be shown
971 * @param bool $clearwrong whether the wrong parts should be reset.
973 public function __construct($id, $hint, $hintformat, $shownumcorrect, $clearwrong) {
974 parent
::__construct($id, $hint, $hintformat);
975 $this->shownumcorrect
= $shownumcorrect;
976 $this->clearwrong
= $clearwrong;
980 * Create a basic hint from a row loaded from the question_hints table in the database.
981 * @param object $row with $row->hint, ->shownumcorrect and ->clearwrong set.
982 * @return question_hint_with_parts
984 public static function load_from_record($row) {
985 return new question_hint_with_parts($row->id
, $row->hint
, $row->hintformat
,
986 $row->shownumcorrect
, $row->clearwrong
);
989 public function adjust_display_options(question_display_options
$options) {
990 parent
::adjust_display_options($options);
991 if ($this->clearwrong
) {
992 $options->clearwrong
= true;
994 $options->numpartscorrect
= $this->shownumcorrect
;
1000 * This question_grading_strategy interface. Used to share grading code between
1001 * questions that that subclass {@link question_graded_by_strategy}.
1003 * @copyright 2009 The Open University
1004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1006 interface question_grading_strategy
{
1008 * Return a question answer that describes the outcome (fraction and feeback)
1009 * for a particular respons.
1010 * @param array $response the response.
1011 * @return question_answer the answer describing the outcome.
1013 public function grade(array $response);
1016 * @return question_answer an answer that contains the a response that would
1019 public function get_correct_answer();
1024 * This interface defines the methods that a {@link question_definition} must
1025 * implement if it is to be graded by the
1026 * {@link question_first_matching_answer_grading_strategy}.
1028 * @copyright 2009 The Open University
1029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1031 interface question_response_answer_comparer
{
1032 /** @return array of {@link question_answers}. */
1033 public function get_answers();
1036 * @param array $response the response.
1037 * @param question_answer $answer an answer.
1038 * @return bool whether the response matches the answer.
1040 public function compare_response_with_answer(array $response, question_answer
$answer);
1045 * This grading strategy is used by question types like shortanswer an numerical.
1046 * It gets a list of possible answers from the question, and returns the first one
1047 * that matches the given response. It returns the first answer with fraction 1.0
1048 * when asked for the correct answer.
1050 * @copyright 2009 The Open University
1051 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1053 class question_first_matching_answer_grading_strategy
implements question_grading_strategy
{
1055 * @var question_response_answer_comparer (presumably also a
1056 * {@link question_definition}) the question we are doing the grading for.
1058 protected $question;
1061 * @param question_response_answer_comparer $question (presumably also a
1062 * {@link question_definition}) the question we are doing the grading for.
1064 public function __construct(question_response_answer_comparer
$question) {
1065 $this->question
= $question;
1068 public function grade(array $response) {
1069 foreach ($this->question
->get_answers() as $aid => $answer) {
1070 if ($this->question
->compare_response_with_answer($response, $answer)) {
1078 public function get_correct_answer() {
1079 foreach ($this->question
->get_answers() as $answer) {
1080 $state = question_state
::graded_state_for_fraction($answer->fraction
);
1081 if ($state == question_state
::$gradedright) {