MDL-20636 Current work-in-progress converting the question engine to Moodle 2.0
[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() {
129 return renderer_factory::get_renderer(get_class($this));
130 }
131
132 /**
133 * Make any changes to the display options before a question is rendered, so
134 * that it can be displayed in a way that is appropriate for the statue it is
135 * currently in. For example, by default, if the question is finished, we
136 * ensure that it is only ever displayed read-only.
137 * @param question_display_options $options the options to adjust. Just change
138 * the properties of this object - objects are passed by referece.
139 */
140 public function adjust_display_options(question_display_options $options) {
141 if (!$this->qa->has_marks()) {
142 $options->correctness = false;
143 $options->numpartscorrect = false;
144 }
145 if ($this->qa->get_state()->is_finished()) {
146 $options->readonly = true;
147 $options->numpartscorrect = $options->numpartscorrect &&
148 $this->qa->get_state()->is_partially_correct() &&
149 !empty($this->question->shownumcorrect);
150 } else {
151 $options->hide_all_feedback();
152 }
153 }
154
155 /**
156 * Get the most applicable hint for the question in its current state.
157 * @return question_hint the most applicable hint, or null, if none.
158 */
159 public function get_applicable_hint() {
160 return null;
161 }
162
163 /**
164 * What is the minimum fraction that can be scored for this question.
165 * Normally this will be based on $this->question->init_first_step($step),
166 * but may be modified in some way by the model.
167 *
168 * @return number the minimum fraction when this question is attempted under
169 * this model.
170 */
171 public function get_min_fraction() {
172 return 0;
173 }
174
175 /**
176 * Adjust a random guess score for a question using this model. You have to
177 * do this without knowing details of the specific question, or which usage
178 * it is in.
179 * @param number $fraction the random guess score from the question type.
180 * @return number the adjusted fraction.
181 */
182 public static function adjust_random_guess_score($fraction) {
183 return $fraction;
184 }
185
186 /**
187 * Return an array of the behaviour variables that could be submitted
188 * as part of a question of this type, with their types, so they can be
189 * properly cleaned.
190 * @return array variable name => PARAM_... constant.
191 */
192 public function get_expected_data() {
193 if (!$this->qa->get_state()->is_finished()) {
194 return array();
195 }
196
197 $vars = array('comment' => PARAM_RAW);
198 if ($this->qa->get_max_mark()) {
199 $vars['mark'] = question_attempt::PARAM_MARK;
200 $vars['maxmark'] = PARAM_NUMBER;
201 }
202 return $vars;
203 }
204
205 /**
206 * Return an array of question type variables for the question in its current
207 * state. Normally, if {@link adjust_display_options()} would set
208 * {@link question_display_options::$readonly} to true, then this method
209 * should return an empty array, otherwise it should return
210 * $this->question->get_expected_data(). Thus, there should be little need to
211 * override this method.
212 * @return array|string variable name => PARAM_... constant, or, as a special case
213 * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
214 * meaning take all the raw submitted data belonging to this question.
215 */
216 public function get_expected_qt_data() {
217 $fakeoptions = new question_display_options();
218 $fakeoptions->readonly = false;
219 $this->adjust_display_options($fakeoptions);
220 if ($fakeoptions->readonly) {
221 return array();
222 } else {
223 return $this->question->get_expected_data();
224 }
225 }
226
227 /**
228 * Return an array of any im variables, and the value required to get full
229 * marks.
230 * @return array variable name => value.
231 */
232 public function get_correct_response() {
233 return array();
234 }
235
236 /**
237 * Generate a brief, plain-text, summary of this question. This is used by
238 * various reports. This should show the particular variant of the question
239 * as presented to students. For example, the calculated quetsion type would
240 * fill in the particular numbers that were presented to the student.
241 * This method will return null if such a summary is not possible, or
242 * inappropriate.
243 *
244 * Normally, this method delegates to {question_definition::get_question_summary()}.
245 *
246 * @return string|null a plain text summary of this question.
247 */
248 public function get_question_summary() {
249 return $this->question->get_question_summary();
250 }
251
252 /**
253 * Generate a brief, plain-text, summary of the correct answer to this question.
254 * This is used by various reports, and can also be useful when testing.
255 * This method will return null if such a summary is not possible, or
256 * inappropriate.
257 *
258 * @return string|null a plain text summary of the right answer to this question.
259 */
260 public function get_right_answer_summary() {
261 return null;
262 }
263
264 /**
265 * Used by {@link start_based_on()} to get the data needed to start a new
266 * attempt from the point this attempt has go to.
267 * @return array name => value pairs.
268 */
269 public function get_resume_data() {
270 $olddata = $this->qa->get_step(0)->get_all_data();
271 $olddata = $this->qa->get_last_qt_data() + $olddata;
272 $olddata = $this->get_our_resume_data() + $olddata;
273 return $olddata;
274 }
275
276 /**
277 * Used by {@link start_based_on()} to get the data needed to start a new
278 * attempt from the point this attempt has go to.
279 * @return unknown_type
280 */
281 protected function get_our_resume_data() {
282 return array();
283 }
284
285 /**
286 * @return array subpartid => object with fields
287 * ->responseclassid the
288 * ->response the actual response the student gave to this part, as a string.
289 * ->fraction the credit awarded for this subpart, may be null.
290 * returns an empty array if no analysis is possible.
291 */
292 public function classify_response() {
293 return $this->question->classify_response($this->qa->get_last_qt_data());
294 }
295
296 /**
297 * Generate a brief textual description of the current state of the question,
298 * normally displayed under the question number.
299 *
300 * @param boolean $showcorrectness Whether right/partial/wrong states should
301 * be distinguised.
302 * @return string a brief summary of the current state of the qestion attempt.
303 */
304 public function get_state_string($showcorrectness) {
305 return $this->qa->get_state()->default_string($showcorrectness);
306 }
307
308 abstract public function summarise_action(question_attempt_step $step);
309
310 /**
311 * Initialise the first step in a question attempt.
312 *
313 * This method must call $this->question->init_first_step($step), and may
314 * perform additional processing if the model requries it.
315 *
316 * @param question_attempt_step $step the step being initialised.
317 */
318 public function init_first_step(question_attempt_step $step) {
319 $this->question->init_first_step($step);
320 }
321
322 /**
323 * Checks whether two manual grading actions are the same. That is, whether
324 * the comment, and the mark (if given) is the same.
325 *
326 * @param question_attempt_step $pendingstep contains the new responses.
327 * @return boolean whether the new response is the same as we already have.
328 */
329 protected function is_same_comment($pendingstep) {
330 $previouscomment = $this->qa->get_last_behaviour_var('comment');
331 $newcomment = $pendingstep->get_behaviour_var('comment');
332
333 if (is_null($previouscomment) && !html_is_blank($newcomment) ||
334 $previouscomment != $newcomment) {
335 return false;
336 }
337
338 // So, now we know the comment is the same, so check the mark, if present.
339 $previousfraction = $this->qa->get_fraction();
340 $newmark = $pendingstep->get_behaviour_var('mark');
341
342 if (is_null($previousfraction)) {
343 return is_null($newmark) || $newmark === '';
344 } else if (is_null($newmark) || $newmark === '') {
345 return false;
346 }
347
348 $newfraction = $newmark / $pendingstep->get_behaviour_var('maxmark');
349
350 return abs($newfraction - $previousfraction) < 0.0000001;
351 }
352
353 /**
354 * The main entry point for processing an action.
355 *
356 * All the various operations that can be performed on a
357 * {@link question_attempt} get channeled through this function, except for
358 * {@link question_attempt::start()} which goes to {@link init_first_step()}.
359 * {@link question_attempt::finish()} becomes an action with im vars
360 * finish => 1, and manual comment/grade becomes an action with im vars
361 * comment => comment text, and mark => ..., max_mark => ... if the question
362 * is graded.
363 *
364 * This method should first determine whether the action is significant. For
365 * example, if no actual action is being performed, but instead the current
366 * responses are being saved, and there has been no change since the last
367 * set of responses that were saved, this the action is not significatn. In
368 * this case, this method should return {@link question_attempt::DISCARD}.
369 * Otherwise it should return {@link question_attempt::KEEP}.
370 *
371 * If the action is significant, this method should also perform any
372 * necessary updates to $pendingstep. For example, it should call
373 * {@link question_attempt_step::set_state()} to set the state that results
374 * from this action, and if this is a grading action, it should call
375 * {@link question_attempt_step::set_fraction()}.
376 *
377 * This method can also call {@link question_attempt_step::set_behaviour_var()} to
378 * store additional infomation. There are two main uses for this. This can
379 * be used to store the result of any randomisation done. It is important to
380 * store the result of randomisation once, and then in future use the same
381 * outcome if the actions are ever replayed. This is how regrading works.
382 * The other use is to cache the result of expensive computations performed
383 * on the raw response data, so that subsequent display and review of the
384 * question does not have to repeat the same expensive computations.
385 *
386 * Often this method is implemented as a dispatching method that examines
387 * the pending step to determine the kind of action being performed, and
388 * then calls a more specific method like {@link process_save()} or
389 * {@link process_comment()}. Look at some of the standard behaviours
390 * for examples.
391 *
392 * @param question_attempt_pending_step $pendingstep a partially initialised step
393 * containing all the information about the action that is being peformed.
394 * This information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
395 * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
396 */
397 public abstract function process_action(question_attempt_pending_step $pendingstep);
398
399 /**
400 * Implementation of processing a manual comment/grade action that should
401 * be suitable for most subclasses.
402 * @param question_attempt_pending_step $pendingstep a partially initialised step
403 * containing all the information about the action that is being peformed.
404 * @return boolean either {@link question_attempt::KEEP}
405 */
406 public function process_comment(question_attempt_pending_step $pendingstep) {
407 if (!$this->qa->get_state()->is_finished()) {
408 throw new coding_exception('Cannot manually grade a question before it is finshed.');
409 }
410
411 if ($this->is_same_comment($pendingstep)) {
412 return question_attempt::DISCARD;
413 }
414
415 if ($pendingstep->has_behaviour_var('mark')) {
416 $fraction = $pendingstep->get_behaviour_var('mark') / $pendingstep->get_behaviour_var('maxmark');
417 if ($pendingstep->get_behaviour_var('mark') === '') {
418 $fraction = null;
419 } else if ($fraction > 1 || $fraction < $this->qa->get_min_fraction()) {
420 throw new coding_exception('Score out of range when processing ' .
421 'a manual grading action.', $pendingstep);
422 }
423 $pendingstep->set_fraction($fraction);
424 }
425
426 $pendingstep->set_state($this->qa->get_state()->
427 corresponding_commented_state($pendingstep->get_fraction()));
428 return question_attempt::KEEP;
429 }
430
431 /**
432 * @param $comment the comment text to format. If omitted,
433 * $this->qa->get_manual_comment() is used.
434 * @return string the comment, ready to be output.
435 */
436 public function format_comment($comment = null) {
437 $formatoptions = new stdClass;
438 $formatoptions->noclean = true;
439 $formatoptions->para = false;
440
441 if (is_null($comment)) {
442 $comment = $this->qa->get_manual_comment();
443 }
444
445 return format_text($comment, FORMAT_HTML, $formatoptions);
446 }
447
448 /**
449 * @return string a summary of a manual comment action.
450 * @param unknown_type $step
451 */
452 protected function summarise_manual_comment($step) {
453 $a = new stdClass;
454 if ($step->has_behaviour_var('comment')) {
455 $a->comment = shorten_text(html_to_text($this->format_comment(
456 $step->get_behaviour_var('comment')), 0, false), 200);
457 } else {
458 $a->comment = '';
459 }
460
461 $mark = $step->get_behaviour_var('mark');
462 if (is_null($mark) || $mark === '') {
463 return get_string('commented', 'question', $a->comment);
464 } else {
465 $a->mark = $mark / $step->get_behaviour_var('maxmark') * $this->qa->get_max_mark();
466 return get_string('manuallygraded', 'question', $a);
467 }
468 }
469
470 public function summarise_start($step) {
471 return get_string('started', 'question');
472 }
473
474 public function summarise_finish($step) {
475 return get_string('attemptfinished', 'question');
476 }
477}
478
479
480/**
481 * A subclass of {@link question_behaviour} that implements a save
482 * action that is suitable for most questions that implement the
483 * {@link question_manually_gradable} interface.
484 *
485 * @copyright 2009 The Open University
486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
487 */
488abstract class question_behaviour_with_save extends question_behaviour {
489 public function required_question_definition_type() {
490 return 'question_manually_gradable';
491 }
492
493 /**
494 * Work out whether the response in $pendingstep are significantly different
495 * from the last set of responses we have stored.
496 * @param question_attempt_step $pendingstep contains the new responses.
497 * @return boolean whether the new response is the same as we already have.
498 */
499 protected function is_same_response(question_attempt_step $pendingstep) {
500 return $this->question->is_same_response(
501 $this->qa->get_last_step()->get_qt_data(), $pendingstep->get_qt_data());
502 }
503
504 /**
505 * Work out whether the response in $pendingstep represent a complete answer
506 * to the question. Normally this will call
507 * {@link question_manually_gradable::is_complete_response}, but some
508 * behaviours, for example the CBM ones, have their own parts to the
509 * response.
510 * @param question_attempt_step $pendingstep contains the new responses.
511 * @return boolean whether the new response is complete.
512 */
513 protected function is_complete_response(question_attempt_step $pendingstep) {
514 return $this->question->is_complete_response($pendingstep->get_qt_data());
515 }
516
517 /**
518 * Implementation of processing a save action that should be suitable for
519 * most subclasses.
520 * @param question_attempt_pending_step $pendingstep a partially initialised step
521 * containing all the information about the action that is being peformed.
522 * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
523 */
524 public function process_save(question_attempt_pending_step $pendingstep) {
525 if ($this->qa->get_state()->is_finished()) {
526 return question_attempt::DISCARD;
527 } else if (!$this->qa->get_state()->is_active()) {
528 throw new Exception('Question is not active, cannot process_actions.');
529 }
530
531 if ($this->is_same_response($pendingstep)) {
532 return question_attempt::DISCARD;
533 }
534
535 if ($this->is_complete_response($pendingstep)) {
536 $pendingstep->set_state(question_state::$complete);
537 } else {
538 $pendingstep->set_state(question_state::$todo);
539 }
540 return question_attempt::KEEP;
541 }
542
543 public function summarise_submit(question_attempt_step $step) {
544 return get_string('submitted', 'question',
545 $this->question->summarise_response($step->get_qt_data()));
546 }
547
548 public function summarise_save(question_attempt_step $step) {
549 $data = $step->get_submitted_data();
550 if (empty($data)) {
551 return $this->summarise_start($step);
552 }
553 return get_string('saved', 'question',
554 $this->question->summarise_response($step->get_qt_data()));
555 }
556
557
558 public function summarise_finish($step) {
559 $data = $step->get_qt_data();
560 if ($data) {
561 return get_string('attemptfinishedsubmitting', 'question',
562 $this->question->summarise_response($data));
563 }
564 return get_string('attemptfinished', 'question');
565 }
566}
567
568
569/**
570 * This helper class contains the constants and methods required for
571 * manipulating scores for certainly based marking.
572 *
573 * @copyright 2009 The Open University
574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
575 */
576abstract class question_cbm {
577 /**#@+ @var integer named constants for the certainty levels. */
578 const LOW = 1;
579 const MED = 2;
580 const HIGH = 3;
581 /**#@-*/
582
583 /** @var array list of all the certainty levels. */
584 public static $certainties = array(self::LOW, self::MED, self::HIGH);
585
586 /**#@+ @var array coefficients used to adjust the fraction based on certainty.. */
587 protected static $factor = array(
588 self::LOW => 0.333333333333333,
589 self::MED => 1.333333333333333,
590 self::HIGH => 3,
591 );
592 protected static $offset = array(
593 self::LOW => 0,
594 self::MED => -0.666666666666667,
595 self::HIGH => -2,
596 );
597 /**#@-*/
598
599 /**
600 * @return integer the default certaintly level that should be assuemd if
601 * the student does not choose one.
602 */
603 public static function default_certainty() {
604 return self::LOW;
605 }
606
607 /**
608 * Given a fraction, and a certainly, compute the adjusted fraction.
609 * @param number $fraction the raw fraction for this question.
610 * @param integer $certainty one of the certainly level constants.
611 * @return number the adjusted fraction taking the certainly into account.
612 */
613 public static function adjust_fraction($fraction, $certainty) {
614 return self::$offset[$certainty] + self::$factor[$certainty] * $fraction;
615 }
616
617 /**
618 * @param integer $certainty one of the LOW/MED/HIGH constants.
619 * @return string a textual desciption of this certainly.
620 */
621 public static function get_string($certainty) {
622 return get_string('certainty' . $certainty, 'qbehaviour_deferredcbm');
623 }
624
625 public static function summary_with_certainty($summary, $certainty) {
626 if (is_null($certainty)) {
627 return $summary;
628 }
629 return $summary . ' [' . self::get_string($certainty) . ']';
630 }
631}