weekly release 2.3dev (blame stronk7 for 0202 mistake)
[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.)
101 */
102 public function __construct($data = array(), $timecreated = null, $userid = null) {
103 global $USER;
36e91f1d 104
1da821bb
TH
105 if (!is_array($data)) {
106 echo format_backtrace(debug_backtrace());
107 }
dcd03928
TH
108 $this->state = question_state::$unprocessed;
109 $this->data = $data;
110 if (is_null($timecreated)) {
111 $this->timecreated = time();
112 } else {
113 $this->timecreated = $timecreated;
114 }
115 if (is_null($userid)) {
116 $this->userid = $USER->id;
117 } else {
118 $this->userid = $userid;
119 }
120 }
121
122 /** @return question_state The state after this step. */
123 public function get_state() {
124 return $this->state;
125 }
126
127 /**
128 * Set the state. Normally only called by behaviours.
129 * @param question_state $state one of the {@link question_state} constants.
130 */
131 public function set_state($state) {
132 $this->state = $state;
133 }
134
135 /**
136 * @return null|number the fraction (grade on a scale of minfraction .. 1.0)
137 * or null if this step has not been marked.
138 */
139 public function get_fraction() {
140 return $this->fraction;
141 }
142
143 /**
144 * Set the fraction. Normally only called by behaviours.
145 * @param null|number $fraction the fraction to set.
146 */
147 public function set_fraction($fraction) {
148 $this->fraction = $fraction;
149 }
150
151 /** @return int the id of the user resonsible for creating this step. */
152 public function get_user_id() {
153 return $this->userid;
154 }
155
156 /** @return int the timestamp when this step was created. */
157 public function get_timecreated() {
158 return $this->timecreated;
159 }
160
161 /**
162 * @param string $name the name of a question type variable to look for in the submitted data.
163 * @return bool whether a variable with this name exists in the question type data.
164 */
165 public function has_qt_var($name) {
166 return array_key_exists($name, $this->data);
167 }
168
169 /**
170 * @param string $name the name of a question type variable to look for in the submitted data.
171 * @return string the requested variable, or null if the variable is not set.
172 */
173 public function get_qt_var($name) {
174 if (!$this->has_qt_var($name)) {
175 return null;
176 }
177 return $this->data[$name];
178 }
179
180 /**
181 * Set a cached question type variable.
182 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
183 * @param string $value the value to set.
184 */
185 public function set_qt_var($name, $value) {
186 if ($name[0] != '_') {
9c197f44
TH
187 throw new coding_exception('Cannot set question type data ' . $name .
188 ' on an attempt step. You can only set variables with names begining with _.');
dcd03928
TH
189 }
190 $this->data[$name] = $value;
191 }
192
193 /**
194 * Get the latest set of files for a particular question type variable of
195 * type question_attempt::PARAM_FILES.
196 *
197 * @param string $name the name of the associated variable.
198 * @return array of {@link stored_files}.
199 */
200 public function get_qt_files($name, $contextid) {
201 if (array_key_exists($name, $this->files)) {
202 return $this->files[$name];
203 }
204
205 if (!$this->has_qt_var($name)) {
206 $this->files[$name] = array();
207 return array();
208 }
209
210 $fs = get_file_storage();
211 $this->files[$name] = $fs->get_area_files($contextid, 'question',
212 'response_' . $name, $this->id, 'sortorder', false);
213
214 return $this->files[$name];
215 }
216
217 /**
218 * Prepare a draft file are for the files belonging the a response variable
219 * of this step.
220 *
221 * @param string $name the variable name the files belong to.
222 * @param int $contextid the id of the context the quba belongs to.
223 * @return int the draft itemid.
224 */
225 public function prepare_response_files_draft_itemid($name, $contextid) {
226 list($draftid, $notused) = $this->prepare_response_files_draft_itemid_with_text(
227 $name, $contextid, null);
228 return $draftid;
229 }
230
231 /**
232 * Prepare a draft file are for the files belonging the a response variable
233 * of this step, while rewriting the URLs in some text.
234 *
235 * @param string $name the variable name the files belong to.
236 * @param int $contextid the id of the context the quba belongs to.
237 * @param string $text the text to update the URLs in.
238 * @return array(int, string) the draft itemid and the text with URLs rewritten.
239 */
240 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
241 $draftid = 0; // Will be filled in by file_prepare_draft_area.
242 $newtext = file_prepare_draft_area($draftid, $contextid, 'question',
243 'response_' . $name, $this->id, null, $text);
244 return array($draftid, $newtext);
245 }
246
247 /**
248 * Rewrite the @@PLUGINFILE@@ tokens in a response variable from this step
249 * that contains links to file. Normally you should probably call
250 * {@link question_attempt::rewrite_response_pluginfile_urls()} instead of
251 * calling this method directly.
252 *
253 * @param string $text the text to update the URLs in.
254 * @param int $contextid the id of the context the quba belongs to.
255 * @param string $name the variable name the files belong to.
256 * @param array $extra extra file path components.
257 * @return string the rewritten text.
258 */
259 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
260 return question_rewrite_question_urls($text, 'pluginfile.php', $contextid,
261 'question', 'response_' . $name, $extras, $this->id);
262 }
263
264 /**
265 * Get all the question type variables.
266 * @param array name => value pairs.
267 */
268 public function get_qt_data() {
269 $result = array();
270 foreach ($this->data as $name => $value) {
271 if ($name[0] != '-' && $name[0] != ':') {
272 $result[$name] = $value;
273 }
274 }
275 return $result;
276 }
277
278 /**
279 * @param string $name the name of an behaviour variable to look for in the submitted data.
280 * @return bool whether a variable with this name exists in the question type data.
281 */
282 public function has_behaviour_var($name) {
283 return array_key_exists('-' . $name, $this->data);
284 }
285
286 /**
287 * @param string $name the name of an behaviour variable to look for in the submitted data.
288 * @return string the requested variable, or null if the variable is not set.
289 */
290 public function get_behaviour_var($name) {
291 if (!$this->has_behaviour_var($name)) {
292 return null;
293 }
294 return $this->data['-' . $name];
295 }
296
297 /**
298 * Set a cached behaviour variable.
299 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
300 * @param string $value the value to set.
301 */
302 public function set_behaviour_var($name, $value) {
303 if ($name[0] != '_') {
9c197f44
TH
304 throw new coding_exception('Cannot set question type data ' . $name .
305 ' on an attempt step. You can only set variables with names begining with _.');
dcd03928
TH
306 }
307 return $this->data['-' . $name] = $value;
308 }
309
310 /**
311 * Get all the behaviour variables.
312 * @param array name => value pairs.
313 */
314 public function get_behaviour_data() {
315 $result = array();
316 foreach ($this->data as $name => $value) {
317 if ($name[0] == '-') {
318 $result[substr($name, 1)] = $value;
319 }
320 }
321 return $result;
322 }
323
324 /**
325 * Get all the submitted data, but not the cached data. behaviour
326 * variables have the - at the start of their name. This is only really
327 * intended for use by {@link question_attempt::regrade()}, it should not
328 * be considered part of the public API.
329 * @param array name => value pairs.
330 */
331 public function get_submitted_data() {
332 $result = array();
333 foreach ($this->data as $name => $value) {
334 if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
335 continue;
336 }
337 $result[$name] = $value;
338 }
339 return $result;
340 }
341
342 /**
343 * Get all the data. behaviour variables have the - at the start of
344 * their name. This is only intended for internal use, for example by
345 * {@link question_engine_data_mapper::insert_question_attempt_step()},
346 * however, it can ocasionally be useful in test code. It should not be
347 * considered part of the public API of this class.
348 * @param array name => value pairs.
349 */
350 public function get_all_data() {
351 return $this->data;
352 }
353
354 /**
355 * Create a question_attempt_step from records loaded from the database.
35d5f1c2 356 * @param Iterator $records Raw records loaded from the database.
dcd03928
TH
357 * @param int $stepid The id of the records to extract.
358 * @return question_attempt_step The newly constructed question_attempt_step.
359 */
35d5f1c2
TH
360 public static function load_from_records($records, $attemptstepid) {
361 $currentrec = $records->current();
dcd03928 362 while ($currentrec->attemptstepid != $attemptstepid) {
35d5f1c2
TH
363 $records->next();
364 if (!$records->valid()) {
9c197f44
TH
365 throw new coding_exception('Question attempt step ' . $attemptstepid .
366 ' not found in the database.');
dcd03928 367 }
35d5f1c2 368 $currentrec = $records->current();
dcd03928
TH
369 }
370
371 $record = $currentrec;
372 $data = array();
373 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
374 if ($currentrec->name) {
375 $data[$currentrec->name] = $currentrec->value;
376 }
35d5f1c2
TH
377 $records->next();
378 if ($records->valid()) {
379 $currentrec = $records->current();
380 } else {
381 $currentrec = false;
382 }
dcd03928
TH
383 }
384
385 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
386 $step->state = question_state::get($record->state);
387 $step->id = $record->attemptstepid;
388 if (!is_null($record->fraction)) {
389 $step->fraction = $record->fraction + 0;
390 }
391 return $step;
392 }
393}
394
395
396/**
397 * A subclass with a bit of additional funcitonality, for pending steps.
398 *
399 * @copyright 2010 The Open University
400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
401 */
402class question_attempt_pending_step extends question_attempt_step {
403 /** @var string . */
404 protected $newresponsesummary = null;
405
406 /**
407 * If as a result of processing this step, the response summary for the
408 * question attempt should changed, you should call this method to set the
409 * new summary.
410 * @param string $responsesummary the new response summary.
411 */
412 public function set_new_response_summary($responsesummary) {
413 $this->newresponsesummary = $responsesummary;
414 }
415
416 /** @return string the new response summary, if any. */
417 public function get_new_response_summary() {
418 return $this->newresponsesummary;
419 }
420
421 /** @return string whether this step changes the response summary. */
422 public function response_summary_changed() {
423 return !is_null($this->newresponsesummary);
424 }
425}
426
427
428/**
429 * A subclass of {@link question_attempt_step} that cannot be modified.
430 *
431 * @copyright 2009 The Open University
432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
433 */
434class question_attempt_step_read_only extends question_attempt_step {
435 public function set_state($state) {
436 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
437 }
438 public function set_fraction($fraction) {
439 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
440 }
441 public function set_qt_var($name, $value) {
442 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
443 }
444 public function set_behaviour_var($name, $value) {
445 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
446 }
447}
448
449
450/**
451 * A null {@link question_attempt_step} returned from
452 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
453 * created and there is no acutal step.
454 *
455 * @copyright 2009 The Open University
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 */
458class question_null_step {
459 public function get_state() {
460 return question_state::$notstarted;
461 }
462
463 public function set_state($state) {
464 throw new coding_exception('This question has not been started.');
465 }
466
467 public function get_fraction() {
468 return null;
469 }
470}
ab50232b
TH
471
472
473/**
474 * This is an adapter class that wraps a {@link question_attempt_step} and
475 * modifies the get/set_*_data methods so that they operate only on the parts
476 * that belong to a particular subquestion, as indicated by an extra prefix.
477 *
478 * @copyright 2010 The Open University
479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
480 */
481class question_attempt_step_subquestion_adapter extends question_attempt_step {
482 /** @var question_attempt_step the step we are wrapping. */
483 protected $realstep;
484 /** @var string the exta prefix on fields we work with. */
485 protected $extraprefix;
486
487 /**
488 * Constructor.
489 * @param question_attempt_step $realqas the step to wrap. (Can be null if you
490 * just want to call add/remove.prefix.)
491 * @param unknown_type $extraprefix the extra prefix that is used for date fields.
492 */
493 public function __construct($realqas, $extraprefix) {
494 $this->realqas = $realqas;
495 $this->extraprefix = $extraprefix;
496 }
497
498 /**
499 * Add the extra prefix to a field name.
500 * @param string $field the plain field name.
501 * @return string the field name with the extra bit of prefix added.
502 */
503 public function add_prefix($field) {
504 if (substr($field, 0, 2) === '!_') {
505 return '-_' . $this->extraprefix . substr($field, 2);
506 } else if (substr($field, 0, 1) === '-') {
507 return '-' . $this->extraprefix . substr($field, 1);
508 } else if (substr($field, 0, 1) === '_') {
509 return '_' . $this->extraprefix . substr($field, 1);
510 } else {
511 return $this->extraprefix . $field;
512 }
513 }
514
515 /**
516 * Remove the extra prefix from a field name if it is present.
517 * @param string $field the extended field name.
518 * @return string the field name with the extra bit of prefix removed, or
519 * null if the extre prefix was not present.
520 */
521 public function remove_prefix($field) {
522 if (preg_match('~^(-?_?)' . preg_quote($this->extraprefix) . '(.*)$~', $field, $matches)) {
523 return $matches[1] . $matches[2];
524 } else {
525 return null;
526 }
527 }
528
529 /**
530 * Filter some data to keep only those entries where the key contains
36e91f1d 531 * extraprefix, and remove the extra prefix from the reutrned arrary.
ab50232b
TH
532 * @param array $data some of the data stored in this step.
533 * @return array the data with the keys ajusted using {@link remove_prefix()}.
534 */
535 public function filter_array($data) {
536 $result = array();
537 foreach ($data as $fullname => $value) {
538 if ($name = $this->remove_prefix($fullname)) {
539 $result[$name] = $value;
540 }
541 }
542 return $result;
543 }
544
545 public function get_state() {
546 return $this->realqas->get_state();
547 }
548
549 public function set_state($state) {
550 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
551 }
552
553 public function get_fraction() {
554 return $this->realqas->get_fraction();
555 }
556
557 public function set_fraction($fraction) {
558 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
559 }
560
561 public function get_user_id() {
562 return $this->realqas->get_user_id;
563 }
564
565 public function get_timecreated() {
566 return $this->realqas->get_timecreated();
567 }
568
569 public function has_qt_var($name) {
570 return $this->realqas->has_qt_var($this->add_prefix($name));
571 }
572
573 public function get_qt_var($name) {
574 return $this->realqas->get_qt_var($this->add_prefix($name));
575 }
576
577 public function set_qt_var($name, $value) {
578 return $this->realqas->set_qt_var($this->add_prefix($name), $value);
579 }
580
581 public function get_qt_data() {
582 return $this->filter_array($this->realqas->get_qt_data());
583 }
584
585 public function has_behaviour_var($name) {
586 return $this->realqas->has_im_var($this->add_prefix($name));
587 }
588
589 public function get_behaviour_var($name) {
590 return $this->realqas->get_im_var($this->add_prefix($name));
591 }
592
593 public function set_behaviour_var($name, $value) {
594 return $this->realqas->set_im_var($this->add_prefix($name), $value);
595 }
596
597 public function get_behaviour_data() {
598 return $this->filter_array($this->realqas->get_behaviour_data());
599 }
600
601 public function get_submitted_data() {
602 return $this->filter_array($this->realqas->get_submitted_data());
603 }
604
605 public function get_all_data() {
606 return $this->filter_array($this->realqas->get_all_data());
607 }
608
609 public function get_qt_files($name, $contextid) {
610 throw new coding_exception('No attempt has yet been made to implement files support in ' .
611 'question_attempt_step_subquestion_adapter.');
612 }
613
614 public function prepare_response_files_draft_itemid($name, $contextid) {
615 throw new coding_exception('No attempt has yet been made to implement files support in ' .
616 'question_attempt_step_subquestion_adapter.');
617 }
618
619 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
620 throw new coding_exception('No attempt has yet been made to implement files support in ' .
621 'question_attempt_step_subquestion_adapter.');
622 }
623
624 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
625 throw new coding_exception('No attempt has yet been made to implement files support in ' .
626 'question_attempt_step_subquestion_adapter.');
627 }
628}