on-demand release 2.1beta
[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.
356 * @param array $records Raw records loaded from the database.
357 * @param int $stepid The id of the records to extract.
358 * @return question_attempt_step The newly constructed question_attempt_step.
359 */
360 public static function load_from_records(&$records, $attemptstepid) {
361 $currentrec = current($records);
362 while ($currentrec->attemptstepid != $attemptstepid) {
363 $currentrec = next($records);
364 if (!$currentrec) {
9c197f44
TH
365 throw new coding_exception('Question attempt step ' . $attemptstepid .
366 ' not found in the database.');
dcd03928
TH
367 }
368 }
369
370 $record = $currentrec;
371 $data = array();
372 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
373 if ($currentrec->name) {
374 $data[$currentrec->name] = $currentrec->value;
375 }
376 $currentrec = next($records);
377 }
378
379 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
380 $step->state = question_state::get($record->state);
381 $step->id = $record->attemptstepid;
382 if (!is_null($record->fraction)) {
383 $step->fraction = $record->fraction + 0;
384 }
385 return $step;
386 }
387}
388
389
390/**
391 * A subclass with a bit of additional funcitonality, for pending steps.
392 *
393 * @copyright 2010 The Open University
394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
395 */
396class question_attempt_pending_step extends question_attempt_step {
397 /** @var string . */
398 protected $newresponsesummary = null;
399
400 /**
401 * If as a result of processing this step, the response summary for the
402 * question attempt should changed, you should call this method to set the
403 * new summary.
404 * @param string $responsesummary the new response summary.
405 */
406 public function set_new_response_summary($responsesummary) {
407 $this->newresponsesummary = $responsesummary;
408 }
409
410 /** @return string the new response summary, if any. */
411 public function get_new_response_summary() {
412 return $this->newresponsesummary;
413 }
414
415 /** @return string whether this step changes the response summary. */
416 public function response_summary_changed() {
417 return !is_null($this->newresponsesummary);
418 }
419}
420
421
422/**
423 * A subclass of {@link question_attempt_step} that cannot be modified.
424 *
425 * @copyright 2009 The Open University
426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
427 */
428class question_attempt_step_read_only extends question_attempt_step {
429 public function set_state($state) {
430 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
431 }
432 public function set_fraction($fraction) {
433 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
434 }
435 public function set_qt_var($name, $value) {
436 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
437 }
438 public function set_behaviour_var($name, $value) {
439 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
440 }
441}
442
443
444/**
445 * A null {@link question_attempt_step} returned from
446 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
447 * created and there is no acutal step.
448 *
449 * @copyright 2009 The Open University
450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
451 */
452class question_null_step {
453 public function get_state() {
454 return question_state::$notstarted;
455 }
456
457 public function set_state($state) {
458 throw new coding_exception('This question has not been started.');
459 }
460
461 public function get_fraction() {
462 return null;
463 }
464}
ab50232b
TH
465
466
467/**
468 * This is an adapter class that wraps a {@link question_attempt_step} and
469 * modifies the get/set_*_data methods so that they operate only on the parts
470 * that belong to a particular subquestion, as indicated by an extra prefix.
471 *
472 * @copyright 2010 The Open University
473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
474 */
475class question_attempt_step_subquestion_adapter extends question_attempt_step {
476 /** @var question_attempt_step the step we are wrapping. */
477 protected $realstep;
478 /** @var string the exta prefix on fields we work with. */
479 protected $extraprefix;
480
481 /**
482 * Constructor.
483 * @param question_attempt_step $realqas the step to wrap. (Can be null if you
484 * just want to call add/remove.prefix.)
485 * @param unknown_type $extraprefix the extra prefix that is used for date fields.
486 */
487 public function __construct($realqas, $extraprefix) {
488 $this->realqas = $realqas;
489 $this->extraprefix = $extraprefix;
490 }
491
492 /**
493 * Add the extra prefix to a field name.
494 * @param string $field the plain field name.
495 * @return string the field name with the extra bit of prefix added.
496 */
497 public function add_prefix($field) {
498 if (substr($field, 0, 2) === '!_') {
499 return '-_' . $this->extraprefix . substr($field, 2);
500 } else if (substr($field, 0, 1) === '-') {
501 return '-' . $this->extraprefix . substr($field, 1);
502 } else if (substr($field, 0, 1) === '_') {
503 return '_' . $this->extraprefix . substr($field, 1);
504 } else {
505 return $this->extraprefix . $field;
506 }
507 }
508
509 /**
510 * Remove the extra prefix from a field name if it is present.
511 * @param string $field the extended field name.
512 * @return string the field name with the extra bit of prefix removed, or
513 * null if the extre prefix was not present.
514 */
515 public function remove_prefix($field) {
516 if (preg_match('~^(-?_?)' . preg_quote($this->extraprefix) . '(.*)$~', $field, $matches)) {
517 return $matches[1] . $matches[2];
518 } else {
519 return null;
520 }
521 }
522
523 /**
524 * Filter some data to keep only those entries where the key contains
36e91f1d 525 * extraprefix, and remove the extra prefix from the reutrned arrary.
ab50232b
TH
526 * @param array $data some of the data stored in this step.
527 * @return array the data with the keys ajusted using {@link remove_prefix()}.
528 */
529 public function filter_array($data) {
530 $result = array();
531 foreach ($data as $fullname => $value) {
532 if ($name = $this->remove_prefix($fullname)) {
533 $result[$name] = $value;
534 }
535 }
536 return $result;
537 }
538
539 public function get_state() {
540 return $this->realqas->get_state();
541 }
542
543 public function set_state($state) {
544 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
545 }
546
547 public function get_fraction() {
548 return $this->realqas->get_fraction();
549 }
550
551 public function set_fraction($fraction) {
552 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
553 }
554
555 public function get_user_id() {
556 return $this->realqas->get_user_id;
557 }
558
559 public function get_timecreated() {
560 return $this->realqas->get_timecreated();
561 }
562
563 public function has_qt_var($name) {
564 return $this->realqas->has_qt_var($this->add_prefix($name));
565 }
566
567 public function get_qt_var($name) {
568 return $this->realqas->get_qt_var($this->add_prefix($name));
569 }
570
571 public function set_qt_var($name, $value) {
572 return $this->realqas->set_qt_var($this->add_prefix($name), $value);
573 }
574
575 public function get_qt_data() {
576 return $this->filter_array($this->realqas->get_qt_data());
577 }
578
579 public function has_behaviour_var($name) {
580 return $this->realqas->has_im_var($this->add_prefix($name));
581 }
582
583 public function get_behaviour_var($name) {
584 return $this->realqas->get_im_var($this->add_prefix($name));
585 }
586
587 public function set_behaviour_var($name, $value) {
588 return $this->realqas->set_im_var($this->add_prefix($name), $value);
589 }
590
591 public function get_behaviour_data() {
592 return $this->filter_array($this->realqas->get_behaviour_data());
593 }
594
595 public function get_submitted_data() {
596 return $this->filter_array($this->realqas->get_submitted_data());
597 }
598
599 public function get_all_data() {
600 return $this->filter_array($this->realqas->get_all_data());
601 }
602
603 public function get_qt_files($name, $contextid) {
604 throw new coding_exception('No attempt has yet been made to implement files support in ' .
605 'question_attempt_step_subquestion_adapter.');
606 }
607
608 public function prepare_response_files_draft_itemid($name, $contextid) {
609 throw new coding_exception('No attempt has yet been made to implement files support in ' .
610 'question_attempt_step_subquestion_adapter.');
611 }
612
613 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
614 throw new coding_exception('No attempt has yet been made to implement files support in ' .
615 'question_attempt_step_subquestion_adapter.');
616 }
617
618 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
619 throw new coding_exception('No attempt has yet been made to implement files support in ' .
620 'question_attempt_step_subquestion_adapter.');
621 }
622}