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.
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 maxfraction, 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 {
67    /**
68     * @var integer if this attempts is stored in the question_attempts table,
69     * the id of that row.
70     */
71    private $id = null;
72
73    /**
74     * @var question_state one of the {@link question_state} constants.
75     * The state after this step.
76     */
77    private $state;
78
79    /**
80     * @var null|number the fraction (grade on a scale of
81     * minfraction .. maxfraction, normally 0..1) or null.
82     */
83    private $fraction = null;
84
85    /** @var integer the timestamp when this step was created. */
86    private $timecreated;
87
88    /** @var integer the id of the user resonsible for creating this step. */
89    private $userid;
90
91    /** @var array name => value pairs. The submitted data. */
92    private $data;
93
94    /** @var array name => array of {@link stored_file}s. Caches the contents of file areas. */
95    private $files = array();
96
97    /**
98     * You should not need to call this constructor in your own code. Steps are
99     * normally created by {@link question_attempt} methods like
100     * {@link question_attempt::process_action()}.
101     * @param array $data the submitted data that defines this step.
102     * @param int $timestamp the time to record for the action. (If not given, use now.)
103     * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
104     * @param int $existingstepid if this step is going to replace an existing step
105     *      (for example, during a regrade) this is the id of the previous step we are replacing.
106     */
107    public function __construct($data = array(), $timecreated = null, $userid = null,
108            $existingstepid = null) {
109        global $USER;
110
111        if (!is_array($data)) {
112            throw new coding_exception('$data must be an array when constructing a question_attempt_step.');
113        }
114        $this->state = question_state::$unprocessed;
115        $this->data = $data;
116        if (is_null($timecreated)) {
117            $this->timecreated = time();
118        } else {
119            $this->timecreated = $timecreated;
120        }
121        if (is_null($userid)) {
122            $this->userid = $USER->id;
123        } else {
124            $this->userid = $userid;
125        }
126
127        if (!is_null($existingstepid)) {
128            $this->id = $existingstepid;
129        }
130    }
131
132    /**
133     * @return int|null The id of this step in the database. null if this step
134     * is not stored in the database.
135     */
136    public function get_id() {
137        return $this->id;
138    }
139
140    /** @return question_state The state after this step. */
141    public function get_state() {
142        return $this->state;
143    }
144
145    /**
146     * Set the state. Normally only called by behaviours.
147     * @param question_state $state one of the {@link question_state} constants.
148     */
149    public function set_state($state) {
150        $this->state = $state;
151    }
152
153    /**
154     * @return null|number the fraction (grade on a scale of
155     * minfraction .. maxfraction, normally 0..1),
156     * or null if this step has not been marked.
157     */
158    public function get_fraction() {
159        return $this->fraction;
160    }
161
162    /**
163     * Set the fraction. Normally only called by behaviours.
164     * @param null|number $fraction the fraction to set.
165     */
166    public function set_fraction($fraction) {
167        $this->fraction = $fraction;
168    }
169
170    /** @return int the id of the user resonsible for creating this step. */
171    public function get_user_id() {
172        return $this->userid;
173    }
174
175    /** @return int the timestamp when this step was created. */
176    public function get_timecreated() {
177        return $this->timecreated;
178    }
179
180    /**
181     * @param string $name the name of a question type variable to look for in the submitted data.
182     * @return bool whether a variable with this name exists in the question type data.
183     */
184    public function has_qt_var($name) {
185        return array_key_exists($name, $this->data);
186    }
187
188    /**
189     * @param string $name the name of a question type variable to look for in the submitted data.
190     * @return string the requested variable, or null if the variable is not set.
191     */
192    public function get_qt_var($name) {
193        if (!$this->has_qt_var($name)) {
194            return null;
195        }
196        return $this->data[$name];
197    }
198
199    /**
200     * Set a cached question type variable.
201     * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
202     * @param string $value the value to set.
203     */
204    public function set_qt_var($name, $value) {
205        if ($name[0] != '_') {
206            throw new coding_exception('Cannot set question type data ' . $name .
207                    ' on an attempt step. You can only set variables with names begining with _.');
208        }
209        $this->data[$name] = $value;
210    }
211
212    /**
213     * Get the latest set of files for a particular question type variable of
214     * type question_attempt::PARAM_FILES.
215     *
216     * @param string $name the name of the associated variable.
217     * @return array of {@link stored_files}.
218     */
219    public function get_qt_files($name, $contextid) {
220        if (array_key_exists($name, $this->files)) {
221            return $this->files[$name];
222        }
223
224        if (!$this->has_qt_var($name)) {
225            $this->files[$name] = array();
226            return array();
227        }
228
229        $fs = get_file_storage();
230        $this->files[$name] = $fs->get_area_files($contextid, 'question',
231                'response_' . $name, $this->id, 'sortorder', false);
232
233        return $this->files[$name];
234    }
235
236    /**
237     * Prepare a draft file are for the files belonging the a response variable
238     * of this step.
239     *
240     * @param string $name the variable name the files belong to.
241     * @param int $contextid the id of the context the quba belongs to.
242     * @return int the draft itemid.
243     */
244    public function prepare_response_files_draft_itemid($name, $contextid) {
245        list($draftid, $notused) = $this->prepare_response_files_draft_itemid_with_text(
246                $name, $contextid, null);
247        return $draftid;
248    }
249
250    /**
251     * Prepare a draft file are for the files belonging the a response variable
252     * of this step, while rewriting the URLs in some text.
253     *
254     * @param string $name the variable name the files belong to.
255     * @param int $contextid the id of the context the quba belongs to.
256     * @param string $text the text to update the URLs in.
257     * @return array(int, string) the draft itemid and the text with URLs rewritten.
258     */
259    public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
260        $draftid = 0; // Will be filled in by file_prepare_draft_area.
261        $newtext = file_prepare_draft_area($draftid, $contextid, 'question',
262                'response_' . $name, $this->id, null, $text);
263        return array($draftid, $newtext);
264    }
265
266    /**
267     * Rewrite the @@PLUGINFILE@@ tokens in a response variable from this step
268     * that contains links to file. Normally you should probably call
269     * {@link question_attempt::rewrite_response_pluginfile_urls()} instead of
270     * calling this method directly.
271     *
272     * @param string $text the text to update the URLs in.
273     * @param int $contextid the id of the context the quba belongs to.
274     * @param string $name the variable name the files belong to.
275     * @param array $extra extra file path components.
276     * @return string the rewritten text.
277     */
278    public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
279        return question_rewrite_question_urls($text, 'pluginfile.php', $contextid,
280                'question', 'response_' . $name, $extras, $this->id);
281    }
282
283    /**
284     * Get all the question type variables.
285     * @param array name => value pairs.
286     */
287    public function get_qt_data() {
288        $result = array();
289        foreach ($this->data as $name => $value) {
290            if ($name[0] != '-' && $name[0] != ':') {
291                $result[$name] = $value;
292            }
293        }
294        return $result;
295    }
296
297    /**
298     * @param string $name the name of a behaviour variable to look for in the submitted data.
299     * @return bool whether a variable with this name exists in the question type data.
300     */
301    public function has_behaviour_var($name) {
302        return array_key_exists('-' . $name, $this->data);
303    }
304
305    /**
306     * @param string $name the name of a behaviour variable to look for in the submitted data.
307     * @return string the requested variable, or null if the variable is not set.
308     */
309    public function get_behaviour_var($name) {
310        if (!$this->has_behaviour_var($name)) {
311            return null;
312        }
313        return $this->data['-' . $name];
314    }
315
316    /**
317     * Set a cached behaviour variable.
318     * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
319     * @param string $value the value to set.
320     */
321    public function set_behaviour_var($name, $value) {
322        if ($name[0] != '_') {
323            throw new coding_exception('Cannot set question type data ' . $name .
324                    ' on an attempt step. You can only set variables with names begining with _.');
325        }
326        return $this->data['-' . $name] = $value;
327    }
328
329    /**
330     * Get all the behaviour variables.
331     * @param array name => value pairs.
332     */
333    public function get_behaviour_data() {
334        $result = array();
335        foreach ($this->data as $name => $value) {
336            if ($name[0] == '-') {
337                $result[substr($name, 1)] = $value;
338            }
339        }
340        return $result;
341    }
342
343    /**
344     * Get all the submitted data, but not the cached data. behaviour
345     * variables have the - at the start of their name. This is only really
346     * intended for use by {@link question_attempt::regrade()}, it should not
347     * be considered part of the public API.
348     * @param array name => value pairs.
349     */
350    public function get_submitted_data() {
351        $result = array();
352        foreach ($this->data as $name => $value) {
353            if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
354                continue;
355            }
356            $result[$name] = $value;
357        }
358        return $result;
359    }
360
361    /**
362     * Get all the data. behaviour variables have the - at the start of
363     * their name. This is only intended for internal use, for example by
364     * {@link question_engine_data_mapper::insert_question_attempt_step()},
365     * however, it can occasionally be useful in test code. It should not be
366     * considered part of the public API of this class.
367     * @param array name => value pairs.
368     */
369    public function get_all_data() {
370        return $this->data;
371    }
372
373    /**
374     * Set a metadata variable.
375     *
376     * Do not call this method directly from  your code. It is for internal
377     * use only. You should call {@link question_usage::set_question_attempt_metadata()}.
378     *
379     * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
380     * @param string $value the value to set.
381     */
382    public function set_metadata_var($name, $value) {
383        $this->data[':_' . $name] = $value;
384    }
385
386    /**
387     * Whether this step has a metadata variable.
388     *
389     * Do not call this method directly from  your code. It is for internal
390     * use only. You should call {@link question_usage::get_question_attempt_metadata()}.
391     *
392     * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
393     * @return bool the value to set previously, or null if this variable was never set.
394     */
395    public function has_metadata_var($name) {
396        return isset($this->data[':_' . $name]);
397    }
398
399    /**
400     * Get a metadata variable.
401     *
402     * Do not call this method directly from  your code. It is for internal
403     * use only. You should call {@link question_usage::get_question_attempt_metadata()}.
404     *
405     * @param string $name the name of the variable to set. [a-z][a-z0-9]*.
406     * @return string the value to set previously, or null if this variable was never set.
407     */
408    public function get_metadata_var($name) {
409        if (!$this->has_metadata_var($name)) {
410            return null;
411        }
412        return $this->data[':_' . $name];
413    }
414
415    /**
416     * Create a question_attempt_step from records loaded from the database.
417     * @param Iterator $records Raw records loaded from the database.
418     * @param int $stepid The id of the records to extract.
419     * @param string $qtype The question type of which this is an attempt.
420     *      If not given, each record must include a qtype field.
421     * @return question_attempt_step The newly constructed question_attempt_step.
422     */
423    public static function load_from_records($records, $attemptstepid, $qtype = null) {
424        $currentrec = $records->current();
425        while ($currentrec->attemptstepid != $attemptstepid) {
426            $records->next();
427            if (!$records->valid()) {
428                throw new coding_exception('Question attempt step ' . $attemptstepid .
429                        ' not found in the database.');
430            }
431            $currentrec = $records->current();
432        }
433
434        $record = $currentrec;
435        $contextid = null;
436        $data = array();
437        while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
438            if (!is_null($currentrec->name)) {
439                $data[$currentrec->name] = $currentrec->value;
440            }
441            $records->next();
442            if ($records->valid()) {
443                $currentrec = $records->current();
444            } else {
445                $currentrec = false;
446            }
447        }
448
449        $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
450        $step->state = question_state::get($record->state);
451        $step->id = $record->attemptstepid;
452        if (!is_null($record->fraction)) {
453            $step->fraction = $record->fraction + 0;
454        }
455
456        // This next chunk of code requires getting $contextid and $qtype here.
457        // Somehow, we need to get that information to this point by modifying
458        // all the paths by which this method can be called.
459        // Can we only return files when it's possible? Should there be some kind of warning?
460        if (is_null($qtype)) {
461            $qtype = $record->qtype;
462        }
463        foreach (question_bank::get_qtype($qtype)->response_file_areas() as $area) {
464            if (empty($step->data[$area])) {
465                continue;
466            }
467
468            $step->data[$area] = new question_file_loader($step, $area, $step->data[$area], $record->contextid);
469        }
470
471        return $step;
472    }
473}
474
475
476/**
477 * A subclass of {@link question_attempt_step} used when processing a new submission.
478 *
479 * When we are processing some new submitted data, which may or may not lead to
480 * a new step being added to the {@link question_usage_by_activity} we create an
481 * instance of this class. which is then passed to the question behaviour and question
482 * type for processing. At the end of processing we then may, or may not, keep it.
483 *
484 * @copyright  2010 The Open University
485 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
486 */
487class question_attempt_pending_step extends question_attempt_step {
488    /** @var string the new response summary, if there is one. */
489    protected $newresponsesummary = null;
490
491    /** @var int the new variant number, if there is one. */
492    protected $newvariant = null;
493
494    /**
495     * If as a result of processing this step, the response summary for the
496     * question attempt should changed, you should call this method to set the
497     * new summary.
498     * @param string $responsesummary the new response summary.
499     */
500    public function set_new_response_summary($responsesummary) {
501        $this->newresponsesummary = $responsesummary;
502    }
503
504    /**
505     * Get the new response summary, if there is one.
506     * @return string the new response summary, or null if it has not changed.
507     */
508    public function get_new_response_summary() {
509        return $this->newresponsesummary;
510    }
511
512    /**
513     * Whether this processing this step has changed the response summary.
514     * @return bool true if there is a new response summary.
515     */
516    public function response_summary_changed() {
517        return !is_null($this->newresponsesummary);
518    }
519
520    /**
521     * If as a result of processing this step, you identify that this variant of the
522     * question is actually identical to the another one, you may change the
523     * variant number recorded, in order to give better statistics. For an example
524     * see qbehaviour_opaque.
525     * @param int $variant the new variant number.
526     */
527    public function set_new_variant_number($variant) {
528        $this->newvariant = $variant;
529    }
530
531    /**
532     * Get the new variant number, if there is one.
533     * @return int the new variant number, or null if it has not changed.
534     */
535    public function get_new_variant_number() {
536        return $this->newvariant;
537    }
538
539    /**
540     * Whether this processing this step has changed the variant number.
541     * @return bool true if there is a new variant number.
542     */
543    public function variant_number_changed() {
544        return !is_null($this->newvariant);
545    }
546}
547
548
549/**
550 * A subclass of {@link question_attempt_step} that cannot be modified.
551 *
552 * @copyright  2009 The Open University
553 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
554 */
555class question_attempt_step_read_only extends question_attempt_step {
556    public function set_state($state) {
557        throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
558    }
559    public function set_fraction($fraction) {
560        throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
561    }
562    public function set_qt_var($name, $value) {
563        throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
564    }
565    public function set_behaviour_var($name, $value) {
566        throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
567    }
568}
569
570
571/**
572 * A null {@link question_attempt_step} returned from
573 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
574 * created and there is no actual step.
575 *
576 * @copyright  2009 The Open University
577 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
578 */
579class question_null_step {
580    public function get_state() {
581        return question_state::$notstarted;
582    }
583
584    public function set_state($state) {
585        throw new coding_exception('This question has not been started.');
586    }
587
588    public function get_fraction() {
589        return null;
590    }
591}
592
593
594/**
595 * This is an adapter class that wraps a {@link question_attempt_step} and
596 * modifies the get/set_*_data methods so that they operate only on the parts
597 * that belong to a particular subquestion, as indicated by an extra prefix.
598 *
599 * @copyright  2010 The Open University
600 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
601 */
602class question_attempt_step_subquestion_adapter extends question_attempt_step {
603    /** @var question_attempt_step the step we are wrapping. */
604    protected $realstep;
605    /** @var string the exta prefix on fields we work with. */
606    protected $extraprefix;
607
608    /**
609     * Constructor.
610     * @param question_attempt_step $realqas the step to wrap. (Can be null if you
611     *      just want to call add/remove.prefix.)
612     * @param unknown_type $extraprefix the extra prefix that is used for date fields.
613     */
614    public function __construct($realqas, $extraprefix) {
615        $this->realqas = $realqas;
616        $this->extraprefix = $extraprefix;
617    }
618
619    /**
620     * Add the extra prefix to a field name.
621     * @param string $field the plain field name.
622     * @return string the field name with the extra bit of prefix added.
623     */
624    public function add_prefix($field) {
625        if (substr($field, 0, 2) === '!_') {
626            return '-_' . $this->extraprefix . substr($field, 2);
627        } else if (substr($field, 0, 1) === '-') {
628            return '-' . $this->extraprefix . substr($field, 1);
629        } else if (substr($field, 0, 1) === '_') {
630            return '_' . $this->extraprefix . substr($field, 1);
631        } else {
632            return $this->extraprefix . $field;
633        }
634    }
635
636    /**
637     * Remove the extra prefix from a field name if it is present.
638     * @param string $field the extended field name.
639     * @return string the field name with the extra bit of prefix removed, or
640     * null if the extre prefix was not present.
641     */
642    public function remove_prefix($field) {
643        if (preg_match('~^(-?_?)' . preg_quote($this->extraprefix, '~') . '(.*)$~', $field, $matches)) {
644            return $matches[1] . $matches[2];
645        } else {
646            return null;
647        }
648    }
649
650    /**
651     * Filter some data to keep only those entries where the key contains
652     * extraprefix, and remove the extra prefix from the reutrned arrary.
653     * @param array $data some of the data stored in this step.
654     * @return array the data with the keys ajusted using {@link remove_prefix()}.
655     */
656    public function filter_array($data) {
657        $result = array();
658        foreach ($data as $fullname => $value) {
659            if ($name = $this->remove_prefix($fullname)) {
660                $result[$name] = $value;
661            }
662        }
663        return $result;
664    }
665
666    public function get_state() {
667        return $this->realqas->get_state();
668    }
669
670    public function set_state($state) {
671        throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
672    }
673
674    public function get_fraction() {
675        return $this->realqas->get_fraction();
676    }
677
678    public function set_fraction($fraction) {
679        throw new coding_exception('Cannot modify a question_attempt_step_subquestion_adapter.');
680    }
681
682    public function get_user_id() {
683        return $this->realqas->get_user_id;
684    }
685
686    public function get_timecreated() {
687        return $this->realqas->get_timecreated();
688    }
689
690    public function has_qt_var($name) {
691        return $this->realqas->has_qt_var($this->add_prefix($name));
692    }
693
694    public function get_qt_var($name) {
695        return $this->realqas->get_qt_var($this->add_prefix($name));
696    }
697
698    public function set_qt_var($name, $value) {
699        return $this->realqas->set_qt_var($this->add_prefix($name), $value);
700    }
701
702    public function get_qt_data() {
703        return $this->filter_array($this->realqas->get_qt_data());
704    }
705
706    public function has_behaviour_var($name) {
707        return $this->realqas->has_im_var($this->add_prefix($name));
708    }
709
710    public function get_behaviour_var($name) {
711        return $this->realqas->get_im_var($this->add_prefix($name));
712    }
713
714    public function set_behaviour_var($name, $value) {
715        return $this->realqas->set_im_var($this->add_prefix($name), $value);
716    }
717
718    public function get_behaviour_data() {
719        return $this->filter_array($this->realqas->get_behaviour_data());
720    }
721
722    public function get_submitted_data() {
723        return $this->filter_array($this->realqas->get_submitted_data());
724    }
725
726    public function get_all_data() {
727        return $this->filter_array($this->realqas->get_all_data());
728    }
729
730    public function get_qt_files($name, $contextid) {
731        throw new coding_exception('No attempt has yet been made to implement files support in ' .
732                'question_attempt_step_subquestion_adapter.');
733    }
734
735    public function prepare_response_files_draft_itemid($name, $contextid) {
736        throw new coding_exception('No attempt has yet been made to implement files support in ' .
737                'question_attempt_step_subquestion_adapter.');
738    }
739
740    public function prepare_response_files_draft_itemid_with_text($name, $contextid, $text) {
741        throw new coding_exception('No attempt has yet been made to implement files support in ' .
742                'question_attempt_step_subquestion_adapter.');
743    }
744
745    public function rewrite_response_pluginfile_urls($text, $contextid, $name, $extras) {
746        throw new coding_exception('No attempt has yet been made to implement files support in ' .
747                'question_attempt_step_subquestion_adapter.');
748    }
749}
750