MDL-20636 Previewing a truefalse question in deferred feedback mode now works.
[moodle.git] / question / behaviour / behaviourbase.php
CommitLineData
d1b7e03d
TH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18
19/**
20 * Defines the quetsion behaviour base class
21 *
22 * @package moodlecore
23 * @subpackage questionbehaviours
24 * @copyright 2009 The Open University
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28
29/**
30 * The base class for question behaviours.
31 *
32 * A question behaviour is used by the question engine, specifically by
33 * a {@link question_attempt} to manage the flow of actions a student can take
34 * as they work through a question, and later, as a teacher manually grades it.
35 * In turn, the behaviour will delegate certain processing to the
36 * relevant {@link question_definition}.
37 *
38 * @copyright 2009 The Open University
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 */
41abstract class question_behaviour {
42 /**
43 * Certain behaviours are definitive of a way that questions can
44 * behave when attempted. For example deferredfeedback model, interactive
45 * model, etc. These are the options that should be listed in the
46 * user-interface. These models should define the class constant
47 * IS_ARCHETYPAL as true. Other models are more implementation details, for
48 * example the informationitem model, or a special subclass like
49 * interactive_adapted_for_my_qtype. These models should IS_ARCHETYPAL as
50 * false.
51 * @var boolean
52 */
53 const IS_ARCHETYPAL = false;
54
55 /** @var question_attempt the question attempt we are managing. */
56 protected $qa;
57 /** @var question_definition shortcut to $qa->get_question(). */
58 protected $question;
59
60 /**
61 * Normally you should not call this constuctor directly. The appropriate
62 * behaviour object is created automatically as part of
63 * {@link question_attempt::start()}.
64 * @param question_attempt $qa the question attempt we will be managing.
65 * @param string $preferredbehaviour the type of behaviour that was actually
66 * requested. This information is not needed in most cases, the type of
67 * subclass is enough, but occasionally it is needed.
68 */
69 public function __construct(question_attempt $qa, $preferredbehaviour) {
70 $this->qa = $qa;
71 $this->question = $qa->get_question();
72 $requiredclass = $this->required_question_definition_type();
73 if (!$this->question instanceof $requiredclass) {
74 throw new Exception('This behaviour (' . $this->get_name() .
75 ') cannot work with this question (' . get_class($this->question) . ')');
76 }
77 }
78
79 /**
80 * Most behaviours can only work with {@link question_definition}s
81 * of a particular subtype, or that implement a particular interface.
82 * This method lets the behaviour document that. The type of
83 * question passed to the constructor is then checked against this type.
84 * @return string class/interface name.
85 */
86 public abstract function required_question_definition_type();
87
88 /**
89 * @return string the name of this behaviour. For example the name of
90 * qbehaviour_mymodle is 'mymodel'.
91 */
92 public function get_name() {
93 return substr(get_class($this), 11);
94 }
95
96 /**
97 * 'Override' this method if there are some display options that do not make
98 * sense 'during the attempt'.
99 * @return array of {@link question_display_options} field names, that are
100 * not relevant to this behaviour before a 'finish' action.
101 */
102 public static function get_unused_display_options() {
103 return array();
104 }
105
106 /**
107 * Cause the question to be renderered. This gets the appropriate behaviour
108 * renderer using {@link get_renderer()}, and adjusts the display
109 * options using {@link adjust_display_options()} and then calls
110 * {@link core_question_renderer::question()} to do the work.
111 * @param question_display_options $options controls what should and should not be displayed.
112 * @param unknown_type $number the question number to display.
113 * @param core_question_renderer $qoutput the question renderer that will coordinate everything.
114 * @param qtype_renderer $qtoutput the question type renderer that will be helping.
115 * @return HTML fragment.
116 */
117 public function render(question_display_options $options, $number,
118 core_question_renderer $qoutput, qtype_renderer $qtoutput) {
119 $behaviouroutput = $this->get_renderer();
120 $options = clone($options);
121 $this->adjust_display_options($options);
122 return $qoutput->question($this->qa, $behaviouroutput, $qtoutput, $options, $number);
123 }
124
125 /**
126 * @return qbehaviour_renderer get the appropriate renderer to use for this model.
127 */
128 public function get_renderer() {
c76145d3
TH
129 global $PAGE;
130 return $PAGE->get_renderer(get_class($this));
d1b7e03d
TH
131 }
132
133 /**
134 * Make any changes to the display options before a question is rendered, so
135 * that it can be displayed in a way that is appropriate for the statue it is
136 * currently in. For example, by default, if the question is finished, we
137 * ensure that it is only ever displayed read-only.
138 * @param question_display_options $options the options to adjust. Just change
139 * the properties of this object - objects are passed by referece.
140 */
141 public function adjust_display_options(question_display_options $options) {
142 if (!$this->qa->has_marks()) {
143 $options->correctness = false;
144 $options->numpartscorrect = false;
145 }
146 if ($this->qa->get_state()->is_finished()) {
147 $options->readonly = true;
148 $options->numpartscorrect = $options->numpartscorrect &&
149 $this->qa->get_state()->is_partially_correct() &&
150 !empty($this->question->shownumcorrect);
151 } else {
152 $options->hide_all_feedback();
153 }
154 }
155
156 /**
157 * Get the most applicable hint for the question in its current state.
158 * @return question_hint the most applicable hint, or null, if none.
159 */
160 public function get_applicable_hint() {
161 return null;
162 }
163
164 /**
165 * What is the minimum fraction that can be scored for this question.
166 * Normally this will be based on $this->question->init_first_step($step),
167 * but may be modified in some way by the model.
168 *
169 * @return number the minimum fraction when this question is attempted under
170 * this model.
171 */
172 public function get_min_fraction() {
173 return 0;
174 }
175
176 /**
177 * Adjust a random guess score for a question using this model. You have to
178 * do this without knowing details of the specific question, or which usage
179 * it is in.
180 * @param number $fraction the random guess score from the question type.
181 * @return number the adjusted fraction.
182 */
183 public static function adjust_random_guess_score($fraction) {
184 return $fraction;
185 }
186
187 /**
188 * Return an array of the behaviour variables that could be submitted
189 * as part of a question of this type, with their types, so they can be
190 * properly cleaned.
191 * @return array variable name => PARAM_... constant.
192 */
193 public function get_expected_data() {
194 if (!$this->qa->get_state()->is_finished()) {
195 return array();
196 }
197
198 $vars = array('comment' => PARAM_RAW);
199 if ($this->qa->get_max_mark()) {
200 $vars['mark'] = question_attempt::PARAM_MARK;
201 $vars['maxmark'] = PARAM_NUMBER;
202 }
203 return $vars;
204 }
205
206 /**
207 * Return an array of question type variables for the question in its current
208 * state. Normally, if {@link adjust_display_options()} would set
209 * {@link question_display_options::$readonly} to true, then this method
210 * should return an empty array, otherwise it should return
211 * $this->question->get_expected_data(). Thus, there should be little need to
212 * override this method.
213 * @return array|string variable name => PARAM_... constant, or, as a special case
214 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
215 * meaning take all the raw submitted data belonging to this question.
216 */
217 public function get_expected_qt_data() {
218 $fakeoptions = new question_display_options();
219 $fakeoptions->readonly = false;
220 $this->adjust_display_options($fakeoptions);
221 if ($fakeoptions->readonly) {
222 return array();
223 } else {
224 return $this->question->get_expected_data();
225 }
226 }
227
228 /**
229 * Return an array of any im variables, and the value required to get full
230 * marks.
231 * @return array variable name => value.
232 */
233 public function get_correct_response() {
234 return array();
235 }
236
237 /**
238 * Generate a brief, plain-text, summary of this question. This is used by
239 * various reports. This should show the particular variant of the question
240 * as presented to students. For example, the calculated quetsion type would
241 * fill in the particular numbers that were presented to the student.
242 * This method will return null if such a summary is not possible, or
243 * inappropriate.
244 *
245 * Normally, this method delegates to {question_definition::get_question_summary()}.
246 *
247 * @return string|null a plain text summary of this question.
248 */
249 public function get_question_summary() {
2b7da645 250 return $this->question->get_question_summary($this->qa);
d1b7e03d
TH
251 }
252
253 /**
254 * Generate a brief, plain-text, summary of the correct answer to this question.
255 * This is used by various reports, and can also be useful when testing.
256 * This method will return null if such a summary is not possible, or
257 * inappropriate.
258 *
259 * @return string|null a plain text summary of the right answer to this question.
260 */
261 public function get_right_answer_summary() {
262 return null;
263 }
264
265 /**
266 * Used by {@link start_based_on()} to get the data needed to start a new
267 * attempt from the point this attempt has go to.
268 * @return array name => value pairs.
269 */
270 public function get_resume_data() {
271 $olddata = $this->qa->get_step(0)->get_all_data();
272 $olddata = $this->qa->get_last_qt_data() + $olddata;
273 $olddata = $this->get_our_resume_data() + $olddata;
274 return $olddata;
275 }
276
277 /**
278 * Used by {@link start_based_on()} to get the data needed to start a new
279 * attempt from the point this attempt has go to.
280 * @return unknown_type
281 */
282 protected function get_our_resume_data() {
283 return array();
284 }
285
286 /**
287 * @return array subpartid => object with fields
288 * ->responseclassid the
289 * ->response the actual response the student gave to this part, as a string.
290 * ->fraction the credit awarded for this subpart, may be null.
291 * returns an empty array if no analysis is possible.
292 */
293 public function classify_response() {
294 return $this->question->classify_response($this->qa->get_last_qt_data());
295 }
296
297 /**
298 * Generate a brief textual description of the current state of the question,
299 * normally displayed under the question number.
300 *
301 * @param boolean $showcorrectness Whether right/partial/wrong states should
302 * be distinguised.
303 * @return string a brief summary of the current state of the qestion attempt.
304 */
305 public function get_state_string($showcorrectness) {
306 return $this->qa->get_state()->default_string($showcorrectness);
307 }
308
309 abstract public function summarise_action(question_attempt_step $step);
310
311 /**
312 * Initialise the first step in a question attempt.
313 *
314 * This method must call $this->question->init_first_step($step), and may
315 * perform additional processing if the model requries it.
316 *
317 * @param question_attempt_step $step the step being initialised.
318 */
319 public function init_first_step(question_attempt_step $step) {
320 $this->question->init_first_step($step);
321 }
322
323 /**
324 * Checks whether two manual grading actions are the same. That is, whether
325 * the comment, and the mark (if given) is the same.
326 *
327 * @param question_attempt_step $pendingstep contains the new responses.
328 * @return boolean whether the new response is the same as we already have.
329 */
330 protected function is_same_comment($pendingstep) {
331 $previouscomment = $this->qa->get_last_behaviour_var('comment');
332 $newcomment = $pendingstep->get_behaviour_var('comment');
333
334 if (is_null($previouscomment) && !html_is_blank($newcomment) ||
335 $previouscomment != $newcomment) {
336 return false;
337 }
338
339 // So, now we know the comment is the same, so check the mark, if present.
340 $previousfraction = $this->qa->get_fraction();
341 $newmark = $pendingstep->get_behaviour_var('mark');
342
343 if (is_null($previousfraction)) {
344 return is_null($newmark) || $newmark === '';
345 } else if (is_null($newmark) || $newmark === '') {
346 return false;
347 }
348
349 $newfraction = $newmark / $pendingstep->get_behaviour_var('maxmark');
350
351 return abs($newfraction - $previousfraction) < 0.0000001;
352 }
353
354 /**
355 * The main entry point for processing an action.
356 *
357 * All the various operations that can be performed on a
358 * {@link question_attempt} get channeled through this function, except for
359 * {@link question_attempt::start()} which goes to {@link init_first_step()}.
360 * {@link question_attempt::finish()} becomes an action with im vars
361 * finish => 1, and manual comment/grade becomes an action with im vars
362 * comment => comment text, and mark => ..., max_mark => ... if the question
363 * is graded.
364 *
365 * This method should first determine whether the action is significant. For
366 * example, if no actual action is being performed, but instead the current
367 * responses are being saved, and there has been no change since the last
368 * set of responses that were saved, this the action is not significatn. In
369 * this case, this method should return {@link question_attempt::DISCARD}.
370 * Otherwise it should return {@link question_attempt::KEEP}.
371 *
372 * If the action is significant, this method should also perform any
373 * necessary updates to $pendingstep. For example, it should call
374 * {@link question_attempt_step::set_state()} to set the state that results
375 * from this action, and if this is a grading action, it should call
376 * {@link question_attempt_step::set_fraction()}.
377 *
378 * This method can also call {@link question_attempt_step::set_behaviour_var()} to
379 * store additional infomation. There are two main uses for this. This can
380 * be used to store the result of any randomisation done. It is important to
381 * store the result of randomisation once, and then in future use the same
382 * outcome if the actions are ever replayed. This is how regrading works.
383 * The other use is to cache the result of expensive computations performed
384 * on the raw response data, so that subsequent display and review of the
385 * question does not have to repeat the same expensive computations.
386 *
387 * Often this method is implemented as a dispatching method that examines
388 * the pending step to determine the kind of action being performed, and
389 * then calls a more specific method like {@link process_save()} or
390 * {@link process_comment()}. Look at some of the standard behaviours
391 * for examples.
392 *
393 * @param question_attempt_pending_step $pendingstep a partially initialised step
394 * containing all the information about the action that is being peformed.
395 * This information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
396 * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
397 */
398 public abstract function process_action(question_attempt_pending_step $pendingstep);
399
400 /**
401 * Implementation of processing a manual comment/grade action that should
402 * be suitable for most subclasses.
403 * @param question_attempt_pending_step $pendingstep a partially initialised step
404 * containing all the information about the action that is being peformed.
405 * @return boolean either {@link question_attempt::KEEP}
406 */
407 public function process_comment(question_attempt_pending_step $pendingstep) {
408 if (!$this->qa->get_state()->is_finished()) {
409 throw new coding_exception('Cannot manually grade a question before it is finshed.');
410 }
411
412 if ($this->is_same_comment($pendingstep)) {
413 return question_attempt::DISCARD;
414 }
415
416 if ($pendingstep->has_behaviour_var('mark')) {
417 $fraction = $pendingstep->get_behaviour_var('mark') / $pendingstep->get_behaviour_var('maxmark');
418 if ($pendingstep->get_behaviour_var('mark') === '') {
419 $fraction = null;
420 } else if ($fraction > 1 || $fraction < $this->qa->get_min_fraction()) {
421 throw new coding_exception('Score out of range when processing ' .
422 'a manual grading action.', $pendingstep);
423 }
424 $pendingstep->set_fraction($fraction);
425 }
426
427 $pendingstep->set_state($this->qa->get_state()->
428 corresponding_commented_state($pendingstep->get_fraction()));
429 return question_attempt::KEEP;
430 }
431
432 /**
433 * @param $comment the comment text to format. If omitted,
434 * $this->qa->get_manual_comment() is used.
435 * @return string the comment, ready to be output.
436 */
437 public function format_comment($comment = null) {
438 $formatoptions = new stdClass;
439 $formatoptions->noclean = true;
440 $formatoptions->para = false;
441
442 if (is_null($comment)) {
443 $comment = $this->qa->get_manual_comment();
444 }
445
446 return format_text($comment, FORMAT_HTML, $formatoptions);
447 }
448
449 /**
450 * @return string a summary of a manual comment action.
451 * @param unknown_type $step
452 */
453 protected function summarise_manual_comment($step) {
454 $a = new stdClass;
455 if ($step->has_behaviour_var('comment')) {
456 $a->comment = shorten_text(html_to_text($this->format_comment(
457 $step->get_behaviour_var('comment')), 0, false), 200);
458 } else {
459 $a->comment = '';
460 }
461
462 $mark = $step->get_behaviour_var('mark');
463 if (is_null($mark) || $mark === '') {
464 return get_string('commented', 'question', $a->comment);
465 } else {
466 $a->mark = $mark / $step->get_behaviour_var('maxmark') * $this->qa->get_max_mark();
467 return get_string('manuallygraded', 'question', $a);
468 }
469 }
470
471 public function summarise_start($step) {
472 return get_string('started', 'question');
473 }
474
475 public function summarise_finish($step) {
476 return get_string('attemptfinished', 'question');
477 }
478}
479
480
481/**
482 * A subclass of {@link question_behaviour} that implements a save
483 * action that is suitable for most questions that implement the
484 * {@link question_manually_gradable} interface.
485 *
486 * @copyright 2009 The Open University
487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
488 */
489abstract class question_behaviour_with_save extends question_behaviour {
490 public function required_question_definition_type() {
491 return 'question_manually_gradable';
492 }
493
494 /**
495 * Work out whether the response in $pendingstep are significantly different
496 * from the last set of responses we have stored.
497 * @param question_attempt_step $pendingstep contains the new responses.
498 * @return boolean whether the new response is the same as we already have.
499 */
500 protected function is_same_response(question_attempt_step $pendingstep) {
501 return $this->question->is_same_response(
502 $this->qa->get_last_step()->get_qt_data(), $pendingstep->get_qt_data());
503 }
504
505 /**
506 * Work out whether the response in $pendingstep represent a complete answer
507 * to the question. Normally this will call
508 * {@link question_manually_gradable::is_complete_response}, but some
509 * behaviours, for example the CBM ones, have their own parts to the
510 * response.
511 * @param question_attempt_step $pendingstep contains the new responses.
512 * @return boolean whether the new response is complete.
513 */
514 protected function is_complete_response(question_attempt_step $pendingstep) {
515 return $this->question->is_complete_response($pendingstep->get_qt_data());
516 }
517
518 /**
519 * Implementation of processing a save action that should be suitable for
520 * most subclasses.
521 * @param question_attempt_pending_step $pendingstep a partially initialised step
522 * containing all the information about the action that is being peformed.
523 * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
524 */
525 public function process_save(question_attempt_pending_step $pendingstep) {
526 if ($this->qa->get_state()->is_finished()) {
527 return question_attempt::DISCARD;
528 } else if (!$this->qa->get_state()->is_active()) {
529 throw new Exception('Question is not active, cannot process_actions.');
530 }
531
532 if ($this->is_same_response($pendingstep)) {
533 return question_attempt::DISCARD;
534 }
535
536 if ($this->is_complete_response($pendingstep)) {
537 $pendingstep->set_state(question_state::$complete);
538 } else {
539 $pendingstep->set_state(question_state::$todo);
540 }
541 return question_attempt::KEEP;
542 }
543
544 public function summarise_submit(question_attempt_step $step) {
545 return get_string('submitted', 'question',
546 $this->question->summarise_response($step->get_qt_data()));
547 }
548
549 public function summarise_save(question_attempt_step $step) {
550 $data = $step->get_submitted_data();
551 if (empty($data)) {
552 return $this->summarise_start($step);
553 }
554 return get_string('saved', 'question',
555 $this->question->summarise_response($step->get_qt_data()));
556 }
557
558
559 public function summarise_finish($step) {
560 $data = $step->get_qt_data();
561 if ($data) {
562 return get_string('attemptfinishedsubmitting', 'question',
563 $this->question->summarise_response($data));
564 }
565 return get_string('attemptfinished', 'question');
566 }
567}
568
569
570/**
571 * This helper class contains the constants and methods required for
572 * manipulating scores for certainly based marking.
573 *
574 * @copyright 2009 The Open University
575 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
576 */
577abstract class question_cbm {
578 /**#@+ @var integer named constants for the certainty levels. */
579 const LOW = 1;
580 const MED = 2;
581 const HIGH = 3;
582 /**#@-*/
583
584 /** @var array list of all the certainty levels. */
585 public static $certainties = array(self::LOW, self::MED, self::HIGH);
586
587 /**#@+ @var array coefficients used to adjust the fraction based on certainty.. */
588 protected static $factor = array(
589 self::LOW => 0.333333333333333,
590 self::MED => 1.333333333333333,
591 self::HIGH => 3,
592 );
593 protected static $offset = array(
594 self::LOW => 0,
595 self::MED => -0.666666666666667,
596 self::HIGH => -2,
597 );
598 /**#@-*/
599
600 /**
601 * @return integer the default certaintly level that should be assuemd if
602 * the student does not choose one.
603 */
604 public static function default_certainty() {
605 return self::LOW;
606 }
607
608 /**
609 * Given a fraction, and a certainly, compute the adjusted fraction.
610 * @param number $fraction the raw fraction for this question.
611 * @param integer $certainty one of the certainly level constants.
612 * @return number the adjusted fraction taking the certainly into account.
613 */
614 public static function adjust_fraction($fraction, $certainty) {
615 return self::$offset[$certainty] + self::$factor[$certainty] * $fraction;
616 }
617
618 /**
619 * @param integer $certainty one of the LOW/MED/HIGH constants.
620 * @return string a textual desciption of this certainly.
621 */
622 public static function get_string($certainty) {
623 return get_string('certainty' . $certainty, 'qbehaviour_deferredcbm');
624 }
625
626 public static function summary_with_certainty($summary, $certainty) {
627 if (is_null($certainty)) {
628 return $summary;
629 }
630 return $summary . ' [' . self::get_string($certainty) . ']';
631 }
632}