MDL-73975 course: Remove course_search_form template
[moodle.git] / question / engine / questionattemptstep.php
blobf8bddf685073381b1a9ee065ca4df2407d958b7f
1 <?php
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.
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/>.
17 /**
18 * This file defines the question attempt step class, and a few related classes.
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
27 defined('MOODLE_INTERNAL') || die();
30 /**
31 * Stores one step in a {@see question_attempt}.
33 * The most important attributes of a step are the state, which is one of the
34 * {@see question_state} constants, the fraction, which may be null, or a
35 * number bewteen the attempt's minfraction and maxfraction, and the array of submitted
36 * data, about which more later.
38 * A step also tracks the time it was created, and the user responsible for
39 * creating it.
41 * The submitted data is basically just an array of name => value pairs, with
42 * certain conventions about the to divide the variables into five = 2 x 2 + 1 categories.
44 * Variables may either belong to the behaviour, in which case the
45 * name starts with a '-', or they may belong to the question type in which case
46 * they name does not start with a '-'.
48 * Second, variables may either be ones that came form the original request, in
49 * which case the name does not start with an _, or they are cached values that
50 * were created during processing, in which case the name does start with an _.
52 * In addition, we can store 'metadata', typically only in the first step of a
53 * question attempt. These are stored with the initial characters ':_'.
55 * That is, each name will start with one of '', '_', '-', '-_' or ':_'. The remainder
56 * of the name was supposed to match the regex [a-z][a-z0-9]* - but this has never
57 * been enforced. Question types exist which break this rule. E.g. qtype_combined.
58 * Perhpas now, an accurate regex would be [a-z][a-z0-9_:]*.
60 * These variables can be accessed with {@see get_behaviour_var()} and {@see get_qt_var()},
61 * - to be clear, ->get_behaviour_var('x') gets the variable with name '-x' -
62 * and values whose names start with '_' can be set using {@see set_behaviour_var()}
63 * and {@see set_qt_var()}. There are some other methods like {@see has_behaviour_var()}
64 * to check wether a varaible with a particular name is set, and {@see get_behaviour_data()}
65 * to get all the behaviour data as an associative array. There are also
66 * {@see get_metadata_var()}, {@see set_metadata_var()} and {@see has_metadata_var()},
68 * @copyright 2009 The Open University
69 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
71 class question_attempt_step {
72 /**
73 * @var integer if this attempts is stored in the question_attempts table,
74 * the id of that row.
76 private $id = null;
78 /**
79 * @var question_state one of the {@see question_state} constants.
80 * The state after this step.
82 private $state;
84 /**
85 * @var null|number the fraction (grade on a scale of
86 * minfraction .. maxfraction, normally 0..1) or null.
88 private $fraction = null;
90 /** @var integer the timestamp when this step was created. */
91 private $timecreated;
93 /** @var integer the id of the user resonsible for creating this step. */
94 private $userid;
96 /** @var array name => value pairs. The submitted data. */
97 private $data;
99 /** @var array name => array of {@see stored_file}s. Caches the contents of file areas. */
100 private $files = array();
102 /** @var stdClass User information. */
103 private $user = null;
106 * You should not need to call this constructor in your own code. Steps are
107 * normally created by {@see question_attempt} methods like
108 * {@see question_attempt::process_action()}.
109 * @param array $data the submitted data that defines this step.
110 * @param int $timestamp the time to record for the action. (If not given, use now.)
111 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
112 * @param int $existingstepid if this step is going to replace an existing step
113 * (for example, during a regrade) this is the id of the previous step we are replacing.
115 public function __construct($data = array(), $timecreated = null, $userid = null,
116 $existingstepid = null) {
117 global $USER;
119 if (!is_array($data)) {
120 throw new coding_exception('$data must be an array when constructing a question_attempt_step.');
122 $this->state = question_state::$unprocessed;
123 $this->data = $data;
124 if (is_null($timecreated)) {
125 $this->timecreated = time();
126 } else {
127 $this->timecreated = $timecreated;
129 if (is_null($userid)) {
130 $this->userid = $USER->id;
131 } else {
132 $this->userid = $userid;
135 if (!is_null($existingstepid)) {
136 $this->id = $existingstepid;
141 * @return int|null The id of this step in the database. null if this step
142 * is not stored in the database.
144 public function get_id() {
145 return $this->id;
148 /** @return question_state The state after this step. */
149 public function get_state() {
150 return $this->state;
154 * Set the state. Normally only called by behaviours.
155 * @param question_state $state one of the {@see question_state} constants.
157 public function set_state($state) {
158 $this->state = $state;
162 * @return null|number the fraction (grade on a scale of
163 * minfraction .. maxfraction, normally 0..1),
164 * or null if this step has not been marked.
166 public function get_fraction() {
167 return $this->fraction;
171 * Set the fraction. Normally only called by behaviours.
172 * @param null|number $fraction the fraction to set.
174 public function set_fraction($fraction) {
175 $this->fraction = $fraction;
178 /** @return int the id of the user resonsible for creating this step. */
179 public function get_user_id() {
180 return $this->userid;
184 * Update full user information for step.
186 * @param stdClass $user Full user object.
187 * @throws coding_exception
189 public function add_full_user_object(stdClass $user): void {
190 if ($user->id != $this->userid) {
191 throw new coding_exception('Wrong user passed to add_full_user_object');
193 $this->user = $user;
197 * Return the full user object.
199 * @return stdClass Get full user object.
201 public function get_user(): stdClass {
202 return $this->user;
206 * Get full name of user who did action.
208 * @return string full name of user.
210 public function get_user_fullname(): string {
211 return fullname($this->user);
214 /** @return int the timestamp when this step was created. */
215 public function get_timecreated() {
216 return $this->timecreated;
220 * @param string $name the name of a question type variable to look for in the submitted data.
221 * @return bool whether a variable with this name exists in the question type data.
223 public function has_qt_var($name) {
224 return array_key_exists($name, $this->data);
228 * @param string $name the name of a question type variable to look for in the submitted data.
229 * @return string the requested variable, or null if the variable is not set.
231 public function get_qt_var($name) {
232 if (!$this->has_qt_var($name)) {
233 return null;
235 return $this->data[$name];
239 * Set a cached question type variable.
240 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
241 * @param string $value the value to set.
243 public function set_qt_var($name, $value) {
244 if ($name[0] != '_') {
245 throw new coding_exception('Cannot set question type data ' . $name .
246 ' on an attempt step. You can only set variables with names begining with _.');
248 $this->data[$name] = $value;
252 * Get the latest set of files for a particular question type variable of
253 * type question_attempt::PARAM_FILES.
255 * @param string $name the name of the associated variable.
256 * @param int $contextid contextid of the question attempt
257 * @return array of {@see stored_files}.
259 public function get_qt_files($name, $contextid) {
260 if (array_key_exists($name, $this->files)) {
261 return $this->files[$name];
264 if (!$this->has_qt_var($name)) {
265 $this->files[$name] = array();
266 return array();
269 $fs = get_file_storage();
270 $filearea = question_file_saver::clean_file_area_name('response_' . $name);
271 $this->files[$name] = $fs->get_area_files($contextid, 'question',
272 $filearea, $this->id, 'sortorder', false);
274 return $this->files[$name];
278 * Prepare a draft file are for the files belonging the a response variable
279 * of this step.
281 * @param string $name the variable name the files belong to.
282 * @param int $contextid the id of the context the quba belongs to.
283 * @return int the draft itemid.
285 public function prepare_response_files_draft_itemid($name, $contextid) {
286 list($draftid, $notused) = $this->prepare_response_files_draft_itemid_with_text(
287 $name, $contextid, null);
288 return $draftid;
292 * Prepare a draft file are for the files belonging the a response variable
293 * of this step, while rewriting the URLs in some text.
295 * @param string $name the variable name the files belong to.
296 * @param int $contextid the id of the context the quba belongs to.
297 * @param string|null $text the text to update the URLs in.
298 * @return array(int, string) the draft itemid and the text with URLs rewritten.
300 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
301 $filearea = question_file_saver::clean_file_area_name('response_' . $name);
302 $draftid = 0; // Will be filled in by file_prepare_draft_area.
303 $newtext = file_prepare_draft_area($draftid, $contextid, 'question',
304 $filearea, $this->id, null, $text);
305 return array($draftid, $newtext);
309 * Rewrite the @@PLUGINFILE@@ tokens in a response variable from this step
310 * that contains links to file. Normally you should probably call
311 * {@see question_attempt::rewrite_response_pluginfile_urls()} instead of
312 * calling this method directly.
314 * @param string $text the text to update the URLs in.
315 * @param int $contextid the id of the context the quba belongs to.
316 * @param string $name the variable name the files belong to.
317 * @param array $extras extra file path components.
318 * @return string the rewritten text.
320 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
321 $filearea = question_file_saver::clean_file_area_name('response_' . $name);
322 return question_rewrite_question_urls($text, 'pluginfile.php', $contextid,
323 'question', $filearea, $extras, $this->id);
327 * Get all the question type variables.
328 * @param array name => value pairs.
330 public function get_qt_data() {
331 $result = array();
332 foreach ($this->data as $name => $value) {
333 if ($name[0] != '-' && $name[0] != ':') {
334 $result[$name] = $value;
337 return $result;
341 * @param string $name the name of a behaviour variable to look for in the submitted data.
342 * @return bool whether a variable with this name exists in the question type data.
344 public function has_behaviour_var($name) {
345 return array_key_exists('-' . $name, $this->data);
349 * @param string $name the name of a behaviour variable to look for in the submitted data.
350 * @return string the requested variable, or null if the variable is not set.
352 public function get_behaviour_var($name) {
353 if (!$this->has_behaviour_var($name)) {
354 return null;
356 return $this->data['-' . $name];
360 * Set a cached behaviour variable.
361 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
362 * @param string $value the value to set.
364 public function set_behaviour_var($name, $value) {
365 if ($name[0] != '_') {
366 throw new coding_exception('Cannot set question type data ' . $name .
367 ' on an attempt step. You can only set variables with names begining with _.');
369 return $this->data['-' . $name] = $value;
373 * Get all the behaviour variables.
375 * @return array name => value pairs. NOTE! the name has the leading - stripped off.
376 * (If you don't understand the note, read the comment at the top of this class :-))
378 public function get_behaviour_data() {
379 $result = array();
380 foreach ($this->data as $name => $value) {
381 if ($name[0] == '-') {
382 $result[substr($name, 1)] = $value;
385 return $result;
389 * Get all the submitted data, but not the cached data. behaviour
390 * variables have the - at the start of their name. This is only really
391 * intended for use by {@see question_attempt::regrade()}, it should not
392 * be considered part of the public API.
393 * @param array name => value pairs.
395 public function get_submitted_data() {
396 $result = array();
397 foreach ($this->data as $name => $value) {
398 if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
399 continue;
401 $result[$name] = $value;
403 return $result;
407 * Get all the data. behaviour variables have the - at the start of
408 * their name. This is only intended for internal use, for example by
409 * {@see question_engine_data_mapper::insert_question_attempt_step()},
410 * however, it can occasionally be useful in test code. It should not be
411 * considered part of the public API of this class.
412 * @param array name => value pairs.
414 public function get_all_data() {
415 return $this->data;
419 * Set a metadata variable.
421 * Do not call this method directly from your code. It is for internal
422 * use only. You should call {@see question_usage::set_question_attempt_metadata()}.
424 * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
425 * @param string $value the value to set.
427 public function set_metadata_var($name, $value) {
428 $this->data[':_' . $name] = $value;
432 * Whether this step has a metadata variable.
434 * Do not call this method directly from your code. It is for internal
435 * use only. You should call {@see question_usage::get_question_attempt_metadata()}.
437 * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
438 * @return bool the value to set previously, or null if this variable was never set.
440 public function has_metadata_var($name) {
441 return isset($this->data[':_' . $name]);
445 * Get a metadata variable.
447 * Do not call this method directly from your code. It is for internal
448 * use only. You should call {@see question_usage::get_question_attempt_metadata()}.
450 * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
451 * @return string the value to set previously, or null if this variable was never set.
453 public function get_metadata_var($name) {
454 if (!$this->has_metadata_var($name)) {
455 return null;
457 return $this->data[':_' . $name];
461 * Create a question_attempt_step from records loaded from the database.
462 * @param Iterator $records Raw records loaded from the database.
463 * @param int $stepid The id of the records to extract.
464 * @param string $qtype The question type of which this is an attempt.
465 * If not given, each record must include a qtype field.
466 * @return question_attempt_step The newly constructed question_attempt_step.
468 public static function load_from_records($records, $attemptstepid, $qtype = null) {
469 $currentrec = $records->current();
470 while ($currentrec->attemptstepid != $attemptstepid) {
471 $records->next();
472 if (!$records->valid()) {
473 throw new coding_exception('Question attempt step ' . $attemptstepid .
474 ' not found in the database.');
476 $currentrec = $records->current();
479 $record = $currentrec;
480 $contextid = null;
481 $data = array();
482 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
483 if (!is_null($currentrec->name)) {
484 $data[$currentrec->name] = $currentrec->value;
486 $records->next();
487 if ($records->valid()) {
488 $currentrec = $records->current();
489 } else {
490 $currentrec = false;
494 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
495 $step->state = question_state::get($record->state);
496 $step->id = $record->attemptstepid;
497 if (!is_null($record->fraction)) {
498 $step->fraction = $record->fraction + 0;
501 // This next chunk of code requires getting $contextid and $qtype here.
502 // Somehow, we need to get that information to this point by modifying
503 // all the paths by which this method can be called.
504 // Can we only return files when it's possible? Should there be some kind of warning?
505 if (is_null($qtype)) {
506 $qtype = $record->qtype;
508 foreach (question_bank::get_qtype($qtype)->response_file_areas() as $area) {
509 if (empty($step->data[$area])) {
510 continue;
513 $step->data[$area] = new question_file_loader($step, $area, $step->data[$area], $record->contextid);
516 return $step;
522 * A subclass of {@see question_attempt_step} used when processing a new submission.
524 * When we are processing some new submitted data, which may or may not lead to
525 * a new step being added to the {@see question_usage_by_activity} we create an
526 * instance of this class. which is then passed to the question behaviour and question
527 * type for processing. At the end of processing we then may, or may not, keep it.
529 * @copyright 2010 The Open University
530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
532 class question_attempt_pending_step extends question_attempt_step {
533 /** @var string the new response summary, if there is one. */
534 protected $newresponsesummary = null;
536 /** @var int the new variant number, if there is one. */
537 protected $newvariant = null;
540 * If as a result of processing this step, the response summary for the
541 * question attempt should changed, you should call this method to set the
542 * new summary.
543 * @param string $responsesummary the new response summary.
545 public function set_new_response_summary($responsesummary) {
546 $this->newresponsesummary = $responsesummary;
550 * Get the new response summary, if there is one.
551 * @return string the new response summary, or null if it has not changed.
553 public function get_new_response_summary() {
554 return $this->newresponsesummary;
558 * Whether this processing this step has changed the response summary.
559 * @return bool true if there is a new response summary.
561 public function response_summary_changed() {
562 return !is_null($this->newresponsesummary);
566 * If as a result of processing this step, you identify that this variant of the
567 * question is actually identical to the another one, you may change the
568 * variant number recorded, in order to give better statistics. For an example
569 * see qbehaviour_opaque.
570 * @param int $variant the new variant number.
572 public function set_new_variant_number($variant) {
573 $this->newvariant = $variant;
577 * Get the new variant number, if there is one.
578 * @return int the new variant number, or null if it has not changed.
580 public function get_new_variant_number() {
581 return $this->newvariant;
585 * Whether this processing this step has changed the variant number.
586 * @return bool true if there is a new variant number.
588 public function variant_number_changed() {
589 return !is_null($this->newvariant);
595 * A subclass of {@see question_attempt_step} that cannot be modified.
597 * @copyright 2009 The Open University
598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
600 class question_attempt_step_read_only extends question_attempt_step {
601 public function set_state($state) {
602 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
604 public function set_fraction($fraction) {
605 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
607 public function set_qt_var($name, $value) {
608 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
610 public function set_behaviour_var($name, $value) {
611 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
617 * A null {@see question_attempt_step} returned from
618 * {@see question_attempt::get_last_step()} etc. when a an attempt has just been
619 * created and there is no actual step.
621 * @copyright 2009 The Open University
622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
624 class question_null_step {
625 public function get_state() {
626 return question_state::$notstarted;
629 public function set_state($state) {
630 throw new coding_exception('This question has not been started.');
633 public function get_fraction() {
634 return null;
640 * This is an adapter class that wraps a {@see question_attempt_step} and
641 * modifies the get/set_*_data methods so that they operate only on the parts
642 * that belong to a particular subquestion, as indicated by an extra prefix.
644 * @copyright 2010 The Open University
645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 class question_attempt_step_subquestion_adapter extends question_attempt_step {
648 /** @var question_attempt_step the step we are wrapping. */
649 protected $realstep;
650 /** @var string the exta prefix on fields we work with. */
651 protected $extraprefix;
654 * Constructor.
655 * @param question_attempt_step $realstep the step to wrap. (Can be null if you
656 * just want to call add/remove.prefix.)
657 * @param string $extraprefix the extra prefix that is used for date fields.
659 public function __construct($realstep, $extraprefix) {
660 $this->realstep = $realstep;
661 $this->extraprefix = $extraprefix;
665 * Add the extra prefix to a field name.
666 * @param string $field the plain field name.
667 * @return string the field name with the extra bit of prefix added.
669 public function add_prefix($field) {
670 if (substr($field, 0, 2) === '-_') {
671 return '-_' . $this->extraprefix . substr($field, 2);
672 } else if (substr($field, 0, 1) === '-') {
673 return '-' . $this->extraprefix . substr($field, 1);
674 } else if (substr($field, 0, 1) === '_') {
675 return '_' . $this->extraprefix . substr($field, 1);
676 } else {
677 return $this->extraprefix . $field;
682 * Remove the extra prefix from a field name if it is present.
683 * @param string $field the extended field name.
684 * @return string the field name with the extra bit of prefix removed, or
685 * null if the extre prefix was not present.
687 public function remove_prefix($field) {
688 if (preg_match('~^(-?_?)' . preg_quote($this->extraprefix, '~') . '(.*)$~', $field, $matches)) {
689 return $matches[1] . $matches[2];
690 } else {
691 return null;
696 * Filter some data to keep only those entries where the key contains
697 * extraprefix, and remove the extra prefix from the reutrned arrary.
698 * @param array $data some of the data stored in this step.
699 * @return array the data with the keys ajusted using {@see remove_prefix()}.
701 public function filter_array($data) {
702 $result = array();
703 foreach ($data as $fullname => $value) {
704 if ($name = $this->remove_prefix($fullname)) {
705 $result[$name] = $value;
708 return $result;
711 public function get_state() {
712 return $this->realstep->get_state();
715 public function set_state($state) {
716 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
719 public function get_fraction() {
720 return $this->realstep->get_fraction();
723 public function set_fraction($fraction) {
724 throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
727 public function get_user_id() {
728 return $this->realstep->get_user_id();
731 public function get_timecreated() {
732 return $this->realstep->get_timecreated();
735 public function has_qt_var($name) {
736 return $this->realstep->has_qt_var($this->add_prefix($name));
739 public function get_qt_var($name) {
740 return $this->realstep->get_qt_var($this->add_prefix($name));
743 public function set_qt_var($name, $value) {
744 $this->realstep->set_qt_var($this->add_prefix($name), $value);
747 public function get_qt_data() {
748 return $this->filter_array($this->realstep->get_qt_data());
751 public function has_behaviour_var($name) {
752 return $this->realstep->has_behaviour_var($this->add_prefix($name));
755 public function get_behaviour_var($name) {
756 return $this->realstep->get_behaviour_var($this->add_prefix($name));
759 public function set_behaviour_var($name, $value) {
760 return $this->realstep->set_behaviour_var($this->add_prefix($name), $value);
763 public function get_behaviour_data() {
764 return $this->filter_array($this->realstep->get_behaviour_data());
767 public function get_submitted_data() {
768 return $this->filter_array($this->realstep->get_submitted_data());
771 public function get_all_data() {
772 return $this->filter_array($this->realstep->get_all_data());
775 public function get_qt_files($name, $contextid) {
776 throw new coding_exception('No attempt has yet been made to implement files support in ' .
777 'question_attempt_step_subquestion_adapter.');
780 public function prepare_response_files_draft_itemid($name, $contextid) {
781 throw new coding_exception('No attempt has yet been made to implement files support in ' .
782 'question_attempt_step_subquestion_adapter.');
785 public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
786 throw new coding_exception('No attempt has yet been made to implement files support in ' .
787 'question_attempt_step_subquestion_adapter.');
790 public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
791 throw new coding_exception('No attempt has yet been made to implement files support in ' .
792 'question_attempt_step_subquestion_adapter.');