MDL-70153 qtype_essay: Add behat test for attachments max size
[moodle.git] / question / type / questionbase.php
CommitLineData
d1b7e03d 1<?php
d1b7e03d
TH
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
d1b7e03d
TH
17/**
18 * This file defines the class {@link question_definition} and its subclasses.
19 *
d4a66602
TH
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
27 *
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
34 *
35 * Other interfaces:
36 * - question_response_answer_comparer
37 *
b04a4319 38 * @package moodlecore
d1b7e03d 39 * @subpackage questiontypes
b04a4319
TH
40 * @copyright 2009 The Open University
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
42 */
43
44
a17b297d
TH
45defined('MOODLE_INTERNAL') || die();
46
47
d1b7e03d
TH
48/**
49 * The definition of a question of a particular type.
50 *
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}.
55 *
7764183a
TH
56 * @copyright 2009 The Open University
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
58 */
59abstract 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;
63
64 /** @var integer question category id. */
65 public $category;
66
e35ba43c 67 /** @var integer question context id. */
56e82d99
TH
68 public $contextid;
69
d1b7e03d
TH
70 /** @var integer parent question id. */
71 public $parent = 0;
72
73 /** @var question_type the question type this question is. */
74 public $qtype;
75
76 /** @var string question name. */
77 public $name;
78
79 /** @var string question text. */
80 public $questiontext;
81
82 /** @var integer question test format. */
83 public $questiontextformat;
84
85 /** @var string question general feedback. */
86 public $generalfeedback;
87
1c2ed7c5
TH
88 /** @var integer question test format. */
89 public $generalfeedbackformat;
90
d1b7e03d
TH
91 /** @var number what this quetsion is marked out of, by default. */
92 public $defaultmark = 1;
93
94 /** @var integer How many question numbers this question consumes. */
95 public $length = 1;
96
97 /** @var number penalty factor of this question. */
98 public $penalty = 0;
99
100 /** @var string unique identifier of this question. */
101 public $stamp;
102
103 /** @var string unique identifier of this version of this question. */
104 public $version;
105
106 /** @var boolean whethre this question has been deleted/hidden in the question bank. */
107 public $hidden = 0;
108
7d2c7fed
TH
109 /** @var string question idnumber. */
110 public $idnumber;
111
d1b7e03d
TH
112 /** @var integer timestamp when this question was created. */
113 public $timecreated;
114
115 /** @var integer timestamp when this question was modified. */
116 public $timemodified;
117
118 /** @var integer userid of the use who created this question. */
119 public $createdby;
120
121 /** @var integer userid of the use who modified this question. */
122 public $modifiedby;
123
124 /** @var array of question_hints. */
125 public $hints = array();
126
127 /**
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
132 */
133 public function __construct() {
134 }
135
136 /**
137 * @return the name of the question type (for example multichoice) that this
138 * question is.
139 */
140 public function get_type_name() {
141 return $this->qtype->name();
142 }
143
144 /**
145 * Creat the appropriate behaviour for an attempt at this quetsion,
146 * given the desired (archetypal) behaviour.
147 *
148 * This default implementation will suit most normal graded questions.
149 *
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
153 * what is asked for.
154 *
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.
159 *
c4efeb2b 160 * @param question_attempt $qa the attempt we are creating a behaviour for.
d1b7e03d
TH
161 * @param string $preferredbehaviour the requested type of behaviour.
162 * @return question_behaviour the new behaviour object.
163 */
164 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
165 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
166 }
167
168 /**
ef31a283
TH
169 * Start a new attempt at this question, storing any information that will
170 * be needed later in the step.
d1b7e03d 171 *
ef31a283
TH
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).
d1b7e03d 175 *
ef31a283
TH
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(...).
178 *
179 * @param question_attempt_step The first step of the {@link question_attempt}
180 * being started. Can be used to store state.
1da821bb
TH
181 * @param int $varant which variant of this question to start. Will be between
182 * 1 and {@link get_num_variants()} inclusive.
ef31a283 183 */
1da821bb 184 public function start_attempt(question_attempt_step $step, $variant) {
ef31a283
TH
185 }
186
187 /**
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.
191 *
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.
196 *
197 * @param question_attempt_step The first step of the {@link question_attempt}
198 * being loaded.
d1b7e03d 199 */
ef31a283 200 public function apply_attempt_state(question_attempt_step $step) {
d1b7e03d
TH
201 }
202
203 /**
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
209 * inappropriate.
210 * @return string|null a plain text summary of this question.
211 */
ec3d4ef5 212 public function get_question_summary() {
22cebed5 213 return $this->html_to_text($this->questiontext, $this->questiontextformat);
d1b7e03d
TH
214 }
215
1da821bb
TH
216 /**
217 * @return int the number of vaiants that this question has.
218 */
219 public function get_num_variants() {
220 return 1;
221 }
222
223 /**
224 * @return string that can be used to seed the pseudo-random selection of a
225 * variant.
226 */
227 public function get_variants_selection_seed() {
228 return $this->stamp;
229 }
230
d1b7e03d
TH
231 /**
232 * Some questions can return a negative mark if the student gets it wrong.
233 *
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.
236 *
4e3d8293 237 * @return float minimum fraction this question will ever return.
d1b7e03d
TH
238 */
239 public function get_min_fraction() {
240 return 0;
241 }
242
4e3d8293
TH
243 /**
244 * Some questions can return a mark greater than the maximum.
245 *
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.
248 *
249 * @return float maximum fraction this question will ever return.
250 */
251 public function get_max_fraction() {
252 return 1;
253 }
254
d1b7e03d
TH
255 /**
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.
259 */
260 public function clear_wrong_from_response(array $response) {
261 return array();
262 }
263
264 /**
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.
269 */
270 public function get_num_parts_right(array $response) {
271 return array(null, null);
272 }
273
274 /**
b36d2d06 275 * @param moodle_page the page we are outputting to.
d1b7e03d
TH
276 * @return qtype_renderer the renderer to use for outputting this question.
277 */
2daffca5
TH
278 public function get_renderer(moodle_page $page) {
279 return $page->get_renderer($this->qtype->plugin_name());
d1b7e03d
TH
280 }
281
282 /**
283 * What data may be included in the form submission when a student submits
284 * this question in its current state?
285 *
286 * This information is used in calls to optional_param. The parameter name
287 * has {@link question_attempt::get_field_prefix()} automatically prepended.
288 *
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.
292 */
293 public abstract function get_expected_data();
294
295 /**
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
da22c012
K
298 * return one possibility. If it is not possible to compute a correct
299 * response, this method should return null.
d1b7e03d 300 *
da22c012 301 * @return array|null parameter name => value.
d1b7e03d
TH
302 */
303 public abstract function get_correct_response();
304
388f0473
JP
305
306 /**
58794ac9
JP
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.
388f0473 311 *
58794ac9 312 * In most cases the array will just be returned as is. Some question types will need to transform the keys of the array,
388f0473 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
58794ac9
JP
314 * advantage. The values that represent the response might also be changed in order to more meaningful to a human.
315 *
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
321 *
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.
388f0473
JP
324 *
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)
327 */
328 public function prepare_simulated_post_data($simulatedresponse) {
329 return $simulatedresponse;
330 }
331
58794ac9
JP
332 /**
333 * Does the opposite of {@link prepare_simulated_post_data}.
334 *
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.
337 *
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.
340 *
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.
343 */
344 public function get_student_response_values_for_simulation($realresponse) {
345 return $realresponse;
346 }
347
d1b7e03d
TH
348 /**
349 * Apply {@link format_text()} to some content with appropriate settings for
350 * this question.
351 *
352 * @param string $text some content that needs to be output.
22cebed5 353 * @param int $format the FORMAT_... constant.
068b4594
TH
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.
f7970e3c 357 * @param bool $clean Whether the HTML needs to be cleaned. Generally,
d1b7e03d
TH
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.
360 */
eaeb6b51
TH
361 public function format_text($text, $format, $qa, $component, $filearea, $itemid,
362 $clean = false) {
0ff4bd08 363 $formatoptions = new stdClass();
d1b7e03d
TH
364 $formatoptions->noclean = !$clean;
365 $formatoptions->para = false;
7a719748 366 $text = $qa->rewrite_pluginfile_urls($text, $component, $filearea, $itemid);
22cebed5 367 return format_text($text, $format, $formatoptions);
d1b7e03d
TH
368 }
369
ec3d4ef5
TH
370 /**
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.
22cebed5
TH
374 * @param int $format the FORMAT_... constant.
375 * @return string the equivalent plain text.
ec3d4ef5 376 */
22cebed5 377 public function html_to_text($text, $format) {
e2b388c1 378 return question_utils::to_plain_text($text, $format);
ec3d4ef5
TH
379 }
380
d1b7e03d 381 /** @return the result of applying {@link format_text()} to the question text. */
2b7da645 382 public function format_questiontext($qa) {
22cebed5
TH
383 return $this->format_text($this->questiontext, $this->questiontextformat,
384 $qa, 'question', 'questiontext', $this->id);
d1b7e03d
TH
385 }
386
387 /** @return the result of applying {@link format_text()} to the general feedback. */
2b7da645 388 public function format_generalfeedback($qa) {
22cebed5
TH
389 return $this->format_text($this->generalfeedback, $this->generalfeedbackformat,
390 $qa, 'question', 'generalfeedback', $this->id);
7a719748
TH
391 }
392
299d77dd
TH
393 /**
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.
399 */
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);
404 return trim($html);
405 }
406
7a719748
TH
407 /**
408 * Checks whether the users is allow to be served a particular file.
93cadb1e 409 * @param question_attempt $qa the question attempt being displayed.
7a719748
TH
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.
f7970e3c
TH
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.
7a719748
TH
416 */
417 public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
418 if ($component == 'question' && $filearea == 'questiontext') {
cf0b9432
TH
419 // Question text always visible, but check it is the right question id.
420 return $args[0] == $this->id;
7a719748
TH
421
422 } else if ($component == 'question' && $filearea == 'generalfeedback') {
cf0b9432 423 return $options->generalfeedback && $args[0] == $this->id;
7a719748
TH
424
425 } else {
426 // Unrecognised component or filearea.
427 return false;
428 }
d1b7e03d 429 }
a5dcaee3
JL
430
431 /**
432 * Return the question settings that define this question as structured data.
433 *
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.
436 *
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.
440 *
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.
443 *
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
446 * should be visible.
447 * @return mixed structure representing the question settings. In web services, this will be JSON-encoded.
448 */
449 public function get_question_definition_for_external_rendering(question_attempt $qa, question_display_options $options) {
450
451 debugging('This question does not implement the get_question_definition_for_external_rendering() method yet.',
452 DEBUG_DEVELOPER);
453 return null;
454 }
d1b7e03d
TH
455}
456
457
458/**
459 * This class represents a 'question' that actually does not allow the student
460 * to respond, like the description 'question' type.
461 *
7764183a
TH
462 * @copyright 2009 The Open University
463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
464 */
465class question_information_item extends question_definition {
466 public function __construct() {
467 parent::__construct();
468 $this->defaultmark = 0;
469 $this->penalty = 0;
470 $this->length = 0;
471 }
472
473 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
f3460297 474 return question_engine::make_behaviour('informationitem', $qa, $preferredbehaviour);
d1b7e03d
TH
475 }
476
477 public function get_expected_data() {
478 return array();
479 }
480
481 public function get_correct_response() {
482 return array();
483 }
484
485 public function get_question_summary() {
486 return null;
487 }
488}
489
490
491/**
492 * Interface that a {@link question_definition} must implement to be usable by
493 * the manual graded behaviour.
494 *
7764183a
TH
495 * @copyright 2009 The Open University
496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
497 */
498interface question_manually_gradable {
94cb5a66
LB
499 /**
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.
503 *
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.
507 */
508 public function is_gradable_response(array $response);
509
d1b7e03d
TH
510 /**
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.
514 *
eaeb6b51
TH
515 * @param array $response responses, as returned by
516 * {@link question_attempt_step::get_qt_data()}.
f7970e3c 517 * @return bool whether this response is a complete answer to this question.
d1b7e03d
TH
518 */
519 public function is_complete_response(array $response);
520
521 /**
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.
525 *
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.
f7970e3c 529 * @return bool whether the two sets of responses are the same - that is
d1b7e03d
TH
530 * whether the new set of responses can safely be discarded.
531 */
532 public function is_same_response(array $prevresponse, array $newresponse);
533
534 /**
535 * Produce a plain text summary of a response.
5c0654d7 536 * @param array $response a response, as might be passed to {@link grade_response()}.
d1b7e03d
TH
537 * @return string a plain text summary of that response, that could be used in reports.
538 */
539 public function summarise_response(array $response);
540
5c0654d7
SL
541 /**
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.
545 *
546 * @param string $summary a string, which might have come from summarise_response
547 * @return array a response that could have lead to that.
548 */
549 public function un_summarise_response(string $summary);
550
d1b7e03d
TH
551 /**
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.
557 */
558 public function classify_response(array $response);
559}
560
561
562/**
563 * This class is used in the return value from
564 * {@link question_manually_gradable::classify_response()}.
565 *
7764183a
TH
566 * @copyright 2010 The Open University
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
568 */
569class question_classified_response {
570 /**
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()}.
574 */
575 public $responseclassid;
576 /** @var string the actual response the student gave to this part. */
577 public $response;
578 /** @var number the fraction this part of the response earned. */
579 public $fraction;
580 /**
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.
585 */
586 public function __construct($responseclassid, $response, $fraction) {
587 $this->responseclassid = $responseclassid;
588 $this->response = $response;
589 $this->fraction = $fraction;
590 }
591
592 public static function no_response() {
e5b0920e 593 return new question_classified_response(null, get_string('noresponse', 'question'), null);
d1b7e03d
TH
594 }
595}
596
597
598/**
599 * Interface that a {@link question_definition} must implement to be usable by
600 * the various automatic grading behaviours.
601 *
7764183a
TH
602 * @copyright 2009 The Open University
603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
604 */
605interface question_automatically_gradable extends question_manually_gradable {
d1b7e03d
TH
606 /**
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.
610 */
611 public function get_validation_error(array $response);
612
613 /**
eaeb6b51 614 * Grade a response to the question, returning a fraction between
4e3d8293 615 * get_min_fraction() and get_max_fraction(), and the corresponding {@link question_state}
eaeb6b51
TH
616 * right, partial or wrong.
617 * @param array $response responses, as returned by
618 * {@link question_attempt_step::get_qt_data()}.
4e3d8293 619 * @return array (float, integer) the fraction, and the state.
d1b7e03d
TH
620 */
621 public function grade_response(array $response);
622
623 /**
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.
f7970e3c 628 * @param int $hintnumber Which hint to display. Indexed starting from 0
d1b7e03d
TH
629 * @param question_attempt $qa The question_attempt.
630 */
631 public function get_hint($hintnumber, question_attempt $qa);
632
633 /**
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
637 * inappropriate.
638 * @return string|null a plain text summary of the right answer to this question.
639 */
640 public function get_right_answer_summary();
641}
642
643
644/**
645 * Interface that a {@link question_definition} must implement to be usable by
646 * the interactivecountback behaviour.
647 *
7764183a
TH
648 * @copyright 2010 The Open University
649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
650 */
651interface question_automatically_gradable_with_countback extends question_automatically_gradable {
652 /**
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.
f7970e3c 658 * @param int $totaltries The maximum number of tries allowed.
d1b7e03d
TH
659 * @return numeric the fraction that should be awarded for this
660 * sequence of response.
661 */
662 public function compute_final_grade($responses, $totaltries);
663}
664
665
666/**
667 * This class represents a real question. That is, one that is not a
668 * {@link question_information_item}.
669 *
7764183a
TH
670 * @copyright 2009 The Open University
671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
672 */
673abstract class question_with_responses extends question_definition
674 implements question_manually_gradable {
c7df5006 675 public function classify_response(array $response) {
d1b7e03d
TH
676 return array();
677 }
94cb5a66
LB
678
679 public function is_gradable_response(array $response) {
680 return $this->is_complete_response($response);
681 }
5c0654d7
SL
682
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.');
686 }
d1b7e03d
TH
687}
688
689
690/**
691 * This class represents a question that can be graded automatically.
692 *
7764183a
TH
693 * @copyright 2009 The Open University
694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
695 */
696abstract 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;
700
d1b7e03d
TH
701 public function get_right_answer_summary() {
702 $correctresponse = $this->get_correct_response();
703 if (empty($correctresponse)) {
704 return null;
705 }
706 return $this->summarise_response($correctresponse);
707 }
708
93cadb1e
TH
709 /**
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.
c28bfbef 714 * @param array $args the remaining bits of the file path.
f7970e3c 715 * @return bool whether access to the file should be allowed.
93cadb1e 716 */
c28bfbef 717 protected function check_combined_feedback_file_access($qa, $options, $filearea, $args = null) {
93cadb1e
TH
718 $state = $qa->get_state();
719
c28bfbef
TH
720 if ($args === null) {
721 debugging('You must pass $args as the fourth argument to check_combined_feedback_file_access.',
722 DEBUG_DEVELOPER);
723 $args = array($this->id); // Fake it for now, so the rest of this method works.
724 }
725
93cadb1e
TH
726 if (!$state->is_finished()) {
727 $response = $qa->get_last_qt_data();
728 if (!$this->is_gradable_response($response)) {
729 return false;
730 }
731 list($notused, $state) = $this->grade_response($response);
732 }
733
cf0b9432
TH
734 return $options->feedback && $state->get_feedback_class() . 'feedback' == $filearea &&
735 $args[0] == $this->id;
93cadb1e
TH
736 }
737
738 /**
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.
f7970e3c 743 * @return bool whether access to the file should be allowed.
93cadb1e
TH
744 */
745 protected function check_hint_file_access($qa, $options, $args) {
746 if (!$options->feedback) {
747 return false;
748 }
749 $hint = $qa->get_applicable_hint();
3d9645ae 750 $hintid = reset($args); // Itemid is hint id.
93cadb1e
TH
751 return $hintid == $hint->id;
752 }
753
d1b7e03d
TH
754 public function get_hint($hintnumber, question_attempt $qa) {
755 if (!isset($this->hints[$hintnumber])) {
756 return null;
757 }
758 return $this->hints[$hintnumber];
759 }
7a719748
TH
760
761 public function format_hint(question_hint $hint, question_attempt $qa) {
eaeb6b51
TH
762 return $this->format_text($hint->hint, $hint->hintformat, $qa,
763 'question', 'hint', $hint->id);
7a719748 764 }
d1b7e03d
TH
765}
766
767
768/**
769 * This class represents a question that can be graded automatically with
770 * countback grading in interactive mode.
771 *
7764183a
TH
772 * @copyright 2010 The Open University
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
774 */
775abstract class question_graded_automatically_with_countback
776 extends question_graded_automatically
777 implements question_automatically_gradable_with_countback {
778
779 public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
780 if ($preferredbehaviour == 'interactive') {
eaeb6b51
TH
781 return question_engine::make_behaviour('interactivecountback',
782 $qa, $preferredbehaviour);
d1b7e03d
TH
783 }
784 return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
785 }
786}
787
788
789/**
790 * This class represents a question that can be graded automatically by using
791 * a {@link question_grading_strategy}.
792 *
7764183a
TH
793 * @copyright 2009 The Open University
794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
795 */
796abstract class question_graded_by_strategy extends question_graded_automatically {
797 /** @var question_grading_strategy the strategy to use for grading. */
798 protected $gradingstrategy;
799
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;
804 }
805
806 public function get_correct_response() {
807 $answer = $this->get_correct_answer();
808 if (!$answer) {
809 return array();
810 }
811
812 return array('answer' => $answer->answer);
813 }
814
815 /**
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.
820 */
821 public function get_matching_answer(array $response) {
822 return $this->gradingstrategy->grade($response);
823 }
824
825 /**
826 * @return question_answer an answer that contains the a response that would
827 * get full marks.
828 */
829 public function get_correct_answer() {
830 return $this->gradingstrategy->get_correct_answer();
831 }
832
833 public function grade_response(array $response) {
834 $answer = $this->get_matching_answer($response);
835 if ($answer) {
eaeb6b51
TH
836 return array($answer->fraction,
837 question_state::graded_state_for_fraction($answer->fraction));
d1b7e03d
TH
838 } else {
839 return array(0, question_state::$gradedwrong);
840 }
841 }
842
843 public function classify_response(array $response) {
844 if (empty($response['answer'])) {
845 return array($this->id => question_classified_response::no_response());
846 }
847
848 $ans = $this->get_matching_answer($response);
849 if (!$ans) {
24400682
TH
850 return array($this->id => new question_classified_response(
851 0, $response['answer'], 0));
d1b7e03d 852 }
24400682 853
d1b7e03d
TH
854 return array($this->id => new question_classified_response(
855 $ans->id, $response['answer'], $ans->fraction));
856 }
857}
858
859
860/**
861 * Class to represent a question answer, loaded from the question_answers table
862 * in the database.
863 *
7764183a
TH
864 * @copyright 2009 The Open University
865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
866 */
867class question_answer {
5f7cfba7
TH
868 /** @var integer the answer id. */
869 public $id;
870
d1b7e03d
TH
871 /** @var string the answer. */
872 public $answer;
873
22cebed5
TH
874 /** @var integer one of the FORMAT_... constans. */
875 public $answerformat = FORMAT_PLAIN;
876
d1b7e03d
TH
877 /** @var number the fraction this answer is worth. */
878 public $fraction;
879
880 /** @var string the feedback for this answer. */
881 public $feedback;
882
5f7cfba7
TH
883 /** @var integer one of the FORMAT_... constans. */
884 public $feedbackformat;
885
d1b7e03d
TH
886 /**
887 * Constructor.
22cebed5 888 * @param int $id the answer.
d1b7e03d
TH
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.
22cebed5 892 * @param int $feedbackformat the format of the feedback.
d1b7e03d 893 */
5f7cfba7
TH
894 public function __construct($id, $answer, $fraction, $feedback, $feedbackformat) {
895 $this->id = $id;
d1b7e03d
TH
896 $this->answer = $answer;
897 $this->fraction = $fraction;
898 $this->feedback = $feedback;
5f7cfba7 899 $this->feedbackformat = $feedbackformat;
d1b7e03d
TH
900 }
901}
902
903
904/**
905 * Class to represent a hint associated with a question.
906 * Used by iteractive mode, etc. A question has an array of these.
907 *
7764183a
TH
908 * @copyright 2010 The Open University
909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
910 */
911class question_hint {
7a719748
TH
912 /** @var integer The hint id. */
913 public $id;
914 /** @var string The feedback hint to be shown. */
d1b7e03d 915 public $hint;
7a719748
TH
916 /** @var integer The corresponding text FORMAT_... type. */
917 public $hintformat;
d1b7e03d
TH
918
919 /**
920 * Constructor.
f7970e3c 921 * @param int the hint id from the database.
d1b7e03d 922 * @param string $hint The hint text
f7970e3c 923 * @param int the corresponding text FORMAT_... type.
d1b7e03d 924 */
7a719748
TH
925 public function __construct($id, $hint, $hintformat) {
926 $this->id = $id;
d1b7e03d 927 $this->hint = $hint;
7a719748 928 $this->hintformat = $hintformat;
d1b7e03d
TH
929 }
930
931 /**
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
935 */
936 public static function load_from_record($row) {
7a719748 937 return new question_hint($row->id, $row->hint, $row->hintformat);
d1b7e03d
TH
938 }
939
940 /**
941 * Adjust this display options according to the hint settings.
942 * @param question_display_options $options
943 */
944 public function adjust_display_options(question_display_options $options) {
945 // Do nothing.
946 }
947}
948
949
950/**
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.
954 *
7764183a
TH
955 * @copyright 2010 The Open University
956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
957 */
958class 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;
961
962 /** @var boolean option to clear the parts of the question that were wrong on retry. */
963 public $clearwrong;
964
965 /**
966 * Constructor.
f7970e3c 967 * @param int the hint id from the database.
d1b7e03d 968 * @param string $hint The hint text
f7970e3c
TH
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.
d1b7e03d 972 */
7a719748
TH
973 public function __construct($id, $hint, $hintformat, $shownumcorrect, $clearwrong) {
974 parent::__construct($id, $hint, $hintformat);
d1b7e03d
TH
975 $this->shownumcorrect = $shownumcorrect;
976 $this->clearwrong = $clearwrong;
977 }
978
979 /**
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
983 */
984 public static function load_from_record($row) {
7a719748
TH
985 return new question_hint_with_parts($row->id, $row->hint, $row->hintformat,
986 $row->shownumcorrect, $row->clearwrong);
d1b7e03d
TH
987 }
988
989 public function adjust_display_options(question_display_options $options) {
990 parent::adjust_display_options($options);
991 if ($this->clearwrong) {
992 $options->clearwrong = true;
993 }
994 $options->numpartscorrect = $this->shownumcorrect;
995 }
996}
997
998
999/**
1000 * This question_grading_strategy interface. Used to share grading code between
1001 * questions that that subclass {@link question_graded_by_strategy}.
1002 *
7764183a
TH
1003 * @copyright 2009 The Open University
1004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1005 */
1006interface question_grading_strategy {
1007 /**
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.
1012 */
1013 public function grade(array $response);
1014
1015 /**
1016 * @return question_answer an answer that contains the a response that would
1017 * get full marks.
1018 */
1019 public function get_correct_answer();
1020}
1021
1022
1023/**
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}.
1027 *
7764183a
TH
1028 * @copyright 2009 The Open University
1029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1030 */
1031interface question_response_answer_comparer {
1032 /** @return array of {@link question_answers}. */
1033 public function get_answers();
1034
1035 /**
1036 * @param array $response the response.
1037 * @param question_answer $answer an answer.
f7970e3c 1038 * @return bool whether the response matches the answer.
d1b7e03d
TH
1039 */
1040 public function compare_response_with_answer(array $response, question_answer $answer);
1041}
1042
1043
1044/**
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.
1049 *
7764183a
TH
1050 * @copyright 2009 The Open University
1051 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1052 */
1053class question_first_matching_answer_grading_strategy implements question_grading_strategy {
1054 /**
1055 * @var question_response_answer_comparer (presumably also a
1056 * {@link question_definition}) the question we are doing the grading for.
1057 */
1058 protected $question;
1059
1060 /**
1061 * @param question_response_answer_comparer $question (presumably also a
1062 * {@link question_definition}) the question we are doing the grading for.
1063 */
1064 public function __construct(question_response_answer_comparer $question) {
1065 $this->question = $question;
1066 }
1067
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)) {
1071 $answer->id = $aid;
1072 return $answer;
1073 }
1074 }
1075 return null;
1076 }
1077
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) {
1082 return $answer;
1083 }
1084 }
1085 return null;
1086 }
01c898ec 1087}