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