MDL-32188 quiz/question: behaviours can add to the review summary.
[moodle.git] / question / engine / questionattemptstep.php
CommitLineData
dcd03928 1<?php
dcd03928
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
17/**
18 * This file defines the question attempt step class, and a few related classes.
19 *
20 * @package moodlecore
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26
27defined('MOODLE_INTERNAL') || die();
28
29
30/**
31 * Stores one step in a {@link question_attempt}.
32 *
33 * The most important attributes of a step are the state, which is one of the
34 * {@link question_state} constants, the fraction, which may be null, or a
35 * number bewteen the attempt's minfraction and 1.0, and the array of submitted
36 * data, about which more later.
37 *
38 * A step also tracks the time it was created, and the user responsible for
39 * creating it.
40 *
41 * The submitted data is basically just an array of name => value pairs, with
42 * certain conventions about the to divide the variables into four = two times two
43 * categories.
44 *
45 * Variables may either belong to the behaviour, in which case the
46 * name starts with a '-', or they may belong to the question type in which case
47 * they name does not start with a '-'.
48 *
49 * Second, variables may either be ones that came form the original request, in
50 * which case the name does not start with an _, or they are cached values that
51 * were created during processing, in which case the name does start with an _.
52 *
53 * That is, each name will start with one of '', '_'. '-' or '-_'. The remainder
54 * of the name should match the regex [a-z][a-z0-9]*.
55 *
56 * These variables can be accessed with {@link get_behaviour_var()} and {@link get_qt_var()},
57 * - to be clear, ->get_behaviour_var('x') gets the variable with name '-x' -
58 * and values whose names start with '_' can be set using {@link set_behaviour_var()}
59 * and {@link set_qt_var()}. There are some other methods like {@link has_behaviour_var()}
60 * to check wether a varaible with a particular name is set, and {@link get_behaviour_data()}
61 * to get all the behaviour data as an associative array.
62 *
63 * @copyright 2009 The Open University
64 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
65 */
66class question_attempt_step {
9c197f44
TH
67 /**
68 * @var integer if this attempts is stored in the question_attempts table,
69 * the id of that row.
70 */
dcd03928
TH
71 private $id = null;
72
9c197f44
TH
73 /**
74 * @var question_state one of the {@link question_state} constants.
75 * The state after this step.
76 */
dcd03928
TH
77 private $state;
78
79 /** @var null|number the fraction (grade on a scale of minfraction .. 1.0) or null. */
80 private $fraction = null;
81
82 /** @var integer the timestamp when this step was created. */
83 private $timecreated;
84
85 /** @var integer the id of the user resonsible for creating this step. */
86 private $userid;
87
88 /** @var array name => value pairs. The submitted data. */
89 private $data;
90
91 /** @var array name => array of {@link stored_file}s. Caches the contents of file areas. */
92 private $files = array();
93
94 /**
95 * You should not need to call this constructor in your own code. Steps are
96 * normally created by {@link question_attempt} methods like
97 * {@link question_attempt::process_action()}.
98 * @param array $data the submitted data that defines this step.
99 * @param int $timestamp the time to record for the action. (If not given, use now.)
100 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
94815ccf
TH
101 * @param int $existingstepid if this step is going to replace an existing step
102 * (for example, during a regrade) this is the id of the previous step we are replacing.
dcd03928 103 */
94815ccf
TH
104 public function __construct($data = array(), $timecreated = null, $userid = null,
105 $existingstepid = null) {
dcd03928 106 global $USER;
36e91f1d 107
1da821bb 108 if (!is_array($data)) {
afb1b3d0 109 throw new coding_exception('$data must be an array when constructing a question_attempt_step.');
1da821bb 110 }
dcd03928
TH
111 $this->state = question_state::$unprocessed;
112 $this->data = $data;
113 if (is_null($timecreated)) {
114 $this->timecreated = time();
115 } else {
116 $this->timecreated = $timecreated;
117 }
118 if (is_null($userid)) {
119 $this->userid = $USER->id;
120 } else {
121 $this->userid = $userid;
122 }
94815ccf
TH
123
124 if (!is_null($existingstepid)) {
125 $this->id = $existingstepid;
126 }
127 }
128
129 /**
130 * @return int|null The id of this step in the database. null if this step
131 * is not stored in the database.
132 */
133 public function get_id() {
134 return $this->id;
dcd03928
TH
135 }
136
137 /** @return question_state The state after this step. */
138 public function get_state() {
139 return $this->state;
140 }
141
142 /**
143 * Set the state. Normally only called by behaviours.
144 * @param question_state $state one of the {@link question_state} constants.
145 */
146 public function set_state($state) {
147 $this->state = $state;
148 }
149
150 /**
151 * @return null|number the fraction (grade on a scale of minfraction .. 1.0)
152 * or null if this step has not been marked.
153 */
154 public function get_fraction() {
155 return $this->fraction;
156 }
157
158 /**
159 * Set the fraction. Normally only called by behaviours.
160 * @param null|number $fraction the fraction to set.
161 */
162 public function set_fraction($fraction) {
163 $this->fraction = $fraction;
164 }
165
166 /** @return int the id of the user resonsible for creating this step. */
167 public function get_user_id() {
168 return $this->userid;
169 }
170
171 /** @return int the timestamp when this step was created. */
172 public function get_timecreated() {
173 return $this->timecreated;
174 }
175
176 /**
177 * @param string $name the name of a question type variable to look for in the submitted data.
178 * @return bool whether a variable with this name exists in the question type data.
179 */
180 public function has_qt_var($name) {
181 return array_key_exists($name, $this->data);
182 }
183
184 /**
185 * @param string $name the name of a question type variable to look for in the submitted data.
186 * @return string the requested variable, or null if the variable is not set.
187 */
188 public function get_qt_var($name) {
189 if (!$this->has_qt_var($name)) {
190 return null;
191 }
192 return $this->data[$name];
193 }
194
195 /**
196 * Set a cached question type variable.
197 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
198 * @param string $value the value to set.
199 */
200 public function set_qt_var($name, $value) {
201 if ($name[0] != '_') {
9c197f44
TH
202 throw new coding_exception('Cannot set question type data ' . $name .
203 ' on an attempt step. You can only set variables with names begining with _.');
dcd03928
TH
204 }
205 $this->data[$name] = $value;
206 }
207
208 /**
209 * Get the latest set of files for a particular question type variable of
210 * type question_attempt::PARAM_FILES.
211 *
212 * @param string $name the name of the associated variable.
213 * @return array of {@link stored_files}.
214 */
215 public function get_qt_files($name, $contextid) {
216 if (array_key_exists($name, $this->files)) {
217 return $this->files[$name];
218 }
219
220 if (!$this->has_qt_var($name)) {
221 $this->files[$name] = array();
222 return array();
223 }
224
225 $fs = get_file_storage();
226 $this->files[$name] = $fs->get_area_files($contextid, 'question',
227 'response_' . $name, $this->id, 'sortorder', false);
228
229 return $this->files[$name];
230 }
231
232 /**
233 * Prepare a draft file are for the files belonging the a response variable
234 * of this step.
235 *
236 * @param string $name the variable name the files belong to.
237 * @param int $contextid the id of the context the quba belongs to.
238 * @return int the draft itemid.
239 */
240 public function prepare_response_files_draft_itemid($name, $contextid) {
241 list($draftid, $notused) = $this->prepare_response_files_draft_itemid_with_text(
242 $name, $contextid, null);
243 return $draftid;
244 }
245
246 /**
247 * Prepare a draft file are for the files belonging the a response variable
248 * of this step, while rewriting the URLs in some text.
249 *
250 * @param string $name the variable name the files belong to.
251 * @param int $contextid the id of the context the quba belongs to.
252 * @param string $text the text to update the URLs in.
253 * @return array(int, string) the draft itemid and the text with URLs rewritten.
254 */
255 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
256 $draftid = 0; // Will be filled in by file_prepare_draft_area.
257 $newtext = file_prepare_draft_area($draftid, $contextid, 'question',
258 'response_' . $name, $this->id, null, $text);
259 return array($draftid, $newtext);
260 }
261
262 /**
263 * Rewrite the @@PLUGINFILE@@ tokens in a response variable from this step
264 * that contains links to file. Normally you should probably call
265 * {@link question_attempt::rewrite_response_pluginfile_urls()} instead of
266 * calling this method directly.
267 *
268 * @param string $text the text to update the URLs in.
269 * @param int $contextid the id of the context the quba belongs to.
270 * @param string $name the variable name the files belong to.
271 * @param array $extra extra file path components.
272 * @return string the rewritten text.
273 */
274 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
275 return question_rewrite_question_urls($text, 'pluginfile.php', $contextid,
276 'question', 'response_' . $name, $extras, $this->id);
277 }
278
279 /**
280 * Get all the question type variables.
281 * @param array name => value pairs.
282 */
283 public function get_qt_data() {
284 $result = array();
285 foreach ($this->data as $name => $value) {
286 if ($name[0] != '-' && $name[0] != ':') {
287 $result[$name] = $value;
288 }
289 }
290 return $result;
291 }
292
293 /**
294 * @param string $name the name of an behaviour variable to look for in the submitted data.
295 * @return bool whether a variable with this name exists in the question type data.
296 */
297 public function has_behaviour_var($name) {
298 return array_key_exists('-' . $name, $this->data);
299 }
300
301 /**
302 * @param string $name the name of an behaviour variable to look for in the submitted data.
303 * @return string the requested variable, or null if the variable is not set.
304 */
305 public function get_behaviour_var($name) {
306 if (!$this->has_behaviour_var($name)) {
307 return null;
308 }
309 return $this->data['-' . $name];
310 }
311
312 /**
313 * Set a cached behaviour variable.
314 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
315 * @param string $value the value to set.
316 */
317 public function set_behaviour_var($name, $value) {
318 if ($name[0] != '_') {
9c197f44
TH
319 throw new coding_exception('Cannot set question type data ' . $name .
320 ' on an attempt step. You can only set variables with names begining with _.');
dcd03928
TH
321 }
322 return $this->data['-' . $name] = $value;
323 }
324
325 /**
326 * Get all the behaviour variables.
327 * @param array name => value pairs.
328 */
329 public function get_behaviour_data() {
330 $result = array();
331 foreach ($this->data as $name => $value) {
332 if ($name[0] == '-') {
333 $result[substr($name, 1)] = $value;
334 }
335 }
336 return $result;
337 }
338
339 /**
340 * Get all the submitted data, but not the cached data. behaviour
341 * variables have the - at the start of their name. This is only really
342 * intended for use by {@link question_attempt::regrade()}, it should not
343 * be considered part of the public API.
344 * @param array name => value pairs.
345 */
346 public function get_submitted_data() {
347 $result = array();
348 foreach ($this->data as $name => $value) {
349 if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
350 continue;
351 }
352 $result[$name] = $value;
353 }
354 return $result;
355 }
356
357 /**
358 * Get all the data. behaviour variables have the - at the start of
359 * their name. This is only intended for internal use, for example by
360 * {@link question_engine_data_mapper::insert_question_attempt_step()},
361 * however, it can ocasionally be useful in test code. It should not be
362 * considered part of the public API of this class.
363 * @param array name => value pairs.
364 */
365 public function get_all_data() {
366 return $this->data;
367 }
368
369 /**
370 * Create a question_attempt_step from records loaded from the database.
35d5f1c2 371 * @param Iterator $records Raw records loaded from the database.
dcd03928 372 * @param int $stepid The id of the records to extract.
dc1ee5cb
TH
373 * @param string $qtype The question type of which this is an attempt.
374 * If not given, each record must include a qtype field.
dcd03928
TH
375 * @return question_attempt_step The newly constructed question_attempt_step.
376 */
dc1ee5cb 377 public static function load_from_records($records, $attemptstepid, $qtype = null) {
35d5f1c2 378 $currentrec = $records->current();
dcd03928 379 while ($currentrec->attemptstepid != $attemptstepid) {
35d5f1c2
TH
380 $records->next();
381 if (!$records->valid()) {
9c197f44
TH
382 throw new coding_exception('Question attempt step ' . $attemptstepid .
383 ' not found in the database.');
dcd03928 384 }
35d5f1c2 385 $currentrec = $records->current();
dcd03928
TH
386 }
387
388 $record = $currentrec;
dc1ee5cb 389 $contextid = null;
dcd03928
TH
390 $data = array();
391 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
65cf651f 392 if (!is_null($currentrec->name)) {
dcd03928
TH
393 $data[$currentrec->name] = $currentrec->value;
394 }
35d5f1c2
TH
395 $records->next();
396 if ($records->valid()) {
397 $currentrec = $records->current();
398 } else {
399 $currentrec = false;
400 }
dcd03928
TH
401 }
402
403 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
404 $step->state = question_state::get($record->state);
405 $step->id = $record->attemptstepid;
406 if (!is_null($record->fraction)) {
407 $step->fraction = $record->fraction + 0;
408 }
8a1e7b77
TH
409
410 // This next chunk of code requires getting $contextid and $qtype here.
411 // Somehow, we need to get that information to this point by modifying
412 // all the paths by which this method can be called.
d0782585 413 // Can we only return files when it's possible? Should there be some kind of warning?
dc1ee5cb
TH
414 if (is_null($qtype)) {
415 $qtype = $record->qtype;
416 }
417 foreach (question_bank::get_qtype($qtype)->response_file_areas() as $area) {
418 if (empty($step->data[$area])) {
419 continue;
8a1e7b77 420 }
dc1ee5cb
TH
421
422 $step->data[$area] = new question_file_loader($step, $area, $step->data[$area], $record->contextid);
8a1e7b77
TH
423 }
424
dcd03928
TH
425 return $step;
426 }
427}
428
429
430/**
431 * A subclass with a bit of additional funcitonality, for pending steps.
432 *
433 * @copyright 2010 The Open University
434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
435 */
436class question_attempt_pending_step extends question_attempt_step {
437 /** @var string . */
438 protected $newresponsesummary = null;
439
440 /**
441 * If as a result of processing this step, the response summary for the
442 * question attempt should changed, you should call this method to set the
443 * new summary.
444 * @param string $responsesummary the new response summary.
445 */
446 public function set_new_response_summary($responsesummary) {
447 $this->newresponsesummary = $responsesummary;
448 }
449
450 /** @return string the new response summary, if any. */
451 public function get_new_response_summary() {
452 return $this->newresponsesummary;
453 }
454
455 /** @return string whether this step changes the response summary. */
456 public function response_summary_changed() {
457 return !is_null($this->newresponsesummary);
458 }
459}
460
461
462/**
463 * A subclass of {@link question_attempt_step} that cannot be modified.
464 *
465 * @copyright 2009 The Open University
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
467 */
468class question_attempt_step_read_only extends question_attempt_step {
469 public function set_state($state) {
470 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
471 }
472 public function set_fraction($fraction) {
473 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
474 }
475 public function set_qt_var($name, $value) {
476 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
477 }
478 public function set_behaviour_var($name, $value) {
479 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
480 }
481}
482
483
484/**
485 * A null {@link question_attempt_step} returned from
486 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
487 * created and there is no acutal step.
488 *
489 * @copyright 2009 The Open University
490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
491 */
492class question_null_step {
493 public function get_state() {
494 return question_state::$notstarted;
495 }
496
497 public function set_state($state) {
498 throw new coding_exception('This question has not been started.');
499 }
500
501 public function get_fraction() {
502 return null;
503 }
504}
ab50232b
TH
505
506
507/**
508 * This is an adapter class that wraps a {@link question_attempt_step} and
509 * modifies the get/set_*_data methods so that they operate only on the parts
510 * that belong to a particular subquestion, as indicated by an extra prefix.
511 *
512 * @copyright 2010 The Open University
513 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
514 */
515class question_attempt_step_subquestion_adapter extends question_attempt_step {
516 /** @var question_attempt_step the step we are wrapping. */
517 protected $realstep;
518 /** @var string the exta prefix on fields we work with. */
519 protected $extraprefix;
520
521 /**
522 * Constructor.
523 * @param question_attempt_step $realqas the step to wrap. (Can be null if you
524 * just want to call add/remove.prefix.)
525 * @param unknown_type $extraprefix the extra prefix that is used for date fields.
526 */
527 public function __construct($realqas, $extraprefix) {
528 $this->realqas = $realqas;
529 $this->extraprefix = $extraprefix;
530 }
531
532 /**
533 * Add the extra prefix to a field name.
534 * @param string $field the plain field name.
535 * @return string the field name with the extra bit of prefix added.
536 */
537 public function add_prefix($field) {
538 if (substr($field, 0, 2) === '!_') {
539 return '-_' . $this->extraprefix . substr($field, 2);
540 } else if (substr($field, 0, 1) === '-') {
541 return '-' . $this->extraprefix . substr($field, 1);
542 } else if (substr($field, 0, 1) === '_') {
543 return '_' . $this->extraprefix . substr($field, 1);
544 } else {
545 return $this->extraprefix . $field;
546 }
547 }
548
549 /**
550 * Remove the extra prefix from a field name if it is present.
551 * @param string $field the extended field name.
552 * @return string the field name with the extra bit of prefix removed, or
553 * null if the extre prefix was not present.
554 */
555 public function remove_prefix($field) {
03cefcc9 556 if (preg_match('~^(-?_?)' . preg_quote($this->extraprefix, '~') . '(.*)$~', $field, $matches)) {
ab50232b
TH
557 return $matches[1] . $matches[2];
558 } else {
559 return null;
560 }
561 }
562
563 /**
564 * Filter some data to keep only those entries where the key contains
36e91f1d 565 * extraprefix, and remove the extra prefix from the reutrned arrary.
ab50232b
TH
566 * @param array $data some of the data stored in this step.
567 * @return array the data with the keys ajusted using {@link remove_prefix()}.
568 */
569 public function filter_array($data) {
570 $result = array();
571 foreach ($data as $fullname => $value) {
572 if ($name = $this->remove_prefix($fullname)) {
573 $result[$name] = $value;
574 }
575 }
576 return $result;
577 }
578
579 public function get_state() {
580 return $this->realqas->get_state();
581 }
582
583 public function set_state($state) {
584 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
585 }
586
587 public function get_fraction() {
588 return $this->realqas->get_fraction();
589 }
590
591 public function set_fraction($fraction) {
592 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
593 }
594
595 public function get_user_id() {
596 return $this->realqas->get_user_id;
597 }
598
599 public function get_timecreated() {
600 return $this->realqas->get_timecreated();
601 }
602
603 public function has_qt_var($name) {
604 return $this->realqas->has_qt_var($this->add_prefix($name));
605 }
606
607 public function get_qt_var($name) {
608 return $this->realqas->get_qt_var($this->add_prefix($name));
609 }
610
611 public function set_qt_var($name, $value) {
612 return $this->realqas->set_qt_var($this->add_prefix($name), $value);
613 }
614
615 public function get_qt_data() {
616 return $this->filter_array($this->realqas->get_qt_data());
617 }
618
619 public function has_behaviour_var($name) {
620 return $this->realqas->has_im_var($this->add_prefix($name));
621 }
622
623 public function get_behaviour_var($name) {
624 return $this->realqas->get_im_var($this->add_prefix($name));
625 }
626
627 public function set_behaviour_var($name, $value) {
628 return $this->realqas->set_im_var($this->add_prefix($name), $value);
629 }
630
631 public function get_behaviour_data() {
632 return $this->filter_array($this->realqas->get_behaviour_data());
633 }
634
635 public function get_submitted_data() {
636 return $this->filter_array($this->realqas->get_submitted_data());
637 }
638
639 public function get_all_data() {
640 return $this->filter_array($this->realqas->get_all_data());
641 }
642
643 public function get_qt_files($name, $contextid) {
644 throw new coding_exception('No attempt has yet been made to implement files support in ' .
645 'question_attempt_step_subquestion_adapter.');
646 }
647
648 public function prepare_response_files_draft_itemid($name, $contextid) {
649 throw new coding_exception('No attempt has yet been made to implement files support in ' .
650 'question_attempt_step_subquestion_adapter.');
651 }
652
653 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
654 throw new coding_exception('No attempt has yet been made to implement files support in ' .
655 'question_attempt_step_subquestion_adapter.');
656 }
657
658 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
659 throw new coding_exception('No attempt has yet been made to implement files support in ' .
660 'question_attempt_step_subquestion_adapter.');
661 }
662}