MDL-51090: mod_quiz grading validation of an essay question
[moodle.git] / question / behaviour / behaviourbase.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 17/**
f3460297 18 * Defines the question behaviour base class
d1b7e03d 19 *
017bc1d9 20 * @package moodlecore
d1b7e03d 21 * @subpackage questionbehaviours
017bc1d9
TH
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
24 */
25
26
a17b297d
TH
27defined('MOODLE_INTERNAL') || die();
28
29
d1b7e03d
TH
30/**
31 * The base class for question behaviours.
32 *
33 * A question behaviour is used by the question engine, specifically by
34 * a {@link question_attempt} to manage the flow of actions a student can take
35 * as they work through a question, and later, as a teacher manually grades it.
36 * In turn, the behaviour will delegate certain processing to the
37 * relevant {@link question_definition}.
38 *
017bc1d9
TH
39 * @copyright 2009 The Open University
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
41 */
42abstract class question_behaviour {
d1b7e03d
TH
43
44 /** @var question_attempt the question attempt we are managing. */
45 protected $qa;
f3460297 46
d1b7e03d
TH
47 /** @var question_definition shortcut to $qa->get_question(). */
48 protected $question;
49
50 /**
51 * Normally you should not call this constuctor directly. The appropriate
52 * behaviour object is created automatically as part of
53 * {@link question_attempt::start()}.
54 * @param question_attempt $qa the question attempt we will be managing.
55 * @param string $preferredbehaviour the type of behaviour that was actually
56 * requested. This information is not needed in most cases, the type of
57 * subclass is enough, but occasionally it is needed.
58 */
59 public function __construct(question_attempt $qa, $preferredbehaviour) {
60 $this->qa = $qa;
61 $this->question = $qa->get_question();
15d660a8 62 if (!$this->is_compatible_question($this->question)) {
88f0eb15 63 throw new coding_exception('This behaviour (' . $this->get_name() .
d1b7e03d
TH
64 ') cannot work with this question (' . get_class($this->question) . ')');
65 }
66 }
67
15d660a8
TH
68 /**
69 * Some behaviours can only work with certing types of question. This method
70 * allows the behaviour to verify that a question is compatible.
3d17cd3f
TH
71 *
72 * This implementation is only provided for backwards-compatibility. You should
73 * override this method if you are implementing a behaviour.
74 *
15d660a8
TH
75 * @param question_definition $question the question.
76 */
06616f4b 77 public abstract function is_compatible_question(question_definition $question);
d1b7e03d
TH
78
79 /**
80 * @return string the name of this behaviour. For example the name of
81 * qbehaviour_mymodle is 'mymodel'.
82 */
83 public function get_name() {
84 return substr(get_class($this), 11);
85 }
86
fd7a8af5
TH
87 /**
88 * Whether the current attempt at this question could be completed just by the
89 * student interacting with the question, before $qa->finish() is called.
90 *
91 * @return boolean whether the attempt can finish naturally.
92 */
93 public function can_finish_during_attempt() {
94 return false;
95 }
96
d1b7e03d
TH
97 /**
98 * Cause the question to be renderered. This gets the appropriate behaviour
99 * renderer using {@link get_renderer()}, and adjusts the display
100 * options using {@link adjust_display_options()} and then calls
101 * {@link core_question_renderer::question()} to do the work.
102 * @param question_display_options $options controls what should and should not be displayed.
103 * @param unknown_type $number the question number to display.
104 * @param core_question_renderer $qoutput the question renderer that will coordinate everything.
105 * @param qtype_renderer $qtoutput the question type renderer that will be helping.
106 * @return HTML fragment.
107 */
108 public function render(question_display_options $options, $number,
109 core_question_renderer $qoutput, qtype_renderer $qtoutput) {
2daffca5 110 $behaviouroutput = $this->get_renderer($qoutput->get_page());
d1b7e03d
TH
111 $options = clone($options);
112 $this->adjust_display_options($options);
113 return $qoutput->question($this->qa, $behaviouroutput, $qtoutput, $options, $number);
114 }
115
7a719748
TH
116 /**
117 * Checks whether the users is allow to be served a particular file.
118 * @param question_display_options $options the options that control display of the question.
119 * @param string $component the name of the component we are serving files for.
120 * @param string $filearea the name of the file area.
121 * @param array $args the remaining bits of the file path.
f7970e3c
TH
122 * @param bool $forcedownload whether the user must be forced to download the file.
123 * @return bool true if the user can access this file.
7a719748
TH
124 */
125 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
126 $this->adjust_display_options($options);
1631ceea
TH
127 return $this->question->check_file_access($this->qa, $options, $component,
128 $filearea, $args, $forcedownload);
7a719748
TH
129 }
130
d1b7e03d 131 /**
2daffca5 132 * @param moodle_page $page the page to render for.
d1b7e03d
TH
133 * @return qbehaviour_renderer get the appropriate renderer to use for this model.
134 */
2daffca5
TH
135 public function get_renderer(moodle_page $page) {
136 return $page->get_renderer(get_class($this));
d1b7e03d
TH
137 }
138
139 /**
140 * Make any changes to the display options before a question is rendered, so
141 * that it can be displayed in a way that is appropriate for the statue it is
142 * currently in. For example, by default, if the question is finished, we
143 * ensure that it is only ever displayed read-only.
144 * @param question_display_options $options the options to adjust. Just change
145 * the properties of this object - objects are passed by referece.
146 */
147 public function adjust_display_options(question_display_options $options) {
148 if (!$this->qa->has_marks()) {
149 $options->correctness = false;
150 $options->numpartscorrect = false;
151 }
152 if ($this->qa->get_state()->is_finished()) {
153 $options->readonly = true;
154 $options->numpartscorrect = $options->numpartscorrect &&
155 $this->qa->get_state()->is_partially_correct() &&
156 !empty($this->question->shownumcorrect);
157 } else {
158 $options->hide_all_feedback();
159 }
160 }
161
162 /**
163 * Get the most applicable hint for the question in its current state.
164 * @return question_hint the most applicable hint, or null, if none.
165 */
166 public function get_applicable_hint() {
167 return null;
168 }
169
170 /**
171 * What is the minimum fraction that can be scored for this question.
ef31a283 172 * Normally this will be based on $this->question->get_min_fraction(),
4e3d8293 173 * but may be modified in some way by the behaviour.
d1b7e03d
TH
174 *
175 * @return number the minimum fraction when this question is attempted under
4e3d8293 176 * this behaviour.
d1b7e03d
TH
177 */
178 public function get_min_fraction() {
179 return 0;
180 }
181
4e3d8293
TH
182 /**
183 * Return the maximum possible fraction that can be scored for this question.
184 * Normally this will be based on $this->question->get_max_fraction(),
185 * but may be modified in some way by the behaviour.
186 *
187 * @return number the maximum fraction when this question is attempted under
188 * this behaviour.
189 */
190 public function get_max_fraction() {
191 return $this->question->get_max_fraction();
192 }
193
d1b7e03d
TH
194 /**
195 * Return an array of the behaviour variables that could be submitted
196 * as part of a question of this type, with their types, so they can be
197 * properly cleaned.
198 * @return array variable name => PARAM_... constant.
199 */
200 public function get_expected_data() {
201 if (!$this->qa->get_state()->is_finished()) {
202 return array();
203 }
204
1eb470fc 205 $vars = array('comment' => PARAM_RAW, 'commentformat' => PARAM_INT);
d1b7e03d
TH
206 if ($this->qa->get_max_mark()) {
207 $vars['mark'] = question_attempt::PARAM_MARK;
61cca0b7 208 $vars['maxmark'] = PARAM_FLOAT;
d1b7e03d
TH
209 }
210 return $vars;
211 }
212
213 /**
214 * Return an array of question type variables for the question in its current
215 * state. Normally, if {@link adjust_display_options()} would set
216 * {@link question_display_options::$readonly} to true, then this method
217 * should return an empty array, otherwise it should return
218 * $this->question->get_expected_data(). Thus, there should be little need to
219 * override this method.
220 * @return array|string variable name => PARAM_... constant, or, as a special case
221 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
222 * meaning take all the raw submitted data belonging to this question.
223 */
224 public function get_expected_qt_data() {
225 $fakeoptions = new question_display_options();
226 $fakeoptions->readonly = false;
227 $this->adjust_display_options($fakeoptions);
228 if ($fakeoptions->readonly) {
229 return array();
230 } else {
231 return $this->question->get_expected_data();
232 }
233 }
234
235 /**
236 * Return an array of any im variables, and the value required to get full
237 * marks.
238 * @return array variable name => value.
239 */
240 public function get_correct_response() {
241 return array();
242 }
243
244 /**
245 * Generate a brief, plain-text, summary of this question. This is used by
246 * various reports. This should show the particular variant of the question
247 * as presented to students. For example, the calculated quetsion type would
248 * fill in the particular numbers that were presented to the student.
249 * This method will return null if such a summary is not possible, or
250 * inappropriate.
251 *
252 * Normally, this method delegates to {question_definition::get_question_summary()}.
253 *
254 * @return string|null a plain text summary of this question.
255 */
256 public function get_question_summary() {
ec3d4ef5 257 return $this->question->get_question_summary();
d1b7e03d
TH
258 }
259
260 /**
261 * Generate a brief, plain-text, summary of the correct answer to this question.
262 * This is used by various reports, and can also be useful when testing.
263 * This method will return null if such a summary is not possible, or
264 * inappropriate.
265 *
266 * @return string|null a plain text summary of the right answer to this question.
267 */
268 public function get_right_answer_summary() {
269 return null;
270 }
271
272 /**
273 * Used by {@link start_based_on()} to get the data needed to start a new
274 * attempt from the point this attempt has go to.
275 * @return array name => value pairs.
276 */
277 public function get_resume_data() {
278 $olddata = $this->qa->get_step(0)->get_all_data();
279 $olddata = $this->qa->get_last_qt_data() + $olddata;
280 $olddata = $this->get_our_resume_data() + $olddata;
281 return $olddata;
282 }
283
284 /**
285 * Used by {@link start_based_on()} to get the data needed to start a new
286 * attempt from the point this attempt has go to.
287 * @return unknown_type
288 */
289 protected function get_our_resume_data() {
290 return array();
291 }
292
293 /**
038014c4
JP
294 * Classify responses for this question into a number of sub parts and response classes as defined by
295 * {@link \question_type::get_possible_responses} for this question type.
296 *
297 * @param string $whichtries which tries to analyse for response analysis. Will be one of
298 * question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
299 * Defaults to question_attempt::LAST_TRY.
300 * @return (question_classified_response|array)[] If $whichtries is question_attempt::FIRST_TRY or LAST_TRY index is subpartid
301 * and values are question_classified_response instances.
302 * If $whichtries is question_attempt::ALL_TRIES then first key is submitted response no
303 * and the second key is subpartid.
304 */
305 public function classify_response($whichtries = question_attempt::LAST_TRY) {
306 if ($whichtries == question_attempt::LAST_TRY) {
307 return $this->question->classify_response($this->qa->get_last_qt_data());
308 } else {
309 $stepswithsubmit = $this->qa->get_steps_with_submitted_response_iterator();
310 if ($whichtries == question_attempt::FIRST_TRY) {
312dce0e
TH
311 $firsttry = $stepswithsubmit[1];
312 if ($firsttry) {
313 return $this->question->classify_response($firsttry->get_qt_data());
314 } else {
315 return $this->question->classify_response(array());
316 }
038014c4
JP
317 } else {
318 $classifiedresponses = array();
319 foreach ($stepswithsubmit as $submittedresponseno => $step) {
320 $classifiedresponses[$submittedresponseno] = $this->question->classify_response($step->get_qt_data());
321 }
96a0b9aa 322 return $classifiedresponses;
038014c4
JP
323 }
324 }
325 }
326
d1b7e03d
TH
327 /**
328 * Generate a brief textual description of the current state of the question,
329 * normally displayed under the question number.
330 *
f7970e3c 331 * @param bool $showcorrectness Whether right/partial/wrong states should
d1b7e03d
TH
332 * be distinguised.
333 * @return string a brief summary of the current state of the qestion attempt.
334 */
335 public function get_state_string($showcorrectness) {
336 return $this->qa->get_state()->default_string($showcorrectness);
337 }
338
c7df5006 339 public abstract function summarise_action(question_attempt_step $step);
d1b7e03d
TH
340
341 /**
ef31a283
TH
342 * Initialise the first step in a question attempt when a new
343 * {@link question_attempt} is being started.
d1b7e03d 344 *
f8e28244
RK
345 * This method must call $this->question->start_attempt($step, $variant), and may
346 * perform additional processing if the behaviour requries it.
d1b7e03d 347 *
ef31a283
TH
348 * @param question_attempt_step $step the first step of the
349 * question_attempt being started.
1da821bb 350 * @param int $variant which variant of the question to use.
d1b7e03d 351 */
1da821bb
TH
352 public function init_first_step(question_attempt_step $step, $variant) {
353 $this->question->start_attempt($step, $variant);
f8e28244
RK
354 $step->set_state(question_state::$todo);
355 }
356
357 /**
358 * When an attempt is started based on a previous attempt (see
359 * {@link question_attempt::start_based_on}) this method is called to setup
360 * the new attempt.
361 *
362 * This method must call $this->question->apply_attempt_state($step), and may
363 * perform additional processing if the behaviour requries it.
364 *
365 * @param question_attempt_step The first step of the {@link question_attempt}
366 * being loaded.
367 */
368 public function apply_attempt_state(question_attempt_step $step) {
369 $this->question->apply_attempt_state($step);
370 $step->set_state(question_state::$todo);
d1b7e03d
TH
371 }
372
373 /**
374 * Checks whether two manual grading actions are the same. That is, whether
375 * the comment, and the mark (if given) is the same.
376 *
377 * @param question_attempt_step $pendingstep contains the new responses.
f7970e3c 378 * @return bool whether the new response is the same as we already have.
d1b7e03d
TH
379 */
380 protected function is_same_comment($pendingstep) {
381 $previouscomment = $this->qa->get_last_behaviour_var('comment');
382 $newcomment = $pendingstep->get_behaviour_var('comment');
383
384 if (is_null($previouscomment) && !html_is_blank($newcomment) ||
385 $previouscomment != $newcomment) {
386 return false;
387 }
388
389 // So, now we know the comment is the same, so check the mark, if present.
390 $previousfraction = $this->qa->get_fraction();
391 $newmark = $pendingstep->get_behaviour_var('mark');
392
393 if (is_null($previousfraction)) {
394 return is_null($newmark) || $newmark === '';
395 } else if (is_null($newmark) || $newmark === '') {
396 return false;
397 }
398
399 $newfraction = $newmark / $pendingstep->get_behaviour_var('maxmark');
400
401 return abs($newfraction - $previousfraction) < 0.0000001;
402 }
403
404 /**
405 * The main entry point for processing an action.
406 *
407 * All the various operations that can be performed on a
408 * {@link question_attempt} get channeled through this function, except for
409 * {@link question_attempt::start()} which goes to {@link init_first_step()}.
410 * {@link question_attempt::finish()} becomes an action with im vars
411 * finish => 1, and manual comment/grade becomes an action with im vars
412 * comment => comment text, and mark => ..., max_mark => ... if the question
413 * is graded.
414 *
415 * This method should first determine whether the action is significant. For
416 * example, if no actual action is being performed, but instead the current
417 * responses are being saved, and there has been no change since the last
418 * set of responses that were saved, this the action is not significatn. In
419 * this case, this method should return {@link question_attempt::DISCARD}.
420 * Otherwise it should return {@link question_attempt::KEEP}.
421 *
422 * If the action is significant, this method should also perform any
423 * necessary updates to $pendingstep. For example, it should call
424 * {@link question_attempt_step::set_state()} to set the state that results
425 * from this action, and if this is a grading action, it should call
426 * {@link question_attempt_step::set_fraction()}.
427 *
428 * This method can also call {@link question_attempt_step::set_behaviour_var()} to
429 * store additional infomation. There are two main uses for this. This can
430 * be used to store the result of any randomisation done. It is important to
431 * store the result of randomisation once, and then in future use the same
432 * outcome if the actions are ever replayed. This is how regrading works.
433 * The other use is to cache the result of expensive computations performed
434 * on the raw response data, so that subsequent display and review of the
435 * question does not have to repeat the same expensive computations.
436 *
437 * Often this method is implemented as a dispatching method that examines
438 * the pending step to determine the kind of action being performed, and
439 * then calls a more specific method like {@link process_save()} or
440 * {@link process_comment()}. Look at some of the standard behaviours
441 * for examples.
442 *
443 * @param question_attempt_pending_step $pendingstep a partially initialised step
1631ceea
TH
444 * containing all the information about the action that is being peformed. This
445 * information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
f7970e3c 446 * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
d1b7e03d
TH
447 */
448 public abstract function process_action(question_attempt_pending_step $pendingstep);
449
0a606a2b
TH
450 /**
451 * Auto-saved data. By default this does nothing. interesting processing is
452 * done in {@link question_behaviour_with_save}.
453 *
454 * @param question_attempt_pending_step $pendingstep a partially initialised step
455 * containing all the information about the action that is being peformed. This
456 * information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
457 * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
458 */
459 public function process_autosave(question_attempt_pending_step $pendingstep) {
460 return question_attempt::DISCARD;
461 }
462
d1b7e03d
TH
463 /**
464 * Implementation of processing a manual comment/grade action that should
465 * be suitable for most subclasses.
466 * @param question_attempt_pending_step $pendingstep a partially initialised step
467 * containing all the information about the action that is being peformed.
f7970e3c 468 * @return bool either {@link question_attempt::KEEP}
d1b7e03d
TH
469 */
470 public function process_comment(question_attempt_pending_step $pendingstep) {
471 if (!$this->qa->get_state()->is_finished()) {
472 throw new coding_exception('Cannot manually grade a question before it is finshed.');
473 }
474
475 if ($this->is_same_comment($pendingstep)) {
476 return question_attempt::DISCARD;
477 }
478
479 if ($pendingstep->has_behaviour_var('mark')) {
1631ceea
TH
480 $fraction = $pendingstep->get_behaviour_var('mark') /
481 $pendingstep->get_behaviour_var('maxmark');
d1b7e03d
TH
482 if ($pendingstep->get_behaviour_var('mark') === '') {
483 $fraction = null;
4e3d8293 484 } else if ($fraction > $this->qa->get_max_fraction() || $fraction < $this->qa->get_min_fraction()) {
d1b7e03d 485 throw new coding_exception('Score out of range when processing ' .
15dd7727 486 'a manual grading action.', 'Question ' . $this->question->id .
ee326d5e 487 ', slot ' . $this->qa->get_slot() . ', fraction ' . $fraction);
d1b7e03d
TH
488 }
489 $pendingstep->set_fraction($fraction);
490 }
491
1631ceea
TH
492 $pendingstep->set_state($this->qa->get_state()->corresponding_commented_state(
493 $pendingstep->get_fraction()));
d1b7e03d
TH
494 return question_attempt::KEEP;
495 }
496
497 /**
498 * @param $comment the comment text to format. If omitted,
499 * $this->qa->get_manual_comment() is used.
7a719748 500 * @param $commentformat the format of the comment, one of the FORMAT_... constants.
d1b7e03d
TH
501 * @return string the comment, ready to be output.
502 */
7a719748 503 public function format_comment($comment = null, $commentformat = null) {
0ff4bd08 504 $formatoptions = new stdClass();
d1b7e03d
TH
505 $formatoptions->noclean = true;
506 $formatoptions->para = false;
507
508 if (is_null($comment)) {
7a719748 509 list($comment, $commentformat) = $this->qa->get_manual_comment();
d1b7e03d
TH
510 }
511
7a719748 512 return format_text($comment, $commentformat, $formatoptions);
d1b7e03d
TH
513 }
514
515 /**
516 * @return string a summary of a manual comment action.
517 * @param unknown_type $step
518 */
519 protected function summarise_manual_comment($step) {
0ff4bd08 520 $a = new stdClass();
d1b7e03d
TH
521 if ($step->has_behaviour_var('comment')) {
522 $a->comment = shorten_text(html_to_text($this->format_comment(
523 $step->get_behaviour_var('comment')), 0, false), 200);
524 } else {
525 $a->comment = '';
526 }
527
528 $mark = $step->get_behaviour_var('mark');
529 if (is_null($mark) || $mark === '') {
530 return get_string('commented', 'question', $a->comment);
531 } else {
532 $a->mark = $mark / $step->get_behaviour_var('maxmark') * $this->qa->get_max_mark();
533 return get_string('manuallygraded', 'question', $a);
534 }
535 }
536
537 public function summarise_start($step) {
538 return get_string('started', 'question');
539 }
540
541 public function summarise_finish($step) {
542 return get_string('attemptfinished', 'question');
543 }
99caa248
JP
544
545 /**
546 * Does this step include a response submitted by a student?
547 *
548 * This method should return true for any attempt explicitly submitted by a student. The question engine itself will also
549 * automatically recognise any last saved response before the attempt is finished, you don't need to return true here for these
550 * steps with responses which are not explicitly submitted by the student.
551 *
552 * @param question_attempt_step $step
553 * @return bool is this a step within a question attempt that includes a submitted response by a student.
554 */
555 public function step_has_a_submitted_response($step) {
556 return false;
557 }
d1b7e03d
TH
558}
559
560
561/**
562 * A subclass of {@link question_behaviour} that implements a save
563 * action that is suitable for most questions that implement the
564 * {@link question_manually_gradable} interface.
565 *
f7970e3c
TH
566 * @copyright 2009 The Open University
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
568 */
569abstract class question_behaviour_with_save extends question_behaviour {
570 public function required_question_definition_type() {
571 return 'question_manually_gradable';
572 }
573
f8e28244
RK
574 public function apply_attempt_state(question_attempt_step $step) {
575 parent::apply_attempt_state($step);
576 if ($this->question->is_complete_response($step->get_qt_data())) {
577 $step->set_state(question_state::$complete);
578 }
579 }
580
d1b7e03d
TH
581 /**
582 * Work out whether the response in $pendingstep are significantly different
583 * from the last set of responses we have stored.
584 * @param question_attempt_step $pendingstep contains the new responses.
f7970e3c 585 * @return bool whether the new response is the same as we already have.
d1b7e03d
TH
586 */
587 protected function is_same_response(question_attempt_step $pendingstep) {
588 return $this->question->is_same_response(
589 $this->qa->get_last_step()->get_qt_data(), $pendingstep->get_qt_data());
590 }
591
592 /**
593 * Work out whether the response in $pendingstep represent a complete answer
594 * to the question. Normally this will call
595 * {@link question_manually_gradable::is_complete_response}, but some
596 * behaviours, for example the CBM ones, have their own parts to the
597 * response.
598 * @param question_attempt_step $pendingstep contains the new responses.
f7970e3c 599 * @return bool whether the new response is complete.
d1b7e03d
TH
600 */
601 protected function is_complete_response(question_attempt_step $pendingstep) {
602 return $this->question->is_complete_response($pendingstep->get_qt_data());
603 }
604
0a606a2b
TH
605 public function process_autosave(question_attempt_pending_step $pendingstep) {
606 // If already finished. Nothing to do.
607 if ($this->qa->get_state()->is_finished()) {
608 return question_attempt::DISCARD;
609 }
610
611 // If the new data is the same as we already have, then we don't need it.
612 if ($this->is_same_response($pendingstep)) {
613 return question_attempt::DISCARD;
614 }
615
616 // Repeat that test discarding any existing autosaved data.
617 if ($this->qa->has_autosaved_step()) {
618 $this->qa->discard_autosaved_step();
619 if ($this->is_same_response($pendingstep)) {
620 return question_attempt::DISCARD;
621 }
622 }
623
624 // OK, we need to save.
625 return $this->process_save($pendingstep);
626 }
627
d1b7e03d
TH
628 /**
629 * Implementation of processing a save action that should be suitable for
630 * most subclasses.
631 * @param question_attempt_pending_step $pendingstep a partially initialised step
632 * containing all the information about the action that is being peformed.
f7970e3c 633 * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
d1b7e03d
TH
634 */
635 public function process_save(question_attempt_pending_step $pendingstep) {
636 if ($this->qa->get_state()->is_finished()) {
637 return question_attempt::DISCARD;
638 } else if (!$this->qa->get_state()->is_active()) {
88f0eb15 639 throw new coding_exception('Question is not active, cannot process_actions.');
d1b7e03d
TH
640 }
641
642 if ($this->is_same_response($pendingstep)) {
643 return question_attempt::DISCARD;
644 }
645
646 if ($this->is_complete_response($pendingstep)) {
647 $pendingstep->set_state(question_state::$complete);
648 } else {
649 $pendingstep->set_state(question_state::$todo);
650 }
651 return question_attempt::KEEP;
652 }
653
654 public function summarise_submit(question_attempt_step $step) {
655 return get_string('submitted', 'question',
656 $this->question->summarise_response($step->get_qt_data()));
657 }
658
659 public function summarise_save(question_attempt_step $step) {
660 $data = $step->get_submitted_data();
661 if (empty($data)) {
662 return $this->summarise_start($step);
663 }
664 return get_string('saved', 'question',
665 $this->question->summarise_response($step->get_qt_data()));
666 }
667
668
669 public function summarise_finish($step) {
670 $data = $step->get_qt_data();
671 if ($data) {
672 return get_string('attemptfinishedsubmitting', 'question',
673 $this->question->summarise_response($data));
674 }
675 return get_string('attemptfinished', 'question');
676 }
677}
678
99caa248
JP
679abstract class question_behaviour_with_multiple_tries extends question_behaviour_with_save {
680 public function step_has_a_submitted_response($step) {
681 return $step->has_behaviour_var('submit') && $step->get_state() != question_state::$invalid;
682 }
683}
d1b7e03d
TH
684
685/**
686 * This helper class contains the constants and methods required for
c4efeb2b 687 * manipulating scores for certainty based marking.
d1b7e03d 688 *
f7970e3c
TH
689 * @copyright 2009 The Open University
690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
691 */
692abstract class question_cbm {
693 /**#@+ @var integer named constants for the certainty levels. */
694 const LOW = 1;
695 const MED = 2;
696 const HIGH = 3;
697 /**#@-*/
698
699 /** @var array list of all the certainty levels. */
700 public static $certainties = array(self::LOW, self::MED, self::HIGH);
701
fb74929e
TH
702 /**#@+ @var array coefficients used to adjust the fraction based on certainty. */
703 protected static $rightscore = array(
704 self::LOW => 1,
705 self::MED => 2,
d1b7e03d
TH
706 self::HIGH => 3,
707 );
fb74929e
TH
708 protected static $wrongscore = array(
709 self::LOW => 0,
710 self::MED => -2,
711 self::HIGH => -6,
d1b7e03d
TH
712 );
713 /**#@-*/
714
e74aa0aa
TH
715 /**#@+ @var array upper and lower limits of the optimal window. */
716 protected static $lowlimit = array(
717 self::LOW => 0,
718 self::MED => 0.666666666666667,
719 self::HIGH => 0.8,
720 );
721 protected static $highlimit = array(
722 self::LOW => 0.666666666666667,
723 self::MED => 0.8,
724 self::HIGH => 1,
725 );
726 /**#@-*/
727
d1b7e03d 728 /**
f7970e3c 729 * @return int the default certaintly level that should be assuemd if
d1b7e03d
TH
730 * the student does not choose one.
731 */
732 public static function default_certainty() {
733 return self::LOW;
734 }
735
736 /**
c4efeb2b 737 * Given a fraction, and a certainty, compute the adjusted fraction.
d1b7e03d 738 * @param number $fraction the raw fraction for this question.
c4efeb2b
TH
739 * @param int $certainty one of the certainty level constants.
740 * @return number the adjusted fraction taking the certainty into account.
d1b7e03d
TH
741 */
742 public static function adjust_fraction($fraction, $certainty) {
2bf83cb2
TH
743 if ($certainty == -1) {
744 // Certainty -1 has never been used in standard Moodle, but is
745 // used in Tony-Gardiner Medwin's patches to mean 'No idea' which
746 // we intend to implement: MDL-42077. In the mean time, avoid
747 // errors for people who have used TGM's patches.
748 return 0;
749 }
fb74929e
TH
750 if ($fraction <= 0.00000005) {
751 return self::$wrongscore[$certainty];
752 } else {
753 return self::$rightscore[$certainty] * $fraction;
754 }
d1b7e03d
TH
755 }
756
757 /**
f7970e3c 758 * @param int $certainty one of the LOW/MED/HIGH constants.
c4efeb2b 759 * @return string a textual description of this certainty.
d1b7e03d
TH
760 */
761 public static function get_string($certainty) {
762 return get_string('certainty' . $certainty, 'qbehaviour_deferredcbm');
763 }
764
e74aa0aa
TH
765 /**
766 * @param int $certainty one of the LOW/MED/HIGH constants.
767 * @return string a short textual description of this certainty.
768 */
769 public static function get_short_string($certainty) {
770 return get_string('certaintyshort' . $certainty, 'qbehaviour_deferredcbm');
771 }
772
773 /**
774 * Add information about certainty to a response summary.
775 * @param string $summary the response summary.
776 * @param int $certainty the level of certainty to add.
8b9ef25e 777 * @return string the summary with information about the certainty added.
e74aa0aa 778 */
d1b7e03d
TH
779 public static function summary_with_certainty($summary, $certainty) {
780 if (is_null($certainty)) {
781 return $summary;
782 }
8b9ef25e 783 return $summary . ' [' . self::get_short_string($certainty) . ']';
d1b7e03d 784 }
e74aa0aa
TH
785
786 /**
787 * @param int $certainty one of the LOW/MED/HIGH constants.
788 * @return float the lower limit of the optimal probability range for this certainty.
789 */
790 public static function optimal_probablility_low($certainty) {
791 return self::$lowlimit[$certainty];
792 }
793
794 /**
795 * @param int $certainty one of the LOW/MED/HIGH constants.
796 * @return float the upper limit of the optimal probability range for this certainty.
797 */
798 public static function optimal_probablility_high($certainty) {
799 return self::$highlimit[$certainty];
800 }
d1b7e03d 801}