MDL-20636 Can now display the attachments to an essay question that has attachments.
[moodle.git] / question / engine / lib.php
CommitLineData
d1b7e03d
TH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This defines the core classes of the Moodle question engine.
20 *
017bc1d9 21 * @package moodlecore
d1b7e03d 22 * @subpackage questionengine
017bc1d9
TH
23 * @copyright 2009 The Open University
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
25 */
26
27
a17b297d
TH
28defined('MOODLE_INTERNAL') || die();
29
d1b7e03d
TH
30require_once(dirname(__FILE__) . '/states.php');
31require_once(dirname(__FILE__) . '/datalib.php');
32require_once(dirname(__FILE__) . '/renderer.php');
33require_once(dirname(__FILE__) . '/bank.php');
34require_once(dirname(__FILE__) . '/../type/questiontype.php');
35require_once(dirname(__FILE__) . '/../type/questionbase.php');
36require_once(dirname(__FILE__) . '/../type/rendererbase.php');
37require_once(dirname(__FILE__) . '/../behaviour/behaviourbase.php');
38require_once(dirname(__FILE__) . '/../behaviour/rendererbase.php');
39require_once($CFG->libdir . '/questionlib.php');
40
41
42/**
43 * This static class provides access to the other question engine classes.
44 *
45 * It provides functions for managing question behaviours), and for
46 * creating, loading, saving and deleting {@link question_usage_by_activity}s,
47 * which is the main class that is used by other code that wants to use questions.
48 *
017bc1d9
TH
49 * @copyright 2009 The Open University
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
51 */
52abstract class question_engine {
53 /** @var array behaviour name => 1. Records which behaviours have been loaded. */
54 private static $loadedbehaviours = array();
55
56 /**
57 * Create a new {@link question_usage_by_activity}. The usage is
58 * created in memory. If you want it to persist, you will need to call
59 * {@link save_questions_usage_by_activity()}.
60 *
61 * @param string $component the plugin creating this attempt. For example mod_quiz.
62 * @param object $context the context this usage belongs to.
63 * @return question_usage_by_activity the newly created object.
64 */
65 public static function make_questions_usage_by_activity($component, $context) {
66 return new question_usage_by_activity($component, $context);
67 }
68
69 /**
70 * Load a {@link question_usage_by_activity} from the database, based on its id.
f7970e3c 71 * @param int $qubaid the id of the usage to load.
d1b7e03d
TH
72 * @return question_usage_by_activity loaded from the database.
73 */
74 public static function load_questions_usage_by_activity($qubaid) {
75 $dm = new question_engine_data_mapper();
76 return $dm->load_questions_usage_by_activity($qubaid);
77 }
78
79 /**
80 * Save a {@link question_usage_by_activity} to the database. This works either
81 * if the usage was newly created by {@link make_questions_usage_by_activity()}
82 * or loaded from the database using {@link load_questions_usage_by_activity()}
83 * @param question_usage_by_activity the usage to save.
84 */
85 public static function save_questions_usage_by_activity(question_usage_by_activity $quba) {
86 $dm = new question_engine_data_mapper();
87 $observer = $quba->get_observer();
88 if ($observer instanceof question_engine_unit_of_work) {
89 $observer->save($dm);
90 } else {
91 $dm->insert_questions_usage_by_activity($quba);
92 }
93 }
94
95 /**
96 * Delete a {@link question_usage_by_activity} from the database, based on its id.
f7970e3c 97 * @param int $qubaid the id of the usage to delete.
d1b7e03d
TH
98 */
99 public static function delete_questions_usage_by_activity($qubaid) {
100 global $CFG;
c76145d3 101 self::delete_questions_usage_by_activities('{question_usages}.id = :qubaid', array('qubaid' => $qubaid));
d1b7e03d
TH
102 }
103
104 /**
2daffca5
TH
105 * Delete {@link question_usage_by_activity}s from the database that match
106 * an arbitrary SQL where clause.
107 * @param string $where a where clause. Becuase of MySQL limitations, you
108 * must refer to {question_usages}.id in full like that.
109 * @param array $params values to substitute for placeholders in $where.
d1b7e03d 110 */
c76145d3 111 public static function delete_questions_usage_by_activities($where, $params) {
d1b7e03d 112 $dm = new question_engine_data_mapper();
c76145d3 113 $dm->delete_questions_usage_by_activities($where, $params);
d1b7e03d
TH
114 }
115
116 /**
117 * Change the maxmark for the question_attempt with number in usage $slot
118 * for all the specified question_attempts.
119 * @param qubaid_condition $qubaids Selects which usages are updated.
f7970e3c 120 * @param int $slot the number is usage to affect.
d1b7e03d
TH
121 * @param number $newmaxmark the new max mark to set.
122 */
123 public static function set_max_mark_in_attempts(qubaid_condition $qubaids,
124 $slot, $newmaxmark) {
125 $dm = new question_engine_data_mapper();
126 $dm->set_max_mark_in_attempts($qubaids, $slot, $newmaxmark);
127 }
128
129 /**
130 * @param array $questionids of question ids.
07f88584
TH
131 * @param qubaid_condition $qubaids ids of the usages to consider.
132 * @return boolean whether any of these questions are being used by any of
133 * those usages.
d1b7e03d 134 */
07f88584
TH
135 public static function questions_in_use(array $questionids, qubaid_condition $qubaids = null) {
136 if (is_null($qubaids)) {
137 return false;
138 }
d1b7e03d 139 $dm = new question_engine_data_mapper();
07f88584 140 return $dm->questions_in_use($questionids, $qubaids);
d1b7e03d
TH
141 }
142
143 /**
144 * Create an archetypal behaviour for a particular question attempt.
145 * Used by {@link question_definition::make_behaviour()}.
146 *
147 * @param string $preferredbehaviour the type of model required.
148 * @param question_attempt $qa the question attempt the model will process.
149 * @return question_behaviour an instance of appropriate behaviour class.
150 */
151 public static function make_archetypal_behaviour($preferredbehaviour, question_attempt $qa) {
152 question_engine::load_behaviour_class($preferredbehaviour);
153 $class = 'qbehaviour_' . $preferredbehaviour;
154 if (!constant($class . '::IS_ARCHETYPAL')) {
88f0eb15 155 throw new coding_exception('The requested behaviour is not actually an archetypal one.');
d1b7e03d
TH
156 }
157 return new $class($qa, $preferredbehaviour);
158 }
159
160 /**
161 * @param string $behaviour the name of a behaviour.
162 * @return array of {@link question_display_options} field names, that are
163 * not relevant to this behaviour before a 'finish' action.
164 */
165 public static function get_behaviour_unused_display_options($behaviour) {
166 self::load_behaviour_class($behaviour);
167 $class = 'qbehaviour_' . $behaviour;
168 if (!method_exists($class, 'get_unused_display_options')) {
169 return question_behaviour::get_unused_display_options();
170 }
171 return call_user_func(array($class, 'get_unused_display_options'));
172 }
173
174 /**
175 * Create an behaviour for a particular type. If that type cannot be
176 * found, return an instance of qbehaviour_missing.
177 *
178 * Normally you should use {@link make_archetypal_behaviour()}, or
179 * call the constructor of a particular model class directly. This method
180 * is only intended for use by {@link question_attempt::load_from_records()}.
181 *
182 * @param string $behaviour the type of model to create.
183 * @param question_attempt $qa the question attempt the model will process.
184 * @param string $preferredbehaviour the preferred behaviour for the containing usage.
185 * @return question_behaviour an instance of appropriate behaviour class.
186 */
187 public static function make_behaviour($behaviour, question_attempt $qa, $preferredbehaviour) {
188 try {
189 self::load_behaviour_class($behaviour);
190 } catch (Exception $e) {
191 question_engine::load_behaviour_class('missing');
192 return new qbehaviour_missing($qa, $preferredbehaviour);
193 }
194 $class = 'qbehaviour_' . $behaviour;
195 return new $class($qa, $preferredbehaviour);
196 }
197
198 /**
199 * Load the behaviour class(es) belonging to a particular model. That is,
200 * include_once('/question/behaviour/' . $behaviour . '/behaviour.php'), with a bit
201 * of checking.
202 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
203 */
204 public static function load_behaviour_class($behaviour) {
205 global $CFG;
206 if (isset(self::$loadedbehaviours[$behaviour])) {
207 return;
208 }
209 $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviour.php';
210 if (!is_readable($file)) {
88f0eb15 211 throw new coding_exception('Unknown question behaviour ' . $behaviour);
d1b7e03d
TH
212 }
213 include_once($file);
214 self::$loadedbehaviours[$behaviour] = 1;
215 }
216
217 /**
218 * Return an array where the keys are the internal names of the archetypal
219 * behaviours, and the values are a human-readable name. An
220 * archetypal behaviour is one that is suitable to pass the name of to
221 * {@link question_usage_by_activity::set_preferred_behaviour()}.
222 *
223 * @return array model name => lang string for this behaviour name.
224 */
225 public static function get_archetypal_behaviours() {
226 $archetypes = array();
227 $behaviours = get_list_of_plugins('question/behaviour');
228 foreach ($behaviours as $path) {
229 $behaviour = basename($path);
230 self::load_behaviour_class($behaviour);
231 $plugin = 'qbehaviour_' . $behaviour;
232 if (constant($plugin . '::IS_ARCHETYPAL')) {
233 $archetypes[$behaviour] = self::get_behaviour_name($behaviour);
234 }
235 }
236 asort($archetypes, SORT_LOCALE_STRING);
237 return $archetypes;
238 }
239
240 /**
241 * Return an array where the keys are the internal names of the behaviours
242 * in preferred order and the values are a human-readable name.
243 *
244 * @param array $archetypes, array of behaviours
245 * @param string $questionbehavioursorder, a comma separated list of behaviour names
246 * @param string $questionbehavioursdisabled, a comma separated list of behaviour names
247 * @param string $currentbahaviour, current behaviour name
248 * @return array model name => lang string for this behaviour name.
249 */
250 public static function sort_behaviours($archetypes, $questionbehavioursorder,
251 $questionbehavioursdisabled, $currentbahaviour) {
252 $behaviourorder = array();
253 $behaviourdisabled = array();
254
255 // Get disabled behaviours
256 if ($questionbehavioursdisabled) {
257 $behaviourdisabledtemp = preg_split('/[\s,;]+/', $questionbehavioursdisabled);
258 } else {
259 $behaviourdisabledtemp = array();
260 }
261
262 if ($questionbehavioursorder) {
263 $behaviourordertemp = preg_split('/[\s,;]+/', $questionbehavioursorder);
264 } else {
265 $behaviourordertemp = array();
266 }
267
268 foreach ($behaviourdisabledtemp as $key) {
269 if (array_key_exists($key, $archetypes)) {
270 // Do not disable the current behaviour
271 if ($key != $currentbahaviour) {
272 $behaviourdisabled[$key] = $archetypes[$key];
273 }
274 }
275 }
276
277 // Get behaviours in preferred order
278 foreach ($behaviourordertemp as $key) {
279 if (array_key_exists($key, $archetypes)) {
280 $behaviourorder[$key] = $archetypes[$key];
281 }
282 }
283 // Get the rest of behaviours and sort them alphabetically
284 $leftover = array_diff_key($archetypes, $behaviourdisabled, $behaviourorder);
285 asort($leftover, SORT_LOCALE_STRING);
286
287 // Set up the final order to be displayed
288 $finalorder = $behaviourorder + $leftover;
289 return $finalorder;
290 }
291
292 /**
293 * Return an array where the keys are the internal names of the behaviours
294 * in preferred order and the values are a human-readable name.
295 *
296 * @param string $currentbahaviour
297 * @return array model name => lang string for this behaviour name.
298 */
299 public static function get_behaviour_options($currentbahaviour) {
300 global $CFG;
301 $archetypes = self::get_archetypal_behaviours();
302
303 // If no admin setting return all behavious
c76145d3 304 if (empty($CFG->questionbehavioursdisabled) && empty($CFG->questionbehavioursorder)) {
d1b7e03d
TH
305 return $archetypes;
306 }
307
308 return self::sort_behaviours($archetypes, $CFG->questionbehavioursorder,
309 $CFG->questionbehavioursdisabled, $currentbahaviour);
310 }
311
312 /**
313 * Get the translated name of an behaviour, for display in the UI.
314 * @param string $behaviour the internal name of the model.
315 * @return string name from the current language pack.
316 */
317 public static function get_behaviour_name($behaviour) {
aa9bdbe3 318 return get_string('pluginname', 'qbehaviour_' . $behaviour);
d1b7e03d
TH
319 }
320
321 /**
322 * Returns the valid choices for the number of decimal places for showing
323 * question marks. For use in the user interface.
324 * @return array suitable for passing to {@link choose_from_menu()} or similar.
325 */
326 public static function get_dp_options() {
327 return question_display_options::get_dp_options();
328 }
329
330 public static function initialise_js() {
331 return question_flags::initialise_js();
332 }
333}
334
335
336/**
337 * This class contains all the options that controls how a question is displayed.
338 *
339 * Normally, what will happen is that the calling code will set up some display
340 * options to indicate what sort of question display it wants, and then before the
341 * question is rendered, the behaviour will be given a chance to modify the
342 * display options, so that, for example, A question that is finished will only
343 * be shown read-only, and a question that has not been submitted will not have
344 * any sort of feedback displayed.
345 *
017bc1d9
TH
346 * @copyright 2009 The Open University
347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
348 */
349class question_display_options {
350 /**#@+ @var integer named constants for the values that most of the options take. */
351 const HIDDEN = 0;
352 const VISIBLE = 1;
353 const EDITABLE = 2;
354 /**#@-*/
355
356 /**#@+ @var integer named constants for the {@link $marks} option. */
357 const MAX_ONLY = 1;
358 const MARK_AND_MAX = 2;
359 /**#@-*/
360
361 /**
362 * @var integer maximum value for the {@link $markpd} option. This is
363 * effectively set by the database structure, which uses NUMBER(12,7) columns
364 * for question marks/fractions.
365 */
366 const MAX_DP = 7;
367
368 /**
369 * @var boolean whether the question should be displayed as a read-only review,
370 * or in an active state where you can change the answer.
371 */
372 public $readonly = false;
373
374 /**
375 * @var boolean whether the question type should output hidden form fields
376 * to reset any incorrect parts of the resonse to blank.
377 */
378 public $clearwrong = false;
379
380 /**
381 * Should the student have what they got right and wrong clearly indicated.
382 * This includes the green/red hilighting of the bits of their response,
383 * whether the one-line summary of the current state of the question says
384 * correct/incorrect or just answered.
385 * @var integer {@link question_display_options::HIDDEN} or
386 * {@link question_display_options::VISIBLE}
387 */
388 public $correctness = self::VISIBLE;
389
390 /**
391 * The the mark and/or the maximum available mark for this question be visible?
392 * @var integer {@link question_display_options::HIDDEN},
393 * {@link question_display_options::MAX_ONLY} or {@link question_display_options::MARK_AND_MAX}
394 */
395 public $marks = self::MARK_AND_MAX;
396
397 /** @var number of decimal places to use when formatting marks for output. */
398 public $markdp = 2;
399
400 /**
401 * Should the flag this question UI element be visible, and if so, should the
402 * flag state be changable?
403 * @var integer {@link question_display_options::HIDDEN},
404 * {@link question_display_options::VISIBLE} or {@link question_display_options::EDITABLE}
405 */
406 public $flags = self::VISIBLE;
407
408 /**
409 * Should the specific feedback be visible.
410 * @var integer {@link question_display_options::HIDDEN} or
411 * {@link question_display_options::VISIBLE}
412 */
413 public $feedback = self::VISIBLE;
414
415 /**
416 * For questions with a number of sub-parts (like matching, or
417 * multiple-choice, multiple-reponse) display the number of sub-parts that
418 * were correct.
419 * @var integer {@link question_display_options::HIDDEN} or
420 * {@link question_display_options::VISIBLE}
421 */
422 public $numpartscorrect = self::VISIBLE;
423
424 /**
425 * Should the general feedback be visible?
426 * @var integer {@link question_display_options::HIDDEN} or
427 * {@link question_display_options::VISIBLE}
428 */
429 public $generalfeedback = self::VISIBLE;
430
431 /**
432 * Should the automatically generated display of what the correct answer is
433 * be visible?
434 * @var integer {@link question_display_options::HIDDEN} or
435 * {@link question_display_options::VISIBLE}
436 */
437 public $rightanswer = self::VISIBLE;
438
439 /**
440 * Should the manually added marker's comment be visible. Should the link for
441 * adding/editing the comment be there.
442 * @var integer {@link question_display_options::HIDDEN},
443 * {@link question_display_options::VISIBLE}, or {@link question_display_options::EDITABLE}.
444 * Editable means that form fields are displayed inline.
445 */
446 public $manualcomment = self::VISIBLE;
447
448 /**
449 * Should we show a 'Make comment or override grade' link?
450 * @var string base URL for the edit comment script, which will be shown if
451 * $manualcomment = self::VISIBLE.
452 */
453 public $manualcommentlink = null;
454
455 /**
456 * Used in places like the question history table, to show a link to review
457 * this question in a certain state. If blank, a link is not shown.
458 * @var string base URL for a review question script.
459 */
460 public $questionreviewlink = null;
461
462 /**
463 * Should the history of previous question states table be visible?
464 * @var integer {@link question_display_options::HIDDEN} or
465 * {@link question_display_options::VISIBLE}
466 */
467 public $history = self::HIDDEN;
468
caeeff07
TH
469 /**
470 * @var int the context the attempt being output belongs to.
471 */
472 public $contextid;
473
d1b7e03d
TH
474 /**
475 * Set all the feedback-related fields {@link $feedback}, {@link generalfeedback},
476 * {@link rightanswer} and {@link manualcomment} to
477 * {@link question_display_options::HIDDEN}.
478 */
479 public function hide_all_feedback() {
480 $this->feedback = self::HIDDEN;
481 $this->numpartscorrect = self::HIDDEN;
482 $this->generalfeedback = self::HIDDEN;
483 $this->rightanswer = self::HIDDEN;
484 $this->manualcomment = self::HIDDEN;
485 $this->correctness = self::HIDDEN;
486 }
487
488 /**
489 * Returns the valid choices for the number of decimal places for showing
490 * question marks. For use in the user interface.
491 *
492 * Calling code should probably use {@link question_engine::get_dp_options()}
493 * rather than calling this method directly.
494 *
495 * @return array suitable for passing to {@link choose_from_menu()} or similar.
496 */
497 public static function get_dp_options() {
498 $options = array();
499 for ($i = 0; $i <= self::MAX_DP; $i += 1) {
500 $options[$i] = $i;
501 }
502 return $options;
503 }
504}
505
506
507/**
508 * Contains the logic for handling question flags.
509 *
f7970e3c 510 * @copyright 2010 The Open University
017bc1d9 511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
512 */
513abstract class question_flags {
514 /**
515 * Get the checksum that validates that a toggle request is valid.
f7970e3c
TH
516 * @param int $qubaid the question usage id.
517 * @param int $questionid the question id.
518 * @param int $sessionid the question_attempt id.
d1b7e03d
TH
519 * @param object $user the user. If null, defaults to $USER.
520 * @return string that needs to be sent to question/toggleflag.php for it to work.
521 */
06f8ed54 522 protected static function get_toggle_checksum($qubaid, $questionid, $qaid, $slot, $user = null) {
d1b7e03d
TH
523 if (is_null($user)) {
524 global $USER;
525 $user = $USER;
526 }
06f8ed54 527 return md5($qubaid . "_" . $user->secret . "_" . $questionid . "_" . $qaid . "_" . $slot);
d1b7e03d
TH
528 }
529
530 /**
531 * Get the postdata that needs to be sent to question/toggleflag.php to change the flag state.
532 * You need to append &newstate=0/1 to this.
533 * @return the post data to send.
534 */
535 public static function get_postdata(question_attempt $qa) {
536 $qaid = $qa->get_database_id();
537 $qubaid = $qa->get_usage_id();
538 $qid = $qa->get_question()->id;
06f8ed54
TH
539 $slot = $qa->get_slot();
540 $checksum = self::get_toggle_checksum($qubaid, $qid, $qaid, $slot);
404da238
TH
541 return "qaid=$qaid&qubaid=$qubaid&qid=$qid&slot=$slot&checksum=$checksum&sesskey=" .
542 sesskey() . '&newstate=';
d1b7e03d
TH
543 }
544
545 /**
546 * If the request seems valid, update the flag state of a question attempt.
547 * Throws exceptions if this is not a valid update request.
f7970e3c
TH
548 * @param int $qubaid the question usage id.
549 * @param int $questionid the question id.
550 * @param int $sessionid the question_attempt id.
d1b7e03d
TH
551 * @param string $checksum checksum, as computed by {@link get_toggle_checksum()}
552 * corresponding to the last three arguments.
f7970e3c 553 * @param bool $newstate the new state of the flag. true = flagged.
d1b7e03d 554 */
06f8ed54 555 public static function update_flag($qubaid, $questionid, $qaid, $slot, $checksum, $newstate) {
d1b7e03d 556 // Check the checksum - it is very hard to know who a question session belongs
f9b0500f 557 // to, so we require that checksum parameter is matches an md5 hash of the
d1b7e03d
TH
558 // three ids and the users username. Since we are only updating a flag, that
559 // probably makes it sufficiently difficult for malicious users to toggle
560 // other users flags.
06f8ed54 561 if ($checksum != question_flags::get_toggle_checksum($qubaid, $questionid, $qaid, $slot)) {
88f0eb15 562 throw new moodle_exception('errorsavingflags', 'question');
d1b7e03d
TH
563 }
564
565 $dm = new question_engine_data_mapper();
06f8ed54 566 $dm->update_question_attempt_flag($qubaid, $questionid, $qaid, $slot, $newstate);
d1b7e03d
TH
567 }
568
569 public static function initialise_js() {
f29aeb5a
TH
570 global $CFG, $PAGE, $OUTPUT;
571 static $done = false;
572 if ($done) {
573 return;
574 }
575 $module = array(
576 'name' => 'core_question_flags',
577 'fullpath' => '/question/flags.js',
578 'requires' => array('base', 'dom', 'event-delegate', 'io-base'),
579 );
580 $actionurl = $CFG->wwwroot . '/question/toggleflag.php';
581 $flagattributes = array(
582 0 => array(
583 'src' => $OUTPUT->pix_url('i/unflagged') . '',
584 'title' => get_string('clicktoflag', 'question'),
585 'alt' => get_string('notflagged', 'question'),
586 ),
587 1 => array(
588 'src' => $OUTPUT->pix_url('i/flagged') . '',
589 'title' => get_string('clicktounflag', 'question'),
590 'alt' => get_string('flagged', 'question'),
591 ),
d1b7e03d 592 );
f29aeb5a
TH
593 $PAGE->requires->js_init_call('M.core_question_flags.init',
594 array($actionurl, $flagattributes), false, $module);
595 $done = true;
d1b7e03d
TH
596 }
597}
598
599
f7970e3c
TH
600/**
601 * Exception thrown when the system detects that a student has done something
602 * out-of-order to a question. This can happen, for example, if they click
5e8a85aa 603 * the browser's back button in a quiz, then try to submit a different response.
f7970e3c
TH
604 *
605 * @copyright 2010 The Open University
606 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
607 */
d1b7e03d 608class question_out_of_sequence_exception extends moodle_exception {
c7df5006 609 public function __construct($qubaid, $slot, $postdata) {
d1b7e03d
TH
610 if ($postdata == null) {
611 $postdata = data_submitted();
612 }
613 parent::__construct('submissionoutofsequence', 'question', '', null,
614 "QUBAid: $qubaid, slot: $slot, post data: " . print_r($postdata, true));
615 }
616}
617
618
619/**
620 * This class keeps track of a group of questions that are being attempted,
621 * and which state, and so on, each one is currently in.
622 *
623 * A quiz attempt or a lesson attempt could use an instance of this class to
624 * keep track of all the questions in the attempt and process student submissions.
625 * It is basically a collection of {@question_attempt} objects.
626 *
627 * The questions being attempted as part of this usage are identified by an integer
628 * that is passed into many of the methods as $slot. ($question->id is not
629 * used so that the same question can be used more than once in an attempt.)
630 *
631 * Normally, calling code should be able to do everything it needs to be calling
632 * methods of this class. You should not normally need to get individual
633 * {@question_attempt} objects and play around with their inner workind, in code
634 * that it outside the quetsion engine.
635 *
636 * Instances of this class correspond to rows in the question_usages table.
637 *
017bc1d9
TH
638 * @copyright 2009 The Open University
639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
640 */
641class question_usage_by_activity {
642 /**
643 * @var integer|string the id for this usage. If this usage was loaded from
644 * the database, then this is the database id. Otherwise a unique random
645 * string is used.
646 */
647 protected $id = null;
648
649 /**
650 * @var string name of an archetypal behaviour, that should be used
651 * by questions in this usage if possible.
652 */
653 protected $preferredbehaviour = null;
654
655 /** @var object the context this usage belongs to. */
656 protected $context;
657
658 /** @var string plugin name of the plugin this usage belongs to. */
659 protected $owningcomponent;
660
661 /** @var array {@link question_attempt}s that make up this usage. */
662 protected $questionattempts = array();
663
664 /** @var question_usage_observer that tracks changes to this usage. */
665 protected $observer;
666
667 /**
668 * Create a new instance. Normally, calling code should use
669 * {@link question_engine::make_questions_usage_by_activity()} or
670 * {@link question_engine::load_questions_usage_by_activity()} rather than
671 * calling this constructor directly.
672 *
673 * @param string $component the plugin creating this attempt. For example mod_quiz.
674 * @param object $context the context this usage belongs to.
675 */
676 public function __construct($component, $context) {
677 $this->owningcomponent = $component;
678 $this->context = $context;
679 $this->observer = new question_usage_null_observer();
680 }
681
682 /**
683 * @param string $behaviour the name of an archetypal behaviour, that should
684 * be used by questions in this usage if possible.
685 */
686 public function set_preferred_behaviour($behaviour) {
687 $this->preferredbehaviour = $behaviour;
688 $this->observer->notify_modified();
689 }
690
691 /** @return string the name of the preferred behaviour. */
692 public function get_preferred_behaviour() {
693 return $this->preferredbehaviour;
694 }
695
0ff4bd08 696 /** @return object the context this usage belongs to. */
d1b7e03d
TH
697 public function get_owning_context() {
698 return $this->context;
699 }
700
701 /** @return string the name of the plugin that owns this attempt. */
702 public function get_owning_component() {
703 return $this->owningcomponent;
704 }
705
f7970e3c 706 /** @return int|string If this usage came from the database, then the id
d1b7e03d
TH
707 * from the question_usages table is returned. Otherwise a random string is
708 * returned. */
709 public function get_id() {
710 if (is_null($this->id)) {
711 $this->id = random_string(10);
712 }
713 return $this->id;
714 }
715
716 /** @return question_usage_observer that is tracking changes made to this usage. */
717 public function get_observer() {
718 return $this->observer;
719 }
720
721 /**
722 * For internal use only. Used by {@link question_engine_data_mapper} to set
723 * the id when a usage is saved to the database.
f7970e3c 724 * @param int $id the newly determined id for this usage.
d1b7e03d
TH
725 */
726 public function set_id_from_database($id) {
727 $this->id = $id;
728 foreach ($this->questionattempts as $qa) {
729 $qa->set_usage_id($id);
730 }
731 }
732
733 /**
734 * Add another question to this usage.
735 *
736 * The added question is not started until you call {@link start_question()}
737 * on it.
738 *
739 * @param question_definition $question the question to add.
740 * @param number $maxmark the maximum this question will be marked out of in
741 * this attempt (optional). If not given, $question->defaultmark is used.
f7970e3c 742 * @return int the number used to identify this question within this usage.
d1b7e03d
TH
743 */
744 public function add_question(question_definition $question, $maxmark = null) {
2daffca5 745 $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark);
d1b7e03d
TH
746 if (count($this->questionattempts) == 0) {
747 $this->questionattempts[1] = $qa;
748 } else {
749 $this->questionattempts[] = $qa;
750 }
751 $qa->set_number_in_usage(end(array_keys($this->questionattempts)));
752 $this->observer->notify_attempt_added($qa);
753 return $qa->get_slot();
754 }
755
756 /**
757 * Get the question_definition for a question in this attempt.
f7970e3c 758 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
759 * @return question_definition the requested question object.
760 */
761 public function get_question($slot) {
762 return $this->get_question_attempt($slot)->get_question();
763 }
764
765 /** @return array all the identifying numbers of all the questions in this usage. */
a1eb3a44 766 public function get_slots() {
d1b7e03d
TH
767 return array_keys($this->questionattempts);
768 }
769
f7970e3c 770 /** @return int the identifying number of the first question that was added to this usage. */
d1b7e03d
TH
771 public function get_first_question_number() {
772 reset($this->questionattempts);
773 return key($this->questionattempts);
774 }
775
f7970e3c 776 /** @return int the number of questions that are currently in this usage. */
d1b7e03d
TH
777 public function question_count() {
778 return count($this->questionattempts);
779 }
780
781 /**
782 * Note the part of the {@link question_usage_by_activity} comment that explains
783 * that {@link question_attempt} objects should be considered part of the inner
784 * workings of the question engine, and should not, if possible, be accessed directly.
785 *
786 * @return question_attempt_iterator for iterating over all the questions being
787 * attempted. as part of this usage.
788 */
789 public function get_attempt_iterator() {
790 return new question_attempt_iterator($this);
791 }
792
793 /**
794 * Check whether $number actually corresponds to a question attempt that is
795 * part of this usage. Throws an exception if not.
796 *
f7970e3c 797 * @param int $slot a number allegedly identifying a question within this usage.
d1b7e03d
TH
798 */
799 protected function check_slot($slot) {
800 if (!array_key_exists($slot, $this->questionattempts)) {
88f0eb15 801 throw new coding_exception("There is no question_attempt number $slot in this attempt.");
d1b7e03d
TH
802 }
803 }
804
805 /**
806 * Note the part of the {@link question_usage_by_activity} comment that explains
807 * that {@link question_attempt} objects should be considered part of the inner
808 * workings of the question engine, and should not, if possible, be accessed directly.
809 *
f7970e3c 810 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
811 * @return question_attempt the corresponding {@link question_attempt} object.
812 */
813 public function get_question_attempt($slot) {
814 $this->check_slot($slot);
815 return $this->questionattempts[$slot];
816 }
817
818 /**
819 * Get the current state of the attempt at a question.
f7970e3c 820 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
821 * @return question_state.
822 */
823 public function get_question_state($slot) {
824 return $this->get_question_attempt($slot)->get_state();
825 }
826
827 /**
f7970e3c
TH
828 * @param int $slot the number used to identify this question within this usage.
829 * @param bool $showcorrectness Whether right/partial/wrong states should
d1b7e03d
TH
830 * be distinguised.
831 * @return string A brief textual description of the current state.
832 */
833 public function get_question_state_string($slot, $showcorrectness) {
834 return $this->get_question_attempt($slot)->get_state_string($showcorrectness);
835 }
836
837 /**
838 * Get the time of the most recent action performed on a question.
f7970e3c
TH
839 * @param int $slot the number used to identify this question within this usage.
840 * @return int timestamp.
d1b7e03d
TH
841 */
842 public function get_question_action_time($slot) {
843 return $this->get_question_attempt($slot)->get_last_action_time();
844 }
845
846 /**
847 * Get the current fraction awarded for the attempt at a question.
f7970e3c 848 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
849 * @return number|null The current fraction for this question, or null if one has
850 * not been assigned yet.
851 */
852 public function get_question_fraction($slot) {
853 return $this->get_question_attempt($slot)->get_fraction();
854 }
855
856 /**
857 * Get the current mark awarded for the attempt at a question.
f7970e3c 858 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
859 * @return number|null The current mark for this question, or null if one has
860 * not been assigned yet.
861 */
862 public function get_question_mark($slot) {
863 return $this->get_question_attempt($slot)->get_mark();
864 }
865
866 /**
867 * Get the maximum mark possible for the attempt at a question.
f7970e3c 868 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
869 * @return number the available marks for this question.
870 */
871 public function get_question_max_mark($slot) {
872 return $this->get_question_attempt($slot)->get_max_mark();
873 }
874
875 /**
876 * Get the current mark awarded for the attempt at a question.
f7970e3c 877 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
878 * @return number|null The current mark for this question, or null if one has
879 * not been assigned yet.
880 */
881 public function get_total_mark() {
882 $mark = 0;
883 foreach ($this->questionattempts as $qa) {
f86390dc 884 if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
d1b7e03d
TH
885 return null;
886 }
887 $mark += $qa->get_mark();
888 }
889 return $mark;
890 }
891
892 /**
893 * @return string a simple textual summary of the question that was asked.
894 */
895 public function get_question_summary($slot) {
896 return $this->get_question_attempt($slot)->get_question_summary();
897 }
898
899 /**
900 * @return string a simple textual summary of response given.
901 */
902 public function get_response_summary($slot) {
903 return $this->get_question_attempt($slot)->get_response_summary();
904 }
905
906 /**
907 * @return string a simple textual summary of the correct resonse.
908 */
909 public function get_right_answer_summary($slot) {
910 return $this->get_question_attempt($slot)->get_right_answer_summary();
911 }
912
913 /**
914 * Get the {@link core_question_renderer}, in collaboration with appropriate
915 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
916 * HTML to display this question.
f7970e3c 917 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
918 * @param question_display_options $options controls how the question is rendered.
919 * @param string|null $number The question number to display. 'i' is a special
920 * value that gets displayed as Information. Null means no number is displayed.
921 * @return string HTML fragment representing the question.
922 */
923 public function render_question($slot, $options, $number = null) {
caeeff07 924 $options->contextid = $this->context->id;
d1b7e03d
TH
925 return $this->get_question_attempt($slot)->render($options, $number);
926 }
927
928 /**
929 * Generate any bits of HTML that needs to go in the <head> tag when this question
930 * is displayed in the body.
f7970e3c 931 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
932 * @return string HTML fragment.
933 */
934 public function render_question_head_html($slot) {
caeeff07 935 $options->contextid = $this->context->id;
d1b7e03d
TH
936 return $this->get_question_attempt($slot)->render_head_html();
937 }
938
939 /**
940 * Like {@link render_question()} but displays the question at the past step
941 * indicated by $seq, rather than showing the latest step.
942 *
f7970e3c
TH
943 * @param int $slot the number used to identify this question within this usage.
944 * @param int $seq the seq number of the past state to display.
d1b7e03d
TH
945 * @param question_display_options $options controls how the question is rendered.
946 * @param string|null $number The question number to display. 'i' is a special
947 * value that gets displayed as Information. Null means no number is displayed.
948 * @return string HTML fragment representing the question.
949 */
950 public function render_question_at_step($slot, $seq, $options, $number = null) {
caeeff07 951 $options->contextid = $this->context->id;
d1b7e03d
TH
952 return $this->get_question_attempt($slot)->render_at_step($seq, $options, $number, $this->preferredbehaviour);
953 }
954
7a719748
TH
955 /**
956 * Checks whether the users is allow to be served a particular file.
f7970e3c 957 * @param int $slot the number used to identify this question within this usage.
7a719748
TH
958 * @param question_display_options $options the options that control display of the question.
959 * @param string $component the name of the component we are serving files for.
960 * @param string $filearea the name of the file area.
961 * @param array $args the remaining bits of the file path.
f7970e3c
TH
962 * @param bool $forcedownload whether the user must be forced to download the file.
963 * @return bool true if the user can access this file.
7a719748
TH
964 */
965 public function check_file_access($slot, $options, $component, $filearea, $args, $forcedownload) {
966 return $this->get_question_attempt($slot)->check_file_access($options, $component, $filearea, $args, $forcedownload);
967 }
968
d1b7e03d
TH
969 /**
970 * Replace a particular question_attempt with a different one.
971 *
972 * For internal use only. Used when reloading the state of a question from the
973 * database.
974 *
975 * @param array $records Raw records loaded from the database.
f7970e3c 976 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
977 * @return question_attempt The newly constructed question_attempt_step.
978 */
979 public function replace_loaded_question_attempt_info($slot, $qa) {
980 $this->check_slot($slot);
981 $this->questionattempts[$slot] = $qa;
982 }
983
984 /**
985 * You should probably not use this method in code outside the question engine.
986 * The main reason for exposing it was for the benefit of unit tests.
f7970e3c 987 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
988 * @return string return the prefix that is pre-pended to field names in the HTML
989 * that is output.
990 */
991 public function get_field_prefix($slot) {
992 return $this->get_question_attempt($slot)->get_field_prefix();
993 }
994
995 /**
996 * Start the attempt at a question that has been added to this usage.
f7970e3c 997 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
998 */
999 public function start_question($slot) {
1000 $qa = $this->get_question_attempt($slot);
1001 $qa->start($this->preferredbehaviour);
1002 $this->observer->notify_attempt_modified($qa);
1003 }
1004
1005 /**
1006 * Start the attempt at all questions that has been added to this usage.
1007 */
1008 public function start_all_questions() {
1009 foreach ($this->questionattempts as $qa) {
1010 $qa->start($this->preferredbehaviour);
1011 $this->observer->notify_attempt_modified($qa);
1012 }
1013 }
1014
1015 /**
1016 * Start the attempt at a question, starting from the point where the previous
1017 * question_attempt $oldqa had reached. This is used by the quiz 'Each attempt
1018 * builds on last' mode.
f7970e3c 1019 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1020 * @param question_attempt $oldqa a previous attempt at this quetsion that
1021 * defines the starting point.
1022 */
1023 public function start_question_based_on($slot, question_attempt $oldqa) {
1024 $qa = $this->get_question_attempt($slot);
1025 $qa->start_based_on($oldqa);
1026 $this->observer->notify_attempt_modified($qa);
1027 }
1028
1029 /**
1030 * Process all the question actions in the current request.
1031 *
1032 * If there is a parameter slots included in the post data, then only
1033 * those question numbers will be processed, otherwise all questions in this
1034 * useage will be.
1035 *
1036 * This function also does {@link update_question_flags()}.
1037 *
f7970e3c 1038 * @param int $timestamp optional, use this timestamp as 'now'.
d1b7e03d
TH
1039 * @param array $postdata optional, only intended for testing. Use this data
1040 * instead of the data from $_POST.
1041 */
1042 public function process_all_actions($timestamp = null, $postdata = null) {
1043 $slots = question_attempt::get_submitted_var('slots', PARAM_SEQUENCE, $postdata);
1044 if (is_null($slots)) {
a1eb3a44 1045 $slots = $this->get_slots();
d1b7e03d
TH
1046 } else if (!$slots) {
1047 $slots = array();
1048 } else {
1049 $slots = explode(',', $slots);
1050 }
1051 foreach ($slots as $slot) {
92d04f0b
TH
1052 if (!$this->validate_sequence_number($slot, $postdata)) {
1053 continue;
1054 }
d1b7e03d
TH
1055 $submitteddata = $this->extract_responses($slot, $postdata);
1056 $this->process_action($slot, $submitteddata, $timestamp);
1057 }
1058 $this->update_question_flags($postdata);
1059 }
1060
1061 /**
1062 * Get the submitted data from the current request that belongs to this
1063 * particular question.
1064 *
f7970e3c 1065 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1066 * @param $postdata optional, only intended for testing. Use this data
1067 * instead of the data from $_POST.
1068 * @return array submitted data specific to this question.
1069 */
1070 public function extract_responses($slot, $postdata = null) {
1071 return $this->get_question_attempt($slot)->get_submitted_data($postdata);
1072 }
1073
1074 /**
1075 * Process a specific action on a specific question.
f7970e3c 1076 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1077 * @param $submitteddata the submitted data that constitutes the action.
1078 */
1079 public function process_action($slot, $submitteddata, $timestamp = null) {
1080 $qa = $this->get_question_attempt($slot);
1081 $qa->process_action($submitteddata, $timestamp);
1082 $this->observer->notify_attempt_modified($qa);
1083 }
1084
1085 /**
1086 * Check that the sequence number, that detects weird things like the student
92d04f0b
TH
1087 * clicking back, is OK. If the sequence check variable is not present, returns
1088 * false. If the check variable is present and correct, returns true. If the
1089 * variable is present and wrong, throws an exception.
f7970e3c 1090 * @param int $slot the number used to identify this question within this usage.
d1b7e03d 1091 * @param array $submitteddata the submitted data that constitutes the action.
92d04f0b
TH
1092 * @return bool true if the check variable is present and correct. False if it
1093 * is missing. (Throws an exception if the check fails.)
d1b7e03d
TH
1094 */
1095 public function validate_sequence_number($slot, $postdata = null) {
1096 $qa = $this->get_question_attempt($slot);
1097 $sequencecheck = question_attempt::get_submitted_var(
1098 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
92d04f0b
TH
1099 if (is_null($sequencecheck)) {
1100 return false;
1101 } else if ($sequencecheck != $qa->get_num_steps()) {
d1b7e03d 1102 throw new question_out_of_sequence_exception($this->id, $slot, $postdata);
92d04f0b
TH
1103 } else {
1104 return true;
d1b7e03d
TH
1105 }
1106 }
1107 /**
1108 * Update the flagged state for all question_attempts in this usage, if their
1109 * flagged state was changed in the request.
1110 *
1111 * @param $postdata optional, only intended for testing. Use this data
1112 * instead of the data from $_POST.
1113 */
1114 public function update_question_flags($postdata = null) {
1115 foreach ($this->questionattempts as $qa) {
1116 $flagged = question_attempt::get_submitted_var(
1117 $qa->get_flag_field_name(), PARAM_BOOL, $postdata);
1118 if (!is_null($flagged) && $flagged != $qa->is_flagged()) {
1119 $qa->set_flagged($flagged);
1120 }
1121 }
d1b7e03d
TH
1122 }
1123
1124 /**
1125 * Get the correct response to a particular question. Passing the results of
1126 * this method to {@link process_action()} will probably result in full marks.
f7970e3c 1127 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1128 * @return array that constitutes a correct response to this question.
1129 */
1130 public function get_correct_response($slot) {
1131 return $this->get_question_attempt($slot)->get_correct_response();
1132 }
1133
1134 /**
1135 * Finish the active phase of an attempt at a question.
1136 *
1137 * This is an external act of finishing the attempt. Think, for example, of
1138 * the 'Submit all and finish' button in the quiz. Some behaviours,
1139 * (for example, immediatefeedback) give a way of finishing the active phase
1140 * of a question attempt as part of a {@link process_action()} call.
1141 *
1142 * After the active phase is over, the only changes possible are things like
1143 * manual grading, or changing the flag state.
1144 *
f7970e3c 1145 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1146 */
1147 public function finish_question($slot, $timestamp = null) {
1148 $qa = $this->get_question_attempt($slot);
1149 $qa->finish($timestamp);
1150 $this->observer->notify_attempt_modified($qa);
1151 }
1152
1153 /**
1154 * Finish the active phase of an attempt at a question. See {@link finish_question()}
1155 * for a fuller description of what 'finish' means.
1156 */
1157 public function finish_all_questions($timestamp = null) {
1158 foreach ($this->questionattempts as $qa) {
1159 $qa->finish($timestamp);
1160 $this->observer->notify_attempt_modified($qa);
1161 }
1162 }
1163
1164 /**
1165 * Perform a manual grading action on a question attempt.
f7970e3c 1166 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1167 * @param string $comment the comment being added to the question attempt.
1168 * @param number $mark the mark that is being assigned. Can be null to just
1169 * add a comment.
1170 */
1171 public function manual_grade($slot, $comment, $mark) {
1172 $qa = $this->get_question_attempt($slot);
1173 $qa->manual_grade($comment, $mark);
1174 $this->observer->notify_attempt_modified($qa);
1175 }
1176
1177 /**
1178 * Regrade a question in this usage. This replays the sequence of submitted
1179 * actions to recompute the outcomes.
f7970e3c
TH
1180 * @param int $slot the number used to identify this question within this usage.
1181 * @param bool $finished whether the question attempt should be forced to be finished
d1b7e03d
TH
1182 * after the regrade, or whether it may still be in progress (default false).
1183 * @param number $newmaxmark (optional) if given, will change the max mark while regrading.
1184 */
1185 public function regrade_question($slot, $finished = false, $newmaxmark = null) {
1186 $oldqa = $this->get_question_attempt($slot);
1187 if (is_null($newmaxmark)) {
1188 $newmaxmark = $oldqa->get_max_mark();
1189 }
1190
1191 $this->observer->notify_delete_attempt_steps($oldqa);
1192
1193 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(),
2daffca5 1194 $this->observer, $newmaxmark);
d1b7e03d
TH
1195 $newqa->set_database_id($oldqa->get_database_id());
1196 $newqa->regrade($oldqa, $finished);
1197
1198 $this->questionattempts[$slot] = $newqa;
1199 $this->observer->notify_attempt_modified($newqa);
1200 }
1201
1202 /**
1203 * Regrade all the questions in this usage (without changing their max mark).
f7970e3c 1204 * @param bool $finished whether each question should be forced to be finished
d1b7e03d
TH
1205 * after the regrade, or whether it may still be in progress (default false).
1206 */
1207 public function regrade_all_questions($finished = false) {
1208 foreach ($this->questionattempts as $slot => $notused) {
1209 $this->regrade_question($slot, $finished);
1210 }
1211 }
1212
1213 /**
1214 * Create a question_usage_by_activity from records loaded from the database.
1215 *
1216 * For internal use only.
1217 *
1218 * @param array $records Raw records loaded from the database.
f7970e3c 1219 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
1220 * @return question_attempt The newly constructed question_attempt_step.
1221 */
1222 public static function load_from_records(&$records, $qubaid) {
1223 $record = current($records);
1224 while ($record->qubaid != $qubaid) {
1225 $record = next($records);
1226 if (!$record) {
88f0eb15 1227 throw new coding_exception("Question usage $qubaid not found in the database.");
d1b7e03d
TH
1228 }
1229 }
1230
1231 $quba = new question_usage_by_activity($record->component,
1232 get_context_instance_by_id($record->contextid));
1233 $quba->set_id_from_database($record->qubaid);
1234 $quba->set_preferred_behaviour($record->preferredbehaviour);
1235
1236 $quba->observer = new question_engine_unit_of_work($quba);
1237
1238 while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
1239 $quba->questionattempts[$record->slot] =
1240 question_attempt::load_from_records($records,
1241 $record->questionattemptid, $quba->observer,
1242 $quba->get_preferred_behaviour());
1243 $record = current($records);
1244 }
1245
1246 return $quba;
1247 }
1248}
1249
1250
1251/**
1252 * A class abstracting access to the
1253 * {@link question_usage_by_activity::$questionattempts} array.
1254 *
1255 * This class snapshots the list of {@link question_attempts} to iterate over
1256 * when it is created. If a question is added to the usage mid-iteration, it
1257 * will now show up.
1258 *
1259 * To create an instance of this class, use
1260 * {@link question_usage_by_activity::get_attempt_iterator()}
1261 *
017bc1d9
TH
1262 * @copyright 2009 The Open University
1263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1264 */
1265class question_attempt_iterator implements Iterator, ArrayAccess {
1266 /** @var question_usage_by_activity that we are iterating over. */
1267 protected $quba;
1268 /** @var array of question numbers. */
1269 protected $slots;
1270
1271 /**
1272 * To create an instance of this class, use {@link question_usage_by_activity::get_attempt_iterator()}.
1273 * @param $quba the usage to iterate over.
1274 */
1275 public function __construct(question_usage_by_activity $quba) {
1276 $this->quba = $quba;
a1eb3a44 1277 $this->slots = $quba->get_slots();
d1b7e03d
TH
1278 $this->rewind();
1279 }
1280
1281 /** @return question_attempt_step */
1282 public function current() {
1283 return $this->offsetGet(current($this->slots));
1284 }
f7970e3c 1285 /** @return int */
d1b7e03d
TH
1286 public function key() {
1287 return current($this->slots);
1288 }
1289 public function next() {
1290 next($this->slots);
1291 }
1292 public function rewind() {
1293 reset($this->slots);
1294 }
f7970e3c 1295 /** @return bool */
d1b7e03d
TH
1296 public function valid() {
1297 return current($this->slots) !== false;
1298 }
1299
f7970e3c 1300 /** @return bool */
d1b7e03d
TH
1301 public function offsetExists($slot) {
1302 return in_array($slot, $this->slots);
1303 }
1304 /** @return question_attempt_step */
1305 public function offsetGet($slot) {
1306 return $this->quba->get_question_attempt($slot);
1307 }
1308 public function offsetSet($slot, $value) {
88f0eb15 1309 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
d1b7e03d
TH
1310 }
1311 public function offsetUnset($slot) {
88f0eb15 1312 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
d1b7e03d
TH
1313 }
1314}
1315
1316
1317/**
1318 * Tracks an attempt at one particular question in a {@link question_usage_by_activity}.
1319 *
1320 * Most calling code should need to access objects of this class. They should be
1321 * able to do everything through the usage interface. This class is an internal
1322 * implementation detail of the question engine.
1323 *
1324 * Instances of this class correspond to rows in the question_attempts table, and
1325 * a collection of {@link question_attempt_steps}. Question inteaction models and
1326 * question types do work with question_attempt objects.
1327 *
017bc1d9
TH
1328 * @copyright 2009 The Open University
1329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1330 */
1331class question_attempt {
1332 /**
1333 * @var string this is a magic value that question types can return from
1334 * {@link question_definition::get_expected_data()}.
1335 */
1336 const USE_RAW_DATA = 'use raw data';
1337
1338 /**
1339 * @var string special value used by manual grading because {@link PARAM_NUMBER}
1340 * converts '' to 0.
1341 */
1342 const PARAM_MARK = 'parammark';
1343
caeeff07
TH
1344 /**
1345 * @var string special value used by manual grading because {@link PARAM_NUMBER}
1346 * converts '' to 0.
1347 */
1348 const PARAM_FILES = 'paramfiles';
1349
d1b7e03d
TH
1350 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
1351 protected $id = null;
1352
1353 /** @var integer|string the id of the question_usage_by_activity we belong to. */
1354 protected $usageid;
1355
1356 /** @var integer the number used to identify this question_attempt within the usage. */
1357 protected $slot = null;
1358
1359 /**
1360 * @var question_behaviour the behaviour controlling this attempt.
1361 * null until {@link start()} is called.
1362 */
1363 protected $behaviour = null;
1364
1365 /** @var question_definition the question this is an attempt at. */
1366 protected $question;
1367
1368 /** @var number the maximum mark that can be scored at this question. */
1369 protected $maxmark;
1370
1371 /**
1372 * @var number the minimum fraction that can be scored at this question, so
1373 * the minimum mark is $this->minfraction * $this->maxmark.
1374 */
1375 protected $minfraction = null;
1376
1377 /**
1378 * @var string plain text summary of the variant of the question the
1379 * student saw. Intended for reporting purposes.
1380 */
1381 protected $questionsummary = null;
1382
1383 /**
1384 * @var string plain text summary of the response the student gave.
1385 * Intended for reporting purposes.
1386 */
1387 protected $responsesummary = null;
1388
1389 /**
1390 * @var string plain text summary of the correct response to this question
1391 * variant the student saw. The format should be similar to responsesummary.
1392 * Intended for reporting purposes.
1393 */
1394 protected $rightanswer = null;
1395
1396 /** @var array of {@link question_attempt_step}s. The steps in this attempt. */
1397 protected $steps = array();
1398
1399 /** @var boolean whether the user has flagged this attempt within the usage. */
1400 protected $flagged = false;
1401
1402 /** @var question_usage_observer tracks changes to the useage this attempt is part of.*/
1403 protected $observer;
1404
1405 /**#@+
1406 * Constants used by the intereaction models to indicate whether the current
1407 * pending step should be kept or discarded.
1408 */
1409 const KEEP = true;
1410 const DISCARD = false;
1411 /**#@-*/
1412
1413 /**
1414 * Create a new {@link question_attempt}. Normally you should create question_attempts
1415 * indirectly, by calling {@link question_usage_by_activity::add_question()}.
1416 *
1417 * @param question_definition $question the question this is an attempt at.
f7970e3c 1418 * @param int|string $usageid The id of the
d1b7e03d
TH
1419 * {@link question_usage_by_activity} we belong to. Used by {@link get_field_prefix()}.
1420 * @param question_usage_observer $observer tracks changes to the useage this
1421 * attempt is part of. (Optional, a {@link question_usage_null_observer} is
1422 * used if one is not passed.
1423 * @param number $maxmark the maximum grade for this question_attempt. If not
1424 * passed, $question->defaultmark is used.
1425 */
2daffca5 1426 public function __construct(question_definition $question, $usageid,
d1b7e03d
TH
1427 question_usage_observer $observer = null, $maxmark = null) {
1428 $this->question = $question;
1429 $this->usageid = $usageid;
1430 if (is_null($observer)) {
1431 $observer = new question_usage_null_observer();
1432 }
1433 $this->observer = $observer;
1434 if (!is_null($maxmark)) {
1435 $this->maxmark = $maxmark;
1436 } else {
1437 $this->maxmark = $question->defaultmark;
1438 }
1439 }
1440
1441 /** @return question_definition the question this is an attempt at. */
1442 public function get_question() {
1443 return $this->question;
1444 }
1445
1446 /**
1447 * Set the number used to identify this question_attempt within the usage.
1448 * For internal use only.
f7970e3c 1449 * @param int $slot
d1b7e03d
TH
1450 */
1451 public function set_number_in_usage($slot) {
1452 $this->slot = $slot;
1453 }
1454
f7970e3c 1455 /** @return int the number used to identify this question_attempt within the usage. */
d1b7e03d
TH
1456 public function get_slot() {
1457 return $this->slot;
1458 }
1459
1460 /**
f7970e3c 1461 * @return int the id of row for this question_attempt, if it is stored in the
d1b7e03d
TH
1462 * database. null if not.
1463 */
1464 public function get_database_id() {
1465 return $this->id;
1466 }
1467
1468 /**
1469 * For internal use only. Set the id of the corresponding database row.
f7970e3c 1470 * @param int $id the id of row for this question_attempt, if it is
d1b7e03d
TH
1471 * stored in the database.
1472 */
1473 public function set_database_id($id) {
1474 $this->id = $id;
1475 }
1476
f7970e3c 1477 /** @return int|string the id of the {@link question_usage_by_activity} we belong to. */
d1b7e03d
TH
1478 public function get_usage_id() {
1479 return $this->usageid;
1480 }
1481
1482 /**
1483 * Set the id of the {@link question_usage_by_activity} we belong to.
1484 * For internal use only.
f7970e3c 1485 * @param int|string the new id.
d1b7e03d
TH
1486 */
1487 public function set_usage_id($usageid) {
1488 $this->usageid = $usageid;
1489 }
1490
1491 /** @return string the name of the behaviour that is controlling this attempt. */
1492 public function get_behaviour_name() {
1493 return $this->behaviour->get_name();
1494 }
1495
1496 /**
1497 * For internal use only.
1498 * @return question_behaviour the behaviour that is controlling this attempt.
1499 */
1500 public function get_behaviour() {
1501 return $this->behaviour;
1502 }
1503
1504 /**
1505 * Set the flagged state of this question.
f7970e3c 1506 * @param bool $flagged the new state.
d1b7e03d
TH
1507 */
1508 public function set_flagged($flagged) {
1509 $this->flagged = $flagged;
1510 $this->observer->notify_attempt_modified($this);
1511 }
1512
f7970e3c 1513 /** @return bool whether this question is currently flagged. */
d1b7e03d
TH
1514 public function is_flagged() {
1515 return $this->flagged;
1516 }
1517
1518 /**
1519 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1520 * name) to use for the field that indicates whether this question is flagged.
1521 *
1522 * @return string The field name to use.
1523 */
1524 public function get_flag_field_name() {
1525 return $this->get_control_field_name('flagged');
1526 }
1527
1528 /**
1529 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1530 * name) to use for a question_type variable belonging to this question_attempt.
1531 *
1532 * See the comment on {@link question_attempt_step} for an explanation of
1533 * question type and behaviour variables.
1534 *
1535 * @param $varname The short form of the variable name.
1536 * @return string The field name to use.
1537 */
1538 public function get_qt_field_name($varname) {
1539 return $this->get_field_prefix() . $varname;
1540 }
1541
1542 /**
1543 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1544 * name) to use for a question_type variable belonging to this question_attempt.
1545 *
1546 * See the comment on {@link question_attempt_step} for an explanation of
1547 * question type and behaviour variables.
1548 *
1549 * @param $varname The short form of the variable name.
1550 * @return string The field name to use.
1551 */
1552 public function get_behaviour_field_name($varname) {
1553 return $this->get_field_prefix() . '-' . $varname;
1554 }
1555
1556 /**
1557 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1558 * name) to use for a control variables belonging to this question_attempt.
1559 *
1560 * Examples are :sequencecheck and :flagged
1561 *
1562 * @param $varname The short form of the variable name.
1563 * @return string The field name to use.
1564 */
1565 public function get_control_field_name($varname) {
1566 return $this->get_field_prefix() . ':' . $varname;
1567 }
1568
1569 /**
1570 * Get the prefix added to variable names to give field names for this
1571 * question attempt.
1572 *
1573 * You should not use this method directly. This is an implementation detail
1574 * anyway, but if you must access it, use {@link question_usage_by_activity::get_field_prefix()}.
1575 *
1576 * @param $varname The short form of the variable name.
1577 * @return string The field name to use.
1578 */
1579 public function get_field_prefix() {
1580 return 'q' . $this->usageid . ':' . $this->slot . '_';
1581 }
1582
1583 /**
1584 * Get one of the steps in this attempt.
1585 * For internal/test code use only.
f7970e3c 1586 * @param int $i the step number.
d1b7e03d
TH
1587 * @return question_attempt_step
1588 */
1589 public function get_step($i) {
1590 if ($i < 0 || $i >= count($this->steps)) {
88f0eb15 1591 throw new coding_exception('Index out of bounds in question_attempt::get_step.');
d1b7e03d
TH
1592 }
1593 return $this->steps[$i];
1594 }
1595
1596 /**
1597 * Get the number of steps in this attempt.
1598 * For internal/test code use only.
f7970e3c 1599 * @return int the number of steps we currently have.
d1b7e03d
TH
1600 */
1601 public function get_num_steps() {
1602 return count($this->steps);
1603 }
1604
1605 /**
1606 * Return the latest step in this question_attempt.
1607 * For internal/test code use only.
1608 * @return question_attempt_step
1609 */
1610 public function get_last_step() {
1611 if (count($this->steps) == 0) {
1612 return new question_null_step();
1613 }
1614 return end($this->steps);
1615 }
1616
1617 /**
1618 * @return question_attempt_step_iterator for iterating over the steps in
1619 * this attempt, in order.
1620 */
1621 public function get_step_iterator() {
1622 return new question_attempt_step_iterator($this);
1623 }
1624
1625 /**
1626 * The same as {@link get_step_iterator()}. However, for a
1627 * {@link question_attempt_with_restricted_history} this returns the full
1628 * list of steps, while {@link get_step_iterator()} returns only the
1629 * limited history.
1630 * @return question_attempt_step_iterator for iterating over the steps in
1631 * this attempt, in order.
1632 */
1633 public function get_full_step_iterator() {
1634 return $this->get_step_iterator();
1635 }
1636
1637 /**
1638 * @return question_attempt_reverse_step_iterator for iterating over the steps in
1639 * this attempt, in reverse order.
1640 */
c7df5006 1641 public function get_reverse_step_iterator() {
d1b7e03d
TH
1642 return new question_attempt_reverse_step_iterator($this);
1643 }
1644
1645 /**
1646 * Get the qt data from the latest step that has any qt data. Return $default
1647 * array if it is no step has qt data.
1648 *
1649 * @param string $name the name of the variable to get.
1650 * @param mixed default the value to return no step has qt data.
1651 * (Optional, defaults to an empty array.)
1652 * @return array|mixed the data, or $default if there is not any.
1653 */
1654 public function get_last_qt_data($default = array()) {
1655 foreach ($this->get_reverse_step_iterator() as $step) {
1656 $response = $step->get_qt_data();
1657 if (!empty($response)) {
1658 return $response;
1659 }
1660 }
1661 return $default;
1662 }
1663
1664 /**
1665 * Get the latest value of a particular question type variable. That is, get
1666 * the value from the latest step that has it set. Return null if it is not
1667 * set in any step.
1668 *
1669 * @param string $name the name of the variable to get.
1670 * @param mixed default the value to return in the variable has never been set.
1671 * (Optional, defaults to null.)
1672 * @return mixed string value, or $default if it has never been set.
1673 */
1674 public function get_last_qt_var($name, $default = null) {
1675 foreach ($this->get_reverse_step_iterator() as $step) {
1676 if ($step->has_qt_var($name)) {
1677 return $step->get_qt_var($name);
1678 }
1679 }
1680 return $default;
1681 }
1682
caeeff07
TH
1683 /**
1684 * Get the latest set of files for a particular question type variable of
1685 * type question_attempt::PARAM_FILES.
1686 *
1687 * @param string $name the name of the associated variable.
1688 * @return array of {@link stored_files}.
1689 */
1690 public function get_last_qt_files($name, $contextid) {
1691 foreach ($this->get_reverse_step_iterator() as $step) {
1692 if ($step->has_qt_var($name)) {
1693 return $step->get_qt_files($name, $contextid);
1694 }
1695 }
1696 return array();
1697 }
1698
1699 /**
1700 * Get the URL of a file that belongs to a response variable of this
1701 * question_attempt.
1702 * @param stored_file $file the file to link to.
1703 * @return string the URL of that file.
1704 */
1705 public function get_response_file_url(stored_file $file) {
1706 return file_encode_url(new moodle_url('/pluginfile.php'), '/' . implode('/', array(
1707 $file->get_contextid(),
1708 $file->get_component(),
1709 $file->get_filearea(),
1710 $this->usageid,
1711 $this->slot,
1712 $file->get_itemid())) .
1713 $file->get_filepath() . $file->get_filename());
1714 }
1715
d1b7e03d
TH
1716 /**
1717 * Get the latest value of a particular behaviour variable. That is,
1718 * get the value from the latest step that has it set. Return null if it is
1719 * not set in any step.
1720 *
1721 * @param string $name the name of the variable to get.
1722 * @param mixed default the value to return in the variable has never been set.
1723 * (Optional, defaults to null.)
1724 * @return mixed string value, or $default if it has never been set.
1725 */
1726 public function get_last_behaviour_var($name, $default = null) {
1727 foreach ($this->get_reverse_step_iterator() as $step) {
1728 if ($step->has_behaviour_var($name)) {
1729 return $step->get_behaviour_var($name);
1730 }
1731 }
1732 return $default;
1733 }
1734
1735 /**
1736 * Get the current state of this question attempt. That is, the state of the
1737 * latest step.
1738 * @return question_state
1739 */
1740 public function get_state() {
1741 return $this->get_last_step()->get_state();
1742 }
1743
1744 /**
f7970e3c 1745 * @param bool $showcorrectness Whether right/partial/wrong states should
d1b7e03d
TH
1746 * be distinguised.
1747 * @return string A brief textual description of the current state.
1748 */
1749 public function get_state_string($showcorrectness) {
1750 return $this->behaviour->get_state_string($showcorrectness);
1751 }
1752
1753 /**
f7970e3c 1754 * @return int the timestamp of the most recent step in this question attempt.
d1b7e03d
TH
1755 */
1756 public function get_last_action_time() {
1757 return $this->get_last_step()->get_timecreated();
1758 }
1759
1760 /**
1761 * Get the current fraction of this question attempt. That is, the fraction
1762 * of the latest step, or null if this question has not yet been graded.
1763 * @return number the current fraction.
1764 */
1765 public function get_fraction() {
1766 return $this->get_last_step()->get_fraction();
1767 }
1768
f7970e3c 1769 /** @return bool whether this question attempt has a non-zero maximum mark. */
d1b7e03d
TH
1770 public function has_marks() {
1771 // Since grades are stored in the database as NUMBER(12,7).
1772 return $this->maxmark >= 0.00000005;
1773 }
1774
1775 /**
1776 * @return number the current mark for this question.
1777 * {@link get_fraction()} * {@link get_max_mark()}.
1778 */
1779 public function get_mark() {
1780 return $this->fraction_to_mark($this->get_fraction());
1781 }
1782
1783 /**
1784 * This is used by the manual grading code, particularly in association with
1785 * validation. If there is a mark submitted in the request, then use that,
1786 * otherwise use the latest mark for this question.
1787 * @return number the current mark for this question.
1788 * {@link get_fraction()} * {@link get_max_mark()}.
1789 */
1790 public function get_current_manual_mark() {
1791 $mark = self::get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
1792 if (is_null($mark)) {
1793 return $this->get_mark();
1794 } else {
1795 return $mark;
1796 }
1797 }
1798
1799 /**
1800 * @param number|null $fraction a fraction.
1801 * @return number|null the corresponding mark.
1802 */
1803 public function fraction_to_mark($fraction) {
1804 if (is_null($fraction)) {
1805 return null;
1806 }
1807 return $fraction * $this->maxmark;
1808 }
1809
1810 /** @return number the maximum mark possible for this question attempt. */
1811 public function get_max_mark() {
1812 return $this->maxmark;
1813 }
1814
1815 /** @return number the maximum mark possible for this question attempt. */
1816 public function get_min_fraction() {
1817 if (is_null($this->minfraction)) {
88f0eb15 1818 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
d1b7e03d
TH
1819 }
1820 return $this->minfraction;
1821 }
1822
1823 /**
1824 * The current mark, formatted to the stated number of decimal places. Uses
1825 * {@link format_float()} to format floats according to the current locale.
f7970e3c 1826 * @param int $dp number of decimal places.
d1b7e03d
TH
1827 * @return string formatted mark.
1828 */
1829 public function format_mark($dp) {
1830 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
1831 }
1832
1833 /**
1834 * The current mark, formatted to the stated number of decimal places. Uses
1835 * {@link format_float()} to format floats according to the current locale.
f7970e3c 1836 * @param int $dp number of decimal places.
d1b7e03d
TH
1837 * @return string formatted mark.
1838 */
1839 public function format_fraction_as_mark($fraction, $dp) {
1840 return format_float($this->fraction_to_mark($fraction), $dp);
1841 }
1842
1843 /**
1844 * The maximum mark for this question attempt, formatted to the stated number
1845 * of decimal places. Uses {@link format_float()} to format floats according
1846 * to the current locale.
f7970e3c 1847 * @param int $dp number of decimal places.
d1b7e03d
TH
1848 * @return string formatted maximum mark.
1849 */
1850 public function format_max_mark($dp) {
1851 return format_float($this->maxmark, $dp);
1852 }
1853
1854 /**
1855 * Return the hint that applies to the question in its current state, or null.
1856 * @return question_hint|null
1857 */
1858 public function get_applicable_hint() {
1859 return $this->behaviour->get_applicable_hint();
1860 }
1861
1862 /**
1863 * Produce a plain-text summary of what the user did during a step.
1864 * @param question_attempt_step $step the step in quetsion.
1865 * @return string a summary of what was done during that step.
1866 */
1867 public function summarise_action(question_attempt_step $step) {
1868 return $this->behaviour->summarise_action($step);
1869 }
1870
7a719748
TH
1871 /**
1872 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
1873 * for content belonging to this question.
1874 * @param string $text the content to output.
1875 * @param string $component the component name (normally 'question' or 'qtype_...')
1876 * @param string $filearea the name of the file area.
f7970e3c 1877 * @param int $itemid the item id.
7a719748
TH
1878 */
1879 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
2b7da645 1880 return question_rewrite_question_urls($text,
56e82d99 1881 'pluginfile.php', $this->question->contextid, $component, $filearea,
7a719748 1882 array($this->get_usage_id(), $this->get_slot()), $itemid);
2b7da645
TH
1883 }
1884
d1b7e03d
TH
1885 /**
1886 * Get the {@link core_question_renderer}, in collaboration with appropriate
1887 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
1888 * HTML to display this question attempt in its current state.
1889 * @param question_display_options $options controls how the question is rendered.
1890 * @param string|null $number The question number to display.
1891 * @return string HTML fragment representing the question.
1892 */
2daffca5
TH
1893 public function render($options, $number, $page = null) {
1894 if (is_null($page)) {
1895 global $PAGE;
1896 $page = $PAGE;
1897 }
1898 $qoutput = $page->get_renderer('core', 'question');
1899 $qtoutput = $this->question->get_renderer($page);
d1b7e03d
TH
1900 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
1901 }
1902
1903 /**
1904 * Generate any bits of HTML that needs to go in the <head> tag when this question
1905 * attempt is displayed in the body.
1906 * @return string HTML fragment.
1907 */
2daffca5
TH
1908 public function render_head_html($page = null) {
1909 if (is_null($page)) {
1910 global $PAGE;
1911 $page = $PAGE;
1912 }
1913 // TODO go via behaviour.
1914 return $this->question->get_renderer($page)->head_code($this) .
1915 $this->behaviour->get_renderer($page)->head_code($this);
d1b7e03d
TH
1916 }
1917
1918 /**
1919 * Like {@link render_question()} but displays the question at the past step
1920 * indicated by $seq, rather than showing the latest step.
1921 *
f7970e3c 1922 * @param int $seq the seq number of the past state to display.
d1b7e03d
TH
1923 * @param question_display_options $options controls how the question is rendered.
1924 * @param string|null $number The question number to display. 'i' is a special
1925 * value that gets displayed as Information. Null means no number is displayed.
1926 * @return string HTML fragment representing the question.
1927 */
1928 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
1929 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
1930 return $restrictedqa->render($options, $number);
1931 }
1932
7a719748
TH
1933 /**
1934 * Checks whether the users is allow to be served a particular file.
1935 * @param question_display_options $options the options that control display of the question.
1936 * @param string $component the name of the component we are serving files for.
1937 * @param string $filearea the name of the file area.
1938 * @param array $args the remaining bits of the file path.
f7970e3c
TH
1939 * @param bool $forcedownload whether the user must be forced to download the file.
1940 * @return bool true if the user can access this file.
7a719748
TH
1941 */
1942 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
1943 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
1944 }
1945
d1b7e03d
TH
1946 /**
1947 * Add a step to this question attempt.
1948 * @param question_attempt_step $step the new step.
1949 */
1950 protected function add_step(question_attempt_step $step) {
1951 $this->steps[] = $step;
1952 end($this->steps);
1953 $this->observer->notify_step_added($step, $this, key($this->steps));
1954 }
1955
1956 /**
ef31a283 1957 * Start this question attempt.
d1b7e03d
TH
1958 *
1959 * You should not call this method directly. Call
1960 * {@link question_usage_by_activity::start_question()} instead.
1961 *
1962 * @param string|question_behaviour $preferredbehaviour the name of the
1963 * desired archetypal behaviour, or an actual model instance.
ef31a283
TH
1964 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
1965 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
1966 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
d1b7e03d
TH
1967 */
1968 public function start($preferredbehaviour, $submitteddata = array(), $timestamp = null, $userid = null) {
1969 // Initialise the behaviour.
1970 if (is_string($preferredbehaviour)) {
1971 $this->behaviour =
1972 $this->question->make_behaviour($this, $preferredbehaviour);
1973 } else {
1974 $class = get_class($preferredbehaviour);
1975 $this->behaviour = new $class($this, $preferredbehaviour);
1976 }
1977
1978 // Record the minimum fraction.
1979 $this->minfraction = $this->behaviour->get_min_fraction();
1980
1981 // Initialise the first step.
1982 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid);
1983 $firststep->set_state(question_state::$todo);
ef31a283
TH
1984 if ($submitteddata) {
1985 $this->question->apply_attempt_state($firststep);
1986 } else {
1987 $this->behaviour->init_first_step($firststep);
1988 }
d1b7e03d
TH
1989 $this->add_step($firststep);
1990
1991 // Record questionline and correct answer.
d1b7e03d
TH
1992 $this->questionsummary = $this->behaviour->get_question_summary();
1993 $this->rightanswer = $this->behaviour->get_right_answer_summary();
1994 }
1995
1996 /**
1997 * Start this question attempt, starting from the point that the previous
1998 * attempt $oldqa had reached.
1999 *
2000 * You should not call this method directly. Call
2001 * {@link question_usage_by_activity::start_question_based_on()} instead.
2002 *
2003 * @param question_attempt $oldqa a previous attempt at this quetsion that
2004 * defines the starting point.
2005 */
2006 public function start_based_on(question_attempt $oldqa) {
2007 $this->start($oldqa->behaviour, $oldqa->get_resume_data());
2008 }
2009
2010 /**
2011 * Used by {@link start_based_on()} to get the data needed to start a new
2012 * attempt from the point this attempt has go to.
2013 * @return array name => value pairs.
2014 */
2015 protected function get_resume_data() {
2016 return $this->behaviour->get_resume_data();
2017 }
2018
2019 /**
2020 * Get a particular parameter from the current request. A wrapper round
2021 * {@link optional_param()}, except that the results is returned without
2022 * slashes.
2023 * @param string $name the paramter name.
f7970e3c 2024 * @param int $type one of the PARAM_... constants.
d1b7e03d
TH
2025 * @param array $postdata (optional, only inteded for testing use) take the
2026 * data from this array, instead of from $_POST.
2027 * @return mixed the requested value.
2028 */
2029 public static function get_submitted_var($name, $type, $postdata = null) {
2030 // Special case to work around PARAM_NUMBER converting '' to 0.
2031 if ($type == self::PARAM_MARK) {
2032 $mark = self::get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata);
2033 if ($mark === '') {
2034 return $mark;
2035 } else {
2036 return self::get_submitted_var($name, PARAM_NUMBER, $postdata);
2037 }
2038 }
2039
2040 if (is_null($postdata)) {
2041 $var = optional_param($name, null, $type);
2042 } else if (array_key_exists($name, $postdata)) {
2043 $var = clean_param($postdata[$name], $type);
2044 } else {
2045 $var = null;
2046 }
caeeff07 2047
d1b7e03d 2048 if (is_string($var)) {
caeeff07 2049 $var = $var;
d1b7e03d 2050 }
caeeff07 2051
d1b7e03d
TH
2052 return $var;
2053 }
2054
2055 /**
2056 * Get any data from the request that matches the list of expected params.
2057 * @param array $expected variable name => PARAM_... constant.
2058 * @param string $extraprefix '-' or ''.
2059 * @return array name => value.
2060 */
2061 protected function get_expected_data($expected, $postdata, $extraprefix) {
2062 $submitteddata = array();
2063 foreach ($expected as $name => $type) {
2064 $value = self::get_submitted_var(
2065 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
2066 if (!is_null($value)) {
2067 $submitteddata[$extraprefix . $name] = $value;
2068 }
2069 }
2070 return $submitteddata;
2071 }
2072
2073 /**
2074 * Get all the submitted question type data for this question, whithout checking
2075 * that it is valid or cleaning it in any way.
2076 * @return array name => value.
2077 */
2078 protected function get_all_submitted_qt_vars($postdata) {
2079 if (is_null($postdata)) {
2080 $postdata = $_POST;
2081 }
2082
2083 $pattern = '/^' . preg_quote($this->get_field_prefix()) . '[^-:]/';
2084 $prefixlen = strlen($this->get_field_prefix());
2085
2086 $submitteddata = array();
2087 foreach ($_POST as $name => $value) {
2088 if (preg_match($pattern, $name)) {
2089 $submitteddata[substr($name, $prefixlen)] = $value;
2090 }
2091 }
2092
2093 return $submitteddata;
2094 }
2095
2096 /**
2097 * Get all the sumbitted data belonging to this question attempt from the
2098 * current request.
2099 * @param array $postdata (optional, only inteded for testing use) take the
2100 * data from this array, instead of from $_POST.
2101 * @return array name => value pairs that could be passed to {@link process_action()}.
2102 */
2103 public function get_submitted_data($postdata = null) {
2104 $submitteddata = $this->get_expected_data(
2105 $this->behaviour->get_expected_data(), $postdata, '-');
2106
2107 $expected = $this->behaviour->get_expected_qt_data();
2108 if ($expected === self::USE_RAW_DATA) {
2109 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
2110 } else {
2111 $submitteddata += $this->get_expected_data($expected, $postdata, '');
2112 }
2113 return $submitteddata;
2114 }
2115
2116 /**
2117 * Get a set of response data for this question attempt that would get the
2118 * best possible mark.
2119 * @return array name => value pairs that could be passed to {@link process_action()}.
2120 */
2121 public function get_correct_response() {
2122 $response = $this->question->get_correct_response();
2123 $imvars = $this->behaviour->get_correct_response();
2124 foreach ($imvars as $name => $value) {
2125 $response['-' . $name] = $value;
2126 }
2127 return $response;
2128 }
2129
2130 /**
2131 * Change the quetsion summary. Note, that this is almost never necessary.
2132 * This method was only added to work around a limitation of the Opaque
2133 * protocol, which only sends questionLine at the end of an attempt.
2134 * @param $questionsummary the new summary to set.
2135 */
2136 public function set_question_summary($questionsummary) {
2137 $this->questionsummary = $questionsummary;
2138 $this->observer->notify_attempt_modified($this);
2139 }
2140
2141 /**
2142 * @return string a simple textual summary of the question that was asked.
2143 */
2144 public function get_question_summary() {
2145 return $this->questionsummary;
2146 }
2147
2148 /**
2149 * @return string a simple textual summary of response given.
2150 */
2151 public function get_response_summary() {
2152 return $this->responsesummary;
2153 }
2154
2155 /**
2156 * @return string a simple textual summary of the correct resonse.
2157 */
2158 public function get_right_answer_summary() {
2159 return $this->rightanswer;
2160 }
2161
2162 /**
2163 * Perform the action described by $submitteddata.
2164 * @param array $submitteddata the submitted data the determines the action.
f7970e3c
TH
2165 * @param int $timestamp the time to record for the action. (If not given, use now.)
2166 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2167 */
2168 public function process_action($submitteddata, $timestamp = null, $userid = null) {
2169 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
2170 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
2171 $this->add_step($pendingstep);
2172 if ($pendingstep->response_summary_changed()) {
2173 $this->responsesummary = $pendingstep->get_new_response_summary();
2174 }
2175 }
2176 }
2177
2178 /**
2179 * Perform a finish action on this question attempt. This corresponds to an
2180 * external finish action, for example the user pressing Submit all and finish
2181 * in the quiz, rather than using one of the controls that is part of the
2182 * question.
2183 *
f7970e3c
TH
2184 * @param int $timestamp the time to record for the action. (If not given, use now.)
2185 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2186 */
2187 public function finish($timestamp = null, $userid = null) {
2188 $this->process_action(array('-finish' => 1), $timestamp, $userid);
2189 }
2190
2191 /**
2192 * Perform a regrade. This replays all the actions from $oldqa into this
2193 * attempt.
2194 * @param question_attempt $oldqa the attempt to regrade.
f7970e3c 2195 * @param bool $finished whether the question attempt should be forced to be finished
d1b7e03d
TH
2196 * after the regrade, or whether it may still be in progress (default false).
2197 */
2198 public function regrade(question_attempt $oldqa, $finished) {
2199 $first = true;
2200 foreach ($oldqa->get_step_iterator() as $step) {
2201 if ($first) {
2202 $first = false;
2203 $this->start($oldqa->behaviour, $step->get_all_data(),
2204 $step->get_timecreated(), $step->get_user_id());
2205 } else {
2206 $this->process_action($step->get_submitted_data(),
2207 $step->get_timecreated(), $step->get_user_id());
2208 }
2209 }
2210 if ($finished) {
2211 $this->finish();
2212 }
2213 }
2214
2215 /**
2216 * Perform a manual grading action on this attempt.
2217 * @param $comment the comment being added.
2218 * @param $mark the new mark. (Optional, if not given, then only a comment is added.)
f7970e3c
TH
2219 * @param int $timestamp the time to record for the action. (If not given, use now.)
2220 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2221 * @return unknown_type
2222 */
2223 public function manual_grade($comment, $mark, $timestamp = null, $userid = null) {
2224 $submitteddata = array('-comment' => $comment);
2225 if (!is_null($mark)) {
2226 $submitteddata['-mark'] = $mark;
2227 $submitteddata['-maxmark'] = $this->maxmark;
2228 }
2229 $this->process_action($submitteddata, $timestamp, $userid);
2230 }
2231
f7970e3c 2232 /** @return bool Whether this question attempt has had a manual comment added. */
d1b7e03d
TH
2233 public function has_manual_comment() {
2234 foreach ($this->steps as $step) {
2235 if ($step->has_behaviour_var('comment')) {
2236 return true;
2237 }
2238 }
2239 return false;
2240 }
2241
2242 /**
7a719748
TH
2243 * @return array(string, int) the most recent manual comment that was added
2244 * to this question, and the FORMAT_... it is.
d1b7e03d
TH
2245 */
2246 public function get_manual_comment() {
2247 foreach ($this->get_reverse_step_iterator() as $step) {
2248 if ($step->has_behaviour_var('comment')) {
7a719748
TH
2249 return array($step->get_behaviour_var('comment'),
2250 $step->get_behaviour_var('commentformat'));
d1b7e03d
TH
2251 }
2252 }
7a719748 2253 return array(null, null);
d1b7e03d
TH
2254 }
2255
2256 /**
2257 * @return array subpartid => object with fields
f9b0500f 2258 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
d1b7e03d
TH
2259 * ->response the actual response the student gave to this part, as a string.
2260 * ->fraction the credit awarded for this subpart, may be null.
2261 * returns an empty array if no analysis is possible.
2262 */
2263 public function classify_response() {
2264 return $this->behaviour->classify_response();
2265 }
2266
2267 /**
2268 * Create a question_attempt_step from records loaded from the database.
2269 *
2270 * For internal use only.
2271 *
2272 * @param array $records Raw records loaded from the database.
f7970e3c 2273 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
2274 * @return question_attempt The newly constructed question_attempt_step.
2275 */
2276 public static function load_from_records(&$records, $questionattemptid,
2277 question_usage_observer $observer, $preferredbehaviour) {
2278 $record = current($records);
2279 while ($record->questionattemptid != $questionattemptid) {
2280 $record = next($records);
2281 if (!$record) {
88f0eb15 2282 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
d1b7e03d
TH
2283 }
2284 }
2285
2286 try {
2287 $question = question_bank::load_question($record->questionid);
2288 } catch (Exception $e) {
2289 // The question must have been deleted somehow. Create a missing
2290 // question to use in its place.
2291 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
2292 $record->questionid, $record->maxmark + 0);
2293 }
2294
7a719748 2295 $qa = new question_attempt($question, $record->questionusageid,
2daffca5 2296 null, $record->maxmark + 0);
d1b7e03d
TH
2297 $qa->set_database_id($record->questionattemptid);
2298 $qa->set_number_in_usage($record->slot);
2299 $qa->minfraction = $record->minfraction + 0;
2300 $qa->set_flagged($record->flagged);
2301 $qa->questionsummary = $record->questionsummary;
2302 $qa->rightanswer = $record->rightanswer;
2303 $qa->responsesummary = $record->responsesummary;
2304 $qa->timemodified = $record->timemodified;
2305
2306 $qa->behaviour = question_engine::make_behaviour(
2307 $record->behaviour, $qa, $preferredbehaviour);
2308
2309 $i = 0;
2310 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
2311 $qa->steps[$i] = question_attempt_step::load_from_records($records, $record->attemptstepid);
2312 if ($i == 0) {
ef31a283 2313 $question->apply_attempt_state($qa->steps[0]);
d1b7e03d
TH
2314 }
2315 $i++;
2316 $record = current($records);
2317 }
2318
2319 $qa->observer = $observer;
2320
2321 return $qa;
2322 }
2323}
2324
2325
2326/**
2327 * This subclass of question_attempt pretends that only part of the step history
2328 * exists. It is used for rendering the question in past states.
2329 *
2330 * All methods that try to modify the question_attempt throw exceptions.
2331 *
f7970e3c 2332 * @copyright 2010 The Open University
017bc1d9 2333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2334 */
2335class question_attempt_with_restricted_history extends question_attempt {
2336 /**
2337 * @var question_attempt the underlying question_attempt.
2338 */
2339 protected $baseqa;
2340
2341 /**
2342 * Create a question_attempt_with_restricted_history
2343 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
f7970e3c 2344 * @param int $lastseq the index of the last step to include.
d1b7e03d
TH
2345 * @param string $preferredbehaviour the preferred behaviour. It is slightly
2346 * annoyting that this needs to be passed, but unavoidable for now.
2347 */
2348 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
2349 if ($lastseq < 0 || $lastseq >= $baseqa->get_num_steps()) {
2350 throw new coding_exception('$seq out of range', $seq);
2351 }
2352
2353 $this->baseqa = $baseqa;
2354 $this->steps = array_slice($baseqa->steps, 0, $lastseq + 1);
2355 $this->observer = new question_usage_null_observer();
2356
2357 // This should be a straight copy of all the remaining fields.
2358 $this->id = $baseqa->id;
2359 $this->usageid = $baseqa->usageid;
2360 $this->slot = $baseqa->slot;
2361 $this->question = $baseqa->question;
2362 $this->maxmark = $baseqa->maxmark;
2363 $this->minfraction = $baseqa->minfraction;
2364 $this->questionsummary = $baseqa->questionsummary;
2365 $this->responsesummary = $baseqa->responsesummary;
2366 $this->rightanswer = $baseqa->rightanswer;
2367 $this->flagged = $baseqa->flagged;
2368
2369 // Except behaviour, where we need to create a new one.
2370 $this->behaviour = question_engine::make_behaviour(
2371 $baseqa->get_behaviour_name(), $this, $preferredbehaviour);
2372 }
2373
2374 public function get_full_step_iterator() {
2375 return $this->baseqa->get_step_iterator();
2376 }
2377
2378 protected function add_step(question_attempt_step $step) {
2379 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2380 }
2381 public function process_action($submitteddata, $timestamp = null, $userid = null) {
2382 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2383 }
2384 public function start($preferredbehaviour, $submitteddata = array(), $timestamp = null, $userid = null) {
2385 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2386 }
2387
2388 public function set_database_id($id) {
2389 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2390 }
2391 public function set_flagged($flagged) {
2392 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2393 }
2394 public function set_number_in_usage($slot) {
2395 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2396 }
2397 public function set_question_summary($questionsummary) {
2398 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2399 }
2400 public function set_usage_id($usageid) {
2401 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2402 }
2403}
2404
2405
2406/**
2407 * A class abstracting access to the {@link question_attempt::$states} array.
2408 *
2409 * This is actively linked to question_attempt. If you add an new step
2410 * mid-iteration, then it will be included.
2411 *
017bc1d9
TH
2412 * @copyright 2009 The Open University
2413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2414 */
2415class question_attempt_step_iterator implements Iterator, ArrayAccess {
2416 /** @var question_attempt the question_attempt being iterated over. */
2417 protected $qa;
2418 /** @var integer records the current position in the iteration. */
2419 protected $i;
2420
2421 /**
2422 * Do not call this constructor directly.
2423 * Use {@link question_attempt::get_step_iterator()}.
2424 * @param question_attempt $qa the attempt to iterate over.
2425 */
2426 public function __construct(question_attempt $qa) {
2427 $this->qa = $qa;
2428 $this->rewind();
2429 }
2430
2431 /** @return question_attempt_step */
2432 public function current() {
2433 return $this->offsetGet($this->i);
2434 }
f7970e3c 2435 /** @return int */
d1b7e03d
TH
2436 public function key() {
2437 return $this->i;
2438 }
2439 public function next() {
2440 ++$this->i;
2441 }
2442 public function rewind() {
2443 $this->i = 0;
2444 }
f7970e3c 2445 /** @return bool */
d1b7e03d
TH
2446 public function valid() {
2447 return $this->offsetExists($this->i);
2448 }
2449
f7970e3c 2450 /** @return bool */
d1b7e03d
TH
2451 public function offsetExists($i) {
2452 return $i >= 0 && $i < $this->qa->get_num_steps();
2453 }
2454 /** @return question_attempt_step */
2455 public function offsetGet($i) {
2456 return $this->qa->get_step($i);
2457 }
2458 public function offsetSet($offset, $value) {
88f0eb15 2459 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
d1b7e03d
TH
2460 }
2461 public function offsetUnset($offset) {
88f0eb15 2462 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
d1b7e03d
TH
2463 }
2464}
2465
2466
2467/**
2468 * A variant of {@link question_attempt_step_iterator} that iterates through the
2469 * steps in reverse order.
2470 *
017bc1d9
TH
2471 * @copyright 2009 The Open University
2472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2473 */
2474class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
2475 public function next() {
2476 --$this->i;
2477 }
2478
2479 public function rewind() {
2480 $this->i = $this->qa->get_num_steps() - 1;
2481 }
2482}
2483
2484
2485/**
2486 * Stores one step in a {@link question_attempt}.
2487 *
2488 * The most important attributes of a step are the state, which is one of the
2489 * {@link question_state} constants, the fraction, which may be null, or a
2490 * number bewteen the attempt's minfraction and 1.0, and the array of submitted
2491 * data, about which more later.
2492 *
2493 * A step also tracks the time it was created, and the user responsible for
2494 * creating it.
2495 *
2496 * The submitted data is basically just an array of name => value pairs, with
2497 * certain conventions about the to divide the variables into four = two times two
2498 * categories.
2499 *
2500 * Variables may either belong to the behaviour, in which case the
2501 * name starts with a '-', or they may belong to the question type in which case
2502 * they name does not start with a '-'.
2503 *
2504 * Second, variables may either be ones that came form the original request, in
2505 * which case the name does not start with an _, or they are cached values that
2506 * were created during processing, in which case the name does start with an _.
2507 *
2508 * That is, each name will start with one of '', '_'. '-' or '-_'. The remainder
2509 * of the name should match the regex [a-z][a-z0-9]*.
2510 *
2511 * These variables can be accessed with {@link get_behaviour_var()} and {@link get_qt_var()},
2512 * - to be clear, ->get_behaviour_var('x') gets the variable with name '-x' -
2513 * and values whose names start with '_' can be set using {@link set_behaviour_var()}
2514 * and {@link set_qt_var()}. There are some other methods like {@link has_behaviour_var()}
2515 * to check wether a varaible with a particular name is set, and {@link get_behaviour_data()}
2516 * to get all the behaviour data as an associative array.
2517 *
017bc1d9
TH
2518 * @copyright 2009 The Open University
2519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2520 */
2521class question_attempt_step {
2522 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
2523 private $id = null;
2524
2525 /** @var question_state one of the {@link question_state} constants. The state after this step. */
2526 private $state;
2527
2528 /** @var null|number the fraction (grade on a scale of minfraction .. 1.0) or null. */
2529 private $fraction = null;
2530
2531 /** @var integer the timestamp when this step was created. */
2532 private $timecreated;
2533
2534 /** @var integer the id of the user resonsible for creating this step. */
2535 private $userid;
2536
2537 /** @var array name => value pairs. The submitted data. */
2538 private $data;
2539
caeeff07
TH
2540 /** @var array name => array of {@link stored_file}s. Caches the contents of file areas. */
2541 private $files = array();
2542
d1b7e03d
TH
2543 /**
2544 * You should not need to call this constructor in your own code. Steps are
2545 * normally created by {@link question_attempt} methods like
2546 * {@link question_attempt::process_action()}.
2547 * @param array $data the submitted data that defines this step.
f7970e3c
TH
2548 * @param int $timestamp the time to record for the action. (If not given, use now.)
2549 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2550 */
2551 public function __construct($data = array(), $timecreated = null, $userid = null) {
2552 global $USER;
2553 $this->state = question_state::$unprocessed;
2554 $this->data = $data;
2555 if (is_null($timecreated)) {
2556 $this->timecreated = time();
2557 } else {
2558 $this->timecreated = $timecreated;
2559 }
2560 if (is_null($userid)) {
2561 $this->userid = $USER->id;
2562 } else {
2563 $this->userid = $userid;
2564 }
2565 }
2566
2567 /** @return question_state The state after this step. */
2568 public function get_state() {
2569 return $this->state;
2570 }
2571
2572 /**
2573 * Set the state. Normally only called by behaviours.
2574 * @param question_state $state one of the {@link question_state} constants.
2575 */
2576 public function set_state($state) {
2577 $this->state = $state;
2578 }
2579
2580 /**
2581 * @return null|number the fraction (grade on a scale of minfraction .. 1.0)
2582 * or null if this step has not been marked.
2583 */
2584 public function get_fraction() {
2585 return $this->fraction;
2586 }
2587
2588 /**
2589 * Set the fraction. Normally only called by behaviours.
2590 * @param null|number $fraction the fraction to set.
2591 */
2592 public function set_fraction($fraction) {
2593 $this->fraction = $fraction;
2594 }
2595
f7970e3c 2596 /** @return int the id of the user resonsible for creating this step. */
d1b7e03d
TH
2597 public function get_user_id() {
2598 return $this->userid;
2599 }
2600
f7970e3c 2601 /** @return int the timestamp when this step was created. */
d1b7e03d
TH
2602 public function get_timecreated() {
2603 return $this->timecreated;
2604 }
2605
2606 /**
2607 * @param string $name the name of a question type variable to look for in the submitted data.
f7970e3c 2608 * @return bool whether a variable with this name exists in the question type data.
d1b7e03d
TH
2609 */
2610 public function has_qt_var($name) {
2611 return array_key_exists($name, $this->data);
2612 }
2613
2614 /**
2615 * @param string $name the name of a question type variable to look for in the submitted data.
2616 * @return string the requested variable, or null if the variable is not set.
2617 */
2618 public function get_qt_var($name) {
2619 if (!$this->has_qt_var($name)) {
2620 return null;
2621 }
2622 return $this->data[$name];
2623 }
2624
2625 /**
2626 * Set a cached question type variable.
2627 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
2628 * @param string $value the value to set.
2629 */
2630 public function set_qt_var($name, $value) {
2631 if ($name[0] != '_') {
88f0eb15 2632 throw new coding_exception('Cannot set question type data ' . $name . ' on an attempt step. You can only set variables with names begining with _.');
d1b7e03d
TH
2633 }
2634 $this->data[$name] = $value;
2635 }
2636
caeeff07
TH
2637 /**
2638 * Get the latest set of files for a particular question type variable of
2639 * type question_attempt::PARAM_FILES.
2640 *
2641 * @param string $name the name of the associated variable.
2642 * @return array of {@link stored_files}.
2643 */
2644 public function get_qt_files($name, $contextid) {
2645 if (array_key_exists($name, $this->files)) {
2646 return $this->files[$name];
2647 }
2648
2649 if (!$this->has_qt_var($name)) {
2650 $this->files[$name] = array();
2651 return array();
2652 }
2653
2654 $fs = get_file_storage();
2655 $this->files[$name] = $fs->get_area_files($contextid, 'question',
2656 'response_' . $name, $this->id, 'sortorder', false);
2657
2658 return $this->files[$name];
2659 }
2660
d1b7e03d
TH
2661 /**
2662 * Get all the question type variables.
2663 * @param array name => value pairs.
2664 */
2665 public function get_qt_data() {
2666 $result = array();
2667 foreach ($this->data as $name => $value) {
2668 if ($name[0] != '-' && $name[0] != ':') {
2669 $result[$name] = $value;
2670 }
2671 }
2672 return $result;
2673 }
2674
2675 /**
2676 * @param string $name the name of an behaviour variable to look for in the submitted data.
f7970e3c 2677 * @return bool whether a variable with this name exists in the question type data.
d1b7e03d
TH
2678 */
2679 public function has_behaviour_var($name) {
2680 return array_key_exists('-' . $name, $this->data);
2681 }
2682
2683 /**
2684 * @param string $name the name of an behaviour variable to look for in the submitted data.
2685 * @return string the requested variable, or null if the variable is not set.
2686 */
2687 public function get_behaviour_var($name) {
2688 if (!$this->has_behaviour_var($name)) {
2689 return null;
2690 }
2691 return $this->data['-' . $name];
2692 }
2693
2694 /**
2695 * Set a cached behaviour variable.
2696 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
2697 * @param string $value the value to set.
2698 */
2699 public function set_behaviour_var($name, $value) {
2700 if ($name[0] != '_') {
88f0eb15 2701 throw new coding_exception('Cannot set question type data ' . $name . ' on an attempt step. You can only set variables with names begining with _.');
d1b7e03d
TH
2702 }
2703 return $this->data['-' . $name] = $value;
2704 }
2705
2706 /**
2707 * Get all the behaviour variables.
2708 * @param array name => value pairs.
2709 */
2710 public function get_behaviour_data() {
2711 $result = array();
2712 foreach ($this->data as $name => $value) {
2713 if ($name[0] == '-') {
2714 $result[substr($name, 1)] = $value;
2715 }
2716 }
2717 return $result;
2718 }
2719
2720 /**
2721 * Get all the submitted data, but not the cached data. behaviour
2722 * variables have the - at the start of their name. This is only really
2723 * intended for use by {@link question_attempt::regrade()}, it should not
2724 * be considered part of the public API.
2725 * @param array name => value pairs.
2726 */
2727 public function get_submitted_data() {
2728 $result = array();
2729 foreach ($this->data as $name => $value) {
2730 if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
2731 continue;
2732 }
2733 $result[$name] = $value;
2734 }
2735 return $result;
2736 }
2737
2738 /**
2739 * Get all the data. behaviour variables have the ! at the start of
2740 * their name. This is only intended for internal use, for example by
2741 * {@link question_engine_data_mapper::insert_question_attempt_step()},
2742 * however, it can ocasionally be useful in test code. It should not be
2743 * considered part of the public API of this class.
2744 * @param array name => value pairs.
2745 */
2746 public function get_all_data() {
2747 return $this->data;
2748 }
2749
2750 /**
2751 * Create a question_attempt_step from records loaded from the database.
2752 * @param array $records Raw records loaded from the database.
f7970e3c 2753 * @param int $stepid The id of the records to extract.
d1b7e03d
TH
2754 * @return question_attempt_step The newly constructed question_attempt_step.
2755 */
2756 public static function load_from_records(&$records, $attemptstepid) {
2757 $currentrec = current($records);
2758 while ($currentrec->attemptstepid != $attemptstepid) {
2759 $currentrec = next($records);
2760 if (!$currentrec) {
88f0eb15 2761 throw new coding_exception("Question attempt step $attemptstepid not found in the database.");
d1b7e03d
TH
2762 }
2763 }
2764
2765 $record = $currentrec;
2766 $data = array();
2767 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
2768 if ($currentrec->name) {
2769 $data[$currentrec->name] = $currentrec->value;
2770 }
2771 $currentrec = next($records);
2772 }
2773
2774 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
2775 $step->state = question_state::get($record->state);
caeeff07 2776 $step->id = $record->attemptstepid;
d1b7e03d
TH
2777 if (!is_null($record->fraction)) {
2778 $step->fraction = $record->fraction + 0;
2779 }
2780 return $step;
2781 }
2782}
2783
2784
2785/**
2786 * A subclass with a bit of additional funcitonality, for pending steps.
2787 *
f7970e3c 2788 * @copyright 2010 The Open University
017bc1d9 2789 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2790 */
2791class question_attempt_pending_step extends question_attempt_step {
2792 /** @var string . */
2793 protected $newresponsesummary = null;
2794
2795 /**
2796 * If as a result of processing this step, the response summary for the
2797 * question attempt should changed, you should call this method to set the
2798 * new summary.
2799 * @param string $responsesummary the new response summary.
2800 */
2801 public function set_new_response_summary($responsesummary) {
2802 $this->newresponsesummary = $responsesummary;
2803 }
2804
2805 /** @return string the new response summary, if any. */
2806 public function get_new_response_summary() {
2807 return $this->newresponsesummary;
2808 }
2809
2810 /** @return string whether this step changes the response summary. */
2811 public function response_summary_changed() {
2812 return !is_null($this->newresponsesummary);
2813 }
2814}
2815
2816
2817/**
2818 * A subclass of {@link question_attempt_step} that cannot be modified.
2819 *
017bc1d9
TH
2820 * @copyright 2009 The Open University
2821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2822 */
2823class question_attempt_step_read_only extends question_attempt_step {
2824 public function set_state($state) {
2825 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2826 }
2827 public function set_fraction($fraction) {
2828 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2829 }
2830 public function set_qt_var($name, $value) {
2831 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2832 }
2833 public function set_behaviour_var($name, $value) {
2834 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2835 }
2836}
2837
2838
2839/**
2840 * A null {@link question_attempt_step} returned from
2841 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
2842 * created and there is no acutal step.
2843 *
017bc1d9
TH
2844 * @copyright 2009 The Open University
2845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2846 */
2847class question_null_step {
2848 public function get_state() {
2849 return question_state::$notstarted;
2850 }
2851
2852 public function set_state($state) {
88f0eb15 2853 throw new coding_exception('This question has not been started.');
d1b7e03d
TH
2854 }
2855
2856 public function get_fraction() {
2857 return null;
2858 }
2859}
2860
2861
2862/**
2863 * Interface for things that want to be notified of signficant changes to a
2864 * {@link question_usage_by_activity}.
2865 *
2866 * A question behaviour controls the flow of actions a student can
2867 * take as they work through a question, and later, as a teacher manually grades it.
2868 *
017bc1d9
TH
2869 * @copyright 2009 The Open University
2870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2871 */
2872interface question_usage_observer {
2873 /** Called when a field of the question_usage_by_activity is changed. */
2874 public function notify_modified();
2875
2876 /**
2877 * Called when the fields of a question attempt in this usage are modified.
2878 * @param question_attempt $qa the newly added question attempt.
2879 */
2880 public function notify_attempt_modified(question_attempt $qa);
2881
2882 /**
2883 * Called when a new question attempt is added to this usage.
2884 * @param question_attempt $qa the newly added question attempt.
2885 */
2886 public function notify_attempt_added(question_attempt $qa);
2887
2888 /**
2889 * Called we want to delete the old step records for an attempt, prior to
2890 * inserting newones. This is used by regrading.
2891 * @param question_attempt $qa the question attempt to delete the steps for.
2892 */
2893 public function notify_delete_attempt_steps(question_attempt $qa);
2894
2895 /**
2896 * Called when a new step is added to a question attempt in this usage.
2897 * @param $step the new step.
2898 * @param $qa the usage it is being added to.
2899 * @param $seq the sequence number of the new step.
2900 */
2901 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq);
2902}
2903
2904
2905/**
2906 * Null implmentation of the {@link question_usage_watcher} interface.
2907 * Does nothing.
2908 *
017bc1d9
TH
2909 * @copyright 2009 The Open University
2910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2911 */
2912class question_usage_null_observer implements question_usage_observer {
2913 public function notify_modified() {
2914 }
2915 public function notify_attempt_modified(question_attempt $qa) {
2916 }
2917 public function notify_attempt_added(question_attempt $qa) {
2918 }
2919 public function notify_delete_attempt_steps(question_attempt $qa) {
2920 }
2921 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
2922 }
2923}
2924
2925
2926/**
2927 * Useful functions for writing question types and behaviours.
2928 *
2929 * @copyright 2010 The Open University
017bc1d9 2930 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2931 */
2932abstract class question_utils {
2933 /**
2934 * Tests to see whether two arrays have the same keys, with the same values
2935 * (as compared by ===) for each key. However, the order of the arrays does
2936 * not have to be the same.
2937 * @param array $array1 the first array.
2938 * @param array $array2 the second array.
f7970e3c 2939 * @return bool whether the two arrays have the same keys with the same
d1b7e03d
TH
2940 * corresponding values.
2941 */
2942 public static function arrays_have_same_keys_and_values(array $array1, array $array2) {
2943 if (count($array1) != count($array2)) {
2944 return false;
2945 }
2946 foreach ($array1 as $key => $value1) {
2947 if (!array_key_exists($key, $array2)) {
2948 return false;
2949 }
2950 if (((string) $value1) !== ((string) $array2[$key])) {
2951 return false;
2952 }
2953 }
2954 return true;
2955 }
2956
2957 /**
2958 * Tests to see whether two arrays have the same value at a particular key.
2959 * This method will return true if:
2960 * 1. Neither array contains the key; or
2961 * 2. Both arrays contain the key, and the corresponding values compare
2962 * identical when cast to strings and compared with ===.
2963 * @param array $array1 the first array.
2964 * @param array $array2 the second array.
2965 * @param string $key an array key.
f7970e3c 2966 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
2967 * one) for a given key.
2968 */
2969 public static function arrays_same_at_key(array $array1, array $array2, $key) {
2970 if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
2971 return ((string) $array1[$key]) === ((string) $array2[$key]);
2972 }
2973 if (!array_key_exists($key, $array1) && !array_key_exists($key, $array2)) {
2974 return true;
2975 }
2976 return false;
2977 }
2978
2979 /**
2980 * Tests to see whether two arrays have the same value at a particular key.
2981 * Missing values are replaced by '', and then the values are cast to
2982 * strings and compared with ===.
2983 * @param array $array1 the first array.
2984 * @param array $array2 the second array.
2985 * @param string $key an array key.
f7970e3c 2986 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
2987 * one) for a given key.
2988 */
2989 public static function arrays_same_at_key_missing_is_blank(
2990 array $array1, array $array2, $key) {
2991 if (array_key_exists($key, $array1)) {
2992 $value1 = $array1[$key];
2993 } else {
2994 $value1 = '';
2995 }
2996 if (array_key_exists($key, $array2)) {
2997 $value2 = $array2[$key];
2998 } else {
2999 $value2 = '';
3000 }
3001 return ((string) $value1) === ((string) $value2);
3002 }
3003
3004 /**
3005 * Tests to see whether two arrays have the same value at a particular key.
3006 * Missing values are replaced by 0, and then the values are cast to
3007 * integers and compared with ===.
3008 * @param array $array1 the first array.
3009 * @param array $array2 the second array.
3010 * @param string $key an array key.
f7970e3c 3011 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
3012 * one) for a given key.
3013 */
3014 public static function arrays_same_at_key_integer(
3015 array $array1, array $array2, $key) {
3016 if (array_key_exists($key, $array1)) {
3017 $value1 = $array1[$key];
3018 } else {
3019 $value1 = 0;
3020 }
3021 if (array_key_exists($key, $array2)) {
3022 $value2 = $array2[$key];
3023 } else {
3024 $value2 = 0;
3025 }
3026 return ((integer) $value1) === ((integer) $value2);
3027 }
3028
3029 private static $units = array('', 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix');
3030 private static $tens = array('', 'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc');
3031 private static $hundreds = array('', 'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm');
3032 private static $thousands = array('', 'm', 'mm', 'mmm');
3033
3034 /**
3035 * Convert an integer to roman numerals.
f7970e3c 3036 * @param int $number an integer between 1 and 3999 inclusive. Anything else will throw an exception.
d1b7e03d
TH
3037 * @return string the number converted to lower case roman numerals.
3038 */
3039 public static function int_to_roman($number) {
3040 if (!is_integer($number) || $number < 1 || $number > 3999) {
3041 throw new coding_exception('Only integers between 0 and 3999 can be ' .
3042 'converted to roman numerals.', $number);
3043 }
3044
3045 return self::$thousands[$number / 1000 % 10] . self::$hundreds[$number / 100 % 10] .
3046 self::$tens[$number / 10 % 10] . self::$units[$number % 10];
3047 }
3048}