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