Merge branch 'MDL-64173-master' of git://github.com/bmbrands/moodle
[moodle.git] / question / engine / lib.php
blobb65ce4b9c24b56a1235369c1b103ad43af85809b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This defines the core classes of the Moodle question engine.
20 * @package moodlecore
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/filelib.php');
30 require_once(__DIR__ . '/questionusage.php');
31 require_once(__DIR__ . '/questionattempt.php');
32 require_once(__DIR__ . '/questionattemptstep.php');
33 require_once(__DIR__ . '/states.php');
34 require_once(__DIR__ . '/datalib.php');
35 require_once(__DIR__ . '/renderer.php');
36 require_once(__DIR__ . '/bank.php');
37 require_once(__DIR__ . '/../type/questiontypebase.php');
38 require_once(__DIR__ . '/../type/questionbase.php');
39 require_once(__DIR__ . '/../type/rendererbase.php');
40 require_once(__DIR__ . '/../behaviour/behaviourtypebase.php');
41 require_once(__DIR__ . '/../behaviour/behaviourbase.php');
42 require_once(__DIR__ . '/../behaviour/rendererbase.php');
43 require_once($CFG->libdir . '/questionlib.php');
46 /**
47 * This static class provides access to the other question engine classes.
49 * It provides functions for managing question behaviours), and for
50 * creating, loading, saving and deleting {@link question_usage_by_activity}s,
51 * which is the main class that is used by other code that wants to use questions.
53 * @copyright 2009 The Open University
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 abstract class question_engine {
57 /** @var array behaviour name => 1. Records which behaviours have been loaded. */
58 private static $loadedbehaviours = array();
60 /** @var array behaviour name => question_behaviour_type for this behaviour. */
61 private static $behaviourtypes = array();
63 /**
64 * Create a new {@link question_usage_by_activity}. The usage is
65 * created in memory. If you want it to persist, you will need to call
66 * {@link save_questions_usage_by_activity()}.
68 * @param string $component the plugin creating this attempt. For example mod_quiz.
69 * @param object $context the context this usage belongs to.
70 * @return question_usage_by_activity the newly created object.
72 public static function make_questions_usage_by_activity($component, $context) {
73 return new question_usage_by_activity($component, $context);
76 /**
77 * Load a {@link question_usage_by_activity} from the database, based on its id.
78 * @param int $qubaid the id of the usage to load.
79 * @param moodle_database $db a database connectoin. Defaults to global $DB.
80 * @return question_usage_by_activity loaded from the database.
82 public static function load_questions_usage_by_activity($qubaid, moodle_database $db = null) {
83 $dm = new question_engine_data_mapper($db);
84 return $dm->load_questions_usage_by_activity($qubaid);
87 /**
88 * Save a {@link question_usage_by_activity} to the database. This works either
89 * if the usage was newly created by {@link make_questions_usage_by_activity()}
90 * or loaded from the database using {@link load_questions_usage_by_activity()}
91 * @param question_usage_by_activity the usage to save.
92 * @param moodle_database $db a database connectoin. Defaults to global $DB.
94 public static function save_questions_usage_by_activity(question_usage_by_activity $quba, moodle_database $db = null) {
95 $dm = new question_engine_data_mapper($db);
96 $observer = $quba->get_observer();
97 if ($observer instanceof question_engine_unit_of_work) {
98 $observer->save($dm);
99 } else {
100 $dm->insert_questions_usage_by_activity($quba);
105 * Delete a {@link question_usage_by_activity} from the database, based on its id.
106 * @param int $qubaid the id of the usage to delete.
108 public static function delete_questions_usage_by_activity($qubaid) {
109 self::delete_questions_usage_by_activities(new qubaid_list(array($qubaid)));
113 * Delete {@link question_usage_by_activity}s from the database.
114 * @param qubaid_condition $qubaids identifies which questions usages to delete.
116 public static function delete_questions_usage_by_activities(qubaid_condition $qubaids) {
117 $dm = new question_engine_data_mapper();
118 $dm->delete_questions_usage_by_activities($qubaids);
122 * Change the maxmark for the question_attempt with number in usage $slot
123 * for all the specified question_attempts.
124 * @param qubaid_condition $qubaids Selects which usages are updated.
125 * @param int $slot the number is usage to affect.
126 * @param number $newmaxmark the new max mark to set.
128 public static function set_max_mark_in_attempts(qubaid_condition $qubaids,
129 $slot, $newmaxmark) {
130 $dm = new question_engine_data_mapper();
131 $dm->set_max_mark_in_attempts($qubaids, $slot, $newmaxmark);
135 * Validate that the manual grade submitted for a particular question is in range.
136 * @param int $qubaid the question_usage id.
137 * @param int $slot the slot number within the usage.
138 * @return bool whether the submitted data is in range.
140 public static function is_manual_grade_in_range($qubaid, $slot) {
141 $prefix = 'q' . $qubaid . ':' . $slot . '_';
142 $mark = question_utils::optional_param_mark($prefix . '-mark');
143 $maxmark = optional_param($prefix . '-maxmark', null, PARAM_FLOAT);
144 $minfraction = optional_param($prefix . ':minfraction', null, PARAM_FLOAT);
145 $maxfraction = optional_param($prefix . ':maxfraction', null, PARAM_FLOAT);
146 return $mark === '' ||
147 ($mark !== null && $mark >= $minfraction * $maxmark && $mark <= $maxfraction * $maxmark) ||
148 ($mark === null && $maxmark === null);
152 * @param array $questionids of question ids.
153 * @param qubaid_condition $qubaids ids of the usages to consider.
154 * @return boolean whether any of these questions are being used by any of
155 * those usages.
157 public static function questions_in_use(array $questionids, qubaid_condition $qubaids = null) {
158 if (is_null($qubaids)) {
159 return false;
161 $dm = new question_engine_data_mapper();
162 return $dm->questions_in_use($questionids, $qubaids);
166 * Get the number of times each variant has been used for each question in a list
167 * in a set of usages.
168 * @param array $questionids of question ids.
169 * @param qubaid_condition $qubaids ids of the usages to consider.
170 * @return array questionid => variant number => num uses.
172 public static function load_used_variants(array $questionids, qubaid_condition $qubaids) {
173 $dm = new question_engine_data_mapper();
174 return $dm->load_used_variants($questionids, $qubaids);
178 * Create an archetypal behaviour for a particular question attempt.
179 * Used by {@link question_definition::make_behaviour()}.
181 * @param string $preferredbehaviour the type of model required.
182 * @param question_attempt $qa the question attempt the model will process.
183 * @return question_behaviour an instance of appropriate behaviour class.
185 public static function make_archetypal_behaviour($preferredbehaviour, question_attempt $qa) {
186 if (!self::is_behaviour_archetypal($preferredbehaviour)) {
187 throw new coding_exception('The requested behaviour is not actually ' .
188 'an archetypal one.');
191 self::load_behaviour_class($preferredbehaviour);
192 $class = 'qbehaviour_' . $preferredbehaviour;
193 return new $class($qa, $preferredbehaviour);
197 * @param string $behaviour the name of a behaviour.
198 * @return array of {@link question_display_options} field names, that are
199 * not relevant to this behaviour before a 'finish' action.
201 public static function get_behaviour_unused_display_options($behaviour) {
202 return self::get_behaviour_type($behaviour)->get_unused_display_options();
206 * With this behaviour, is it possible that a question might finish as the student
207 * interacts with it, without a call to the {@link question_attempt::finish()} method?
208 * @param string $behaviour the name of a behaviour. E.g. 'deferredfeedback'.
209 * @return bool whether with this behaviour, questions may finish naturally.
211 public static function can_questions_finish_during_the_attempt($behaviour) {
212 return self::get_behaviour_type($behaviour)->can_questions_finish_during_the_attempt();
216 * Create a behaviour for a particular type. If that type cannot be
217 * found, return an instance of qbehaviour_missing.
219 * Normally you should use {@link make_archetypal_behaviour()}, or
220 * call the constructor of a particular model class directly. This method
221 * is only intended for use by {@link question_attempt::load_from_records()}.
223 * @param string $behaviour the type of model to create.
224 * @param question_attempt $qa the question attempt the model will process.
225 * @param string $preferredbehaviour the preferred behaviour for the containing usage.
226 * @return question_behaviour an instance of appropriate behaviour class.
228 public static function make_behaviour($behaviour, question_attempt $qa, $preferredbehaviour) {
229 try {
230 self::load_behaviour_class($behaviour);
231 } catch (Exception $e) {
232 self::load_behaviour_class('missing');
233 return new qbehaviour_missing($qa, $preferredbehaviour);
235 $class = 'qbehaviour_' . $behaviour;
236 return new $class($qa, $preferredbehaviour);
240 * Load the behaviour class(es) belonging to a particular model. That is,
241 * include_once('/question/behaviour/' . $behaviour . '/behaviour.php'), with a bit
242 * of checking.
243 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
245 public static function load_behaviour_class($behaviour) {
246 global $CFG;
247 if (isset(self::$loadedbehaviours[$behaviour])) {
248 return;
250 $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviour.php';
251 if (!is_readable($file)) {
252 throw new coding_exception('Unknown question behaviour ' . $behaviour);
254 include_once($file);
256 $class = 'qbehaviour_' . $behaviour;
257 if (!class_exists($class)) {
258 throw new coding_exception('Question behaviour ' . $behaviour .
259 ' does not define the required class ' . $class . '.');
262 self::$loadedbehaviours[$behaviour] = 1;
266 * Create a behaviour for a particular type. If that type cannot be
267 * found, return an instance of qbehaviour_missing.
269 * Normally you should use {@link make_archetypal_behaviour()}, or
270 * call the constructor of a particular model class directly. This method
271 * is only intended for use by {@link question_attempt::load_from_records()}.
273 * @param string $behaviour the type of model to create.
274 * @param question_attempt $qa the question attempt the model will process.
275 * @param string $preferredbehaviour the preferred behaviour for the containing usage.
276 * @return question_behaviour_type an instance of appropriate behaviour class.
278 public static function get_behaviour_type($behaviour) {
280 if (array_key_exists($behaviour, self::$behaviourtypes)) {
281 return self::$behaviourtypes[$behaviour];
284 self::load_behaviour_type_class($behaviour);
286 $class = 'qbehaviour_' . $behaviour . '_type';
287 if (class_exists($class)) {
288 self::$behaviourtypes[$behaviour] = new $class();
289 } else {
290 debugging('Question behaviour ' . $behaviour .
291 ' does not define the required class ' . $class . '.', DEBUG_DEVELOPER);
292 self::$behaviourtypes[$behaviour] = new question_behaviour_type_fallback($behaviour);
295 return self::$behaviourtypes[$behaviour];
299 * Load the behaviour type class for a particular behaviour. That is,
300 * include_once('/question/behaviour/' . $behaviour . '/behaviourtype.php').
301 * @param string $behaviour the behaviour name. For example 'interactive' or 'deferredfeedback'.
303 protected static function load_behaviour_type_class($behaviour) {
304 global $CFG;
305 if (isset(self::$behaviourtypes[$behaviour])) {
306 return;
308 $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviourtype.php';
309 if (!is_readable($file)) {
310 debugging('Question behaviour ' . $behaviour .
311 ' is missing the behaviourtype.php file.', DEBUG_DEVELOPER);
313 include_once($file);
317 * Return an array where the keys are the internal names of the archetypal
318 * behaviours, and the values are a human-readable name. An
319 * archetypal behaviour is one that is suitable to pass the name of to
320 * {@link question_usage_by_activity::set_preferred_behaviour()}.
322 * @return array model name => lang string for this behaviour name.
324 public static function get_archetypal_behaviours() {
325 $archetypes = array();
326 $behaviours = core_component::get_plugin_list('qbehaviour');
327 foreach ($behaviours as $behaviour => $notused) {
328 if (self::is_behaviour_archetypal($behaviour)) {
329 $archetypes[$behaviour] = self::get_behaviour_name($behaviour);
332 asort($archetypes, SORT_LOCALE_STRING);
333 return $archetypes;
337 * @param string $behaviour the name of a behaviour. E.g. 'deferredfeedback'.
338 * @return bool whether this is an archetypal behaviour.
340 public static function is_behaviour_archetypal($behaviour) {
341 return self::get_behaviour_type($behaviour)->is_archetypal();
345 * Return an array where the keys are the internal names of the behaviours
346 * in preferred order and the values are a human-readable name.
348 * @param array $archetypes, array of behaviours
349 * @param string $orderlist, a comma separated list of behaviour names
350 * @param string $disabledlist, a comma separated list of behaviour names
351 * @param string $current, current behaviour name
352 * @return array model name => lang string for this behaviour name.
354 public static function sort_behaviours($archetypes, $orderlist, $disabledlist, $current=null) {
356 // Get disabled behaviours
357 if ($disabledlist) {
358 $disabled = explode(',', $disabledlist);
359 } else {
360 $disabled = array();
363 if ($orderlist) {
364 $order = explode(',', $orderlist);
365 } else {
366 $order = array();
369 foreach ($disabled as $behaviour) {
370 if (array_key_exists($behaviour, $archetypes) && $behaviour != $current) {
371 unset($archetypes[$behaviour]);
375 // Get behaviours in preferred order
376 $behaviourorder = array();
377 foreach ($order as $behaviour) {
378 if (array_key_exists($behaviour, $archetypes)) {
379 $behaviourorder[$behaviour] = $archetypes[$behaviour];
382 // Get the rest of behaviours and sort them alphabetically
383 $leftover = array_diff_key($archetypes, $behaviourorder);
384 asort($leftover, SORT_LOCALE_STRING);
386 // Set up the final order to be displayed
387 return $behaviourorder + $leftover;
391 * Return an array where the keys are the internal names of the behaviours
392 * in preferred order and the values are a human-readable name.
394 * @param string $currentbehaviour
395 * @return array model name => lang string for this behaviour name.
397 public static function get_behaviour_options($currentbehaviour) {
398 $config = question_bank::get_config();
399 $archetypes = self::get_archetypal_behaviours();
401 // If no admin setting return all behavious
402 if (empty($config->disabledbehaviours) && empty($config->behavioursortorder)) {
403 return $archetypes;
406 if (empty($config->behavioursortorder)) {
407 $order = '';
408 } else {
409 $order = $config->behavioursortorder;
411 if (empty($config->disabledbehaviours)) {
412 $disabled = '';
413 } else {
414 $disabled = $config->disabledbehaviours;
417 return self::sort_behaviours($archetypes, $order, $disabled, $currentbehaviour);
421 * Get the translated name of a behaviour, for display in the UI.
422 * @param string $behaviour the internal name of the model.
423 * @return string name from the current language pack.
425 public static function get_behaviour_name($behaviour) {
426 return get_string('pluginname', 'qbehaviour_' . $behaviour);
430 * @return array all the file area names that may contain response files.
432 public static function get_all_response_file_areas() {
433 $variables = array();
434 foreach (question_bank::get_all_qtypes() as $qtype) {
435 $variables += $qtype->response_file_areas();
438 $areas = array();
439 foreach (array_unique($variables) as $variable) {
440 $areas[] = 'response_' . $variable;
442 return $areas;
446 * Returns the valid choices for the number of decimal places for showing
447 * question marks. For use in the user interface.
448 * @return array suitable for passing to {@link html_writer::select()} or similar.
450 public static function get_dp_options() {
451 return question_display_options::get_dp_options();
455 * Initialise the JavaScript required on pages where questions will be displayed.
457 public static function initialise_js() {
458 return question_flags::initialise_js();
464 * This class contains all the options that controls how a question is displayed.
466 * Normally, what will happen is that the calling code will set up some display
467 * options to indicate what sort of question display it wants, and then before the
468 * question is rendered, the behaviour will be given a chance to modify the
469 * display options, so that, for example, A question that is finished will only
470 * be shown read-only, and a question that has not been submitted will not have
471 * any sort of feedback displayed.
473 * @copyright 2009 The Open University
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
476 class question_display_options {
477 /**#@+ @var integer named constants for the values that most of the options take. */
478 const HIDDEN = 0;
479 const VISIBLE = 1;
480 const EDITABLE = 2;
481 /**#@-*/
483 /**#@+ @var integer named constants for the {@link $marks} option. */
484 const MAX_ONLY = 1;
485 const MARK_AND_MAX = 2;
486 /**#@-*/
489 * @var integer maximum value for the {@link $markpd} option. This is
490 * effectively set by the database structure, which uses NUMBER(12,7) columns
491 * for question marks/fractions.
493 const MAX_DP = 7;
496 * @var boolean whether the question should be displayed as a read-only review,
497 * or in an active state where you can change the answer.
499 public $readonly = false;
502 * @var boolean whether the question type should output hidden form fields
503 * to reset any incorrect parts of the resonse to blank.
505 public $clearwrong = false;
508 * Should the student have what they got right and wrong clearly indicated.
509 * This includes the green/red hilighting of the bits of their response,
510 * whether the one-line summary of the current state of the question says
511 * correct/incorrect or just answered.
512 * @var integer {@link question_display_options::HIDDEN} or
513 * {@link question_display_options::VISIBLE}
515 public $correctness = self::VISIBLE;
518 * The the mark and/or the maximum available mark for this question be visible?
519 * @var integer {@link question_display_options::HIDDEN},
520 * {@link question_display_options::MAX_ONLY} or {@link question_display_options::MARK_AND_MAX}
522 public $marks = self::MARK_AND_MAX;
524 /** @var number of decimal places to use when formatting marks for output. */
525 public $markdp = 2;
528 * Should the flag this question UI element be visible, and if so, should the
529 * flag state be changable?
530 * @var integer {@link question_display_options::HIDDEN},
531 * {@link question_display_options::VISIBLE} or {@link question_display_options::EDITABLE}
533 public $flags = self::VISIBLE;
536 * Should the specific feedback be visible.
537 * @var integer {@link question_display_options::HIDDEN} or
538 * {@link question_display_options::VISIBLE}
540 public $feedback = self::VISIBLE;
543 * For questions with a number of sub-parts (like matching, or
544 * multiple-choice, multiple-reponse) display the number of sub-parts that
545 * were correct.
546 * @var integer {@link question_display_options::HIDDEN} or
547 * {@link question_display_options::VISIBLE}
549 public $numpartscorrect = self::VISIBLE;
552 * Should the general feedback be visible?
553 * @var integer {@link question_display_options::HIDDEN} or
554 * {@link question_display_options::VISIBLE}
556 public $generalfeedback = self::VISIBLE;
559 * Should the automatically generated display of what the correct answer is
560 * be visible?
561 * @var integer {@link question_display_options::HIDDEN} or
562 * {@link question_display_options::VISIBLE}
564 public $rightanswer = self::VISIBLE;
567 * Should the manually added marker's comment be visible. Should the link for
568 * adding/editing the comment be there.
569 * @var integer {@link question_display_options::HIDDEN},
570 * {@link question_display_options::VISIBLE}, or {@link question_display_options::EDITABLE}.
571 * Editable means that form fields are displayed inline.
573 public $manualcomment = self::VISIBLE;
576 * Should we show a 'Make comment or override grade' link?
577 * @var string base URL for the edit comment script, which will be shown if
578 * $manualcomment = self::VISIBLE.
580 public $manualcommentlink = null;
583 * Used in places like the question history table, to show a link to review
584 * this question in a certain state. If blank, a link is not shown.
585 * @var string base URL for a review question script.
587 public $questionreviewlink = null;
590 * Should the history of previous question states table be visible?
591 * @var integer {@link question_display_options::HIDDEN} or
592 * {@link question_display_options::VISIBLE}
594 public $history = self::HIDDEN;
597 * @since 2.9
598 * @var string extra HTML to include at the end of the outcome (feedback) box
599 * of the question display.
601 * This field is now badly named. The place it included is was changed
602 * (for the better) but the name was left unchanged for backwards compatibility.
604 public $extrainfocontent = '';
607 * @since 2.9
608 * @var string extra HTML to include in the history box of the question display,
609 * if it is shown.
611 public $extrahistorycontent = '';
614 * If not empty, then a link to edit the question will be included in
615 * the info box for the question.
617 * If used, this array must contain an element courseid or cmid.
619 * It shoudl also contain a parameter returnurl => moodle_url giving a
620 * sensible URL to go back to when the editing form is submitted or cancelled.
622 * @var array url parameter for the edit link. id => questiosnid will be
623 * added automatically.
625 public $editquestionparams = array();
628 * @var int the context the attempt being output belongs to.
630 public $context;
633 * Set all the feedback-related fields {@link $feedback}, {@link generalfeedback},
634 * {@link rightanswer} and {@link manualcomment} to
635 * {@link question_display_options::HIDDEN}.
637 public function hide_all_feedback() {
638 $this->feedback = self::HIDDEN;
639 $this->numpartscorrect = self::HIDDEN;
640 $this->generalfeedback = self::HIDDEN;
641 $this->rightanswer = self::HIDDEN;
642 $this->manualcomment = self::HIDDEN;
643 $this->correctness = self::HIDDEN;
647 * Returns the valid choices for the number of decimal places for showing
648 * question marks. For use in the user interface.
650 * Calling code should probably use {@link question_engine::get_dp_options()}
651 * rather than calling this method directly.
653 * @return array suitable for passing to {@link html_writer::select()} or similar.
655 public static function get_dp_options() {
656 $options = array();
657 for ($i = 0; $i <= self::MAX_DP; $i += 1) {
658 $options[$i] = $i;
660 return $options;
666 * Contains the logic for handling question flags.
668 * @copyright 2010 The Open University
669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
671 abstract class question_flags {
673 * Get the checksum that validates that a toggle request is valid.
674 * @param int $qubaid the question usage id.
675 * @param int $questionid the question id.
676 * @param int $sessionid the question_attempt id.
677 * @param object $user the user. If null, defaults to $USER.
678 * @return string that needs to be sent to question/toggleflag.php for it to work.
680 protected static function get_toggle_checksum($qubaid, $questionid,
681 $qaid, $slot, $user = null) {
682 if (is_null($user)) {
683 global $USER;
684 $user = $USER;
686 return md5($qubaid . "_" . $user->secret . "_" . $questionid . "_" . $qaid . "_" . $slot);
690 * Get the postdata that needs to be sent to question/toggleflag.php to change the flag state.
691 * You need to append &newstate=0/1 to this.
692 * @return the post data to send.
694 public static function get_postdata(question_attempt $qa) {
695 $qaid = $qa->get_database_id();
696 $qubaid = $qa->get_usage_id();
697 $qid = $qa->get_question()->id;
698 $slot = $qa->get_slot();
699 $checksum = self::get_toggle_checksum($qubaid, $qid, $qaid, $slot);
700 return "qaid={$qaid}&qubaid={$qubaid}&qid={$qid}&slot={$slot}&checksum={$checksum}&sesskey=" .
701 sesskey() . '&newstate=';
705 * If the request seems valid, update the flag state of a question attempt.
706 * Throws exceptions if this is not a valid update request.
707 * @param int $qubaid the question usage id.
708 * @param int $questionid the question id.
709 * @param int $sessionid the question_attempt id.
710 * @param string $checksum checksum, as computed by {@link get_toggle_checksum()}
711 * corresponding to the last three arguments.
712 * @param bool $newstate the new state of the flag. true = flagged.
714 public static function update_flag($qubaid, $questionid, $qaid, $slot, $checksum, $newstate) {
715 // Check the checksum - it is very hard to know who a question session belongs
716 // to, so we require that checksum parameter is matches an md5 hash of the
717 // three ids and the users username. Since we are only updating a flag, that
718 // probably makes it sufficiently difficult for malicious users to toggle
719 // other users flags.
720 if ($checksum != self::get_toggle_checksum($qubaid, $questionid, $qaid, $slot)) {
721 throw new moodle_exception('errorsavingflags', 'question');
724 $dm = new question_engine_data_mapper();
725 $dm->update_question_attempt_flag($qubaid, $questionid, $qaid, $slot, $newstate);
728 public static function initialise_js() {
729 global $CFG, $PAGE, $OUTPUT;
730 static $done = false;
731 if ($done) {
732 return;
734 $module = array(
735 'name' => 'core_question_flags',
736 'fullpath' => '/question/flags.js',
737 'requires' => array('base', 'dom', 'event-delegate', 'io-base'),
739 $actionurl = $CFG->wwwroot . '/question/toggleflag.php';
740 $flagtext = array(
741 0 => get_string('clickflag', 'question'),
742 1 => get_string('clickunflag', 'question')
744 $flagattributes = array(
745 0 => array(
746 'src' => $OUTPUT->image_url('i/unflagged') . '',
747 'title' => get_string('clicktoflag', 'question'),
748 'alt' => get_string('notflagged', 'question'),
749 // 'text' => get_string('clickflag', 'question'),
751 1 => array(
752 'src' => $OUTPUT->image_url('i/flagged') . '',
753 'title' => get_string('clicktounflag', 'question'),
754 'alt' => get_string('flagged', 'question'),
755 // 'text' => get_string('clickunflag', 'question'),
758 $PAGE->requires->js_init_call('M.core_question_flags.init',
759 array($actionurl, $flagattributes, $flagtext), false, $module);
760 $done = true;
766 * Exception thrown when the system detects that a student has done something
767 * out-of-order to a question. This can happen, for example, if they click
768 * the browser's back button in a quiz, then try to submit a different response.
770 * @copyright 2010 The Open University
771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
773 class question_out_of_sequence_exception extends moodle_exception {
774 public function __construct($qubaid, $slot, $postdata) {
775 if ($postdata == null) {
776 $postdata = data_submitted();
778 parent::__construct('submissionoutofsequence', 'question', '', null,
779 "QUBAid: {$qubaid}, slot: {$slot}, post data: " . print_r($postdata, true));
785 * Useful functions for writing question types and behaviours.
787 * @copyright 2010 The Open University
788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
790 abstract class question_utils {
792 * Tests to see whether two arrays have the same keys, with the same values
793 * (as compared by ===) for each key. However, the order of the arrays does
794 * not have to be the same.
795 * @param array $array1 the first array.
796 * @param array $array2 the second array.
797 * @return bool whether the two arrays have the same keys with the same
798 * corresponding values.
800 public static function arrays_have_same_keys_and_values(array $array1, array $array2) {
801 if (count($array1) != count($array2)) {
802 return false;
804 foreach ($array1 as $key => $value1) {
805 if (!array_key_exists($key, $array2)) {
806 return false;
808 if (((string) $value1) !== ((string) $array2[$key])) {
809 return false;
812 return true;
816 * Tests to see whether two arrays have the same value at a particular key.
817 * This method will return true if:
818 * 1. Neither array contains the key; or
819 * 2. Both arrays contain the key, and the corresponding values compare
820 * identical when cast to strings and compared with ===.
821 * @param array $array1 the first array.
822 * @param array $array2 the second array.
823 * @param string $key an array key.
824 * @return bool whether the two arrays have the same value (or lack of
825 * one) for a given key.
827 public static function arrays_same_at_key(array $array1, array $array2, $key) {
828 if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
829 return ((string) $array1[$key]) === ((string) $array2[$key]);
831 if (!array_key_exists($key, $array1) && !array_key_exists($key, $array2)) {
832 return true;
834 return false;
838 * Tests to see whether two arrays have the same value at a particular key.
839 * Missing values are replaced by '', and then the values are cast to
840 * strings and compared with ===.
841 * @param array $array1 the first array.
842 * @param array $array2 the second array.
843 * @param string $key an array key.
844 * @return bool whether the two arrays have the same value (or lack of
845 * one) for a given key.
847 public static function arrays_same_at_key_missing_is_blank(
848 array $array1, array $array2, $key) {
849 if (array_key_exists($key, $array1)) {
850 $value1 = $array1[$key];
851 } else {
852 $value1 = '';
854 if (array_key_exists($key, $array2)) {
855 $value2 = $array2[$key];
856 } else {
857 $value2 = '';
859 return ((string) $value1) === ((string) $value2);
863 * Tests to see whether two arrays have the same value at a particular key.
864 * Missing values are replaced by 0, and then the values are cast to
865 * integers and compared with ===.
866 * @param array $array1 the first array.
867 * @param array $array2 the second array.
868 * @param string $key an array key.
869 * @return bool whether the two arrays have the same value (or lack of
870 * one) for a given key.
872 public static function arrays_same_at_key_integer(
873 array $array1, array $array2, $key) {
874 if (array_key_exists($key, $array1)) {
875 $value1 = (int) $array1[$key];
876 } else {
877 $value1 = 0;
879 if (array_key_exists($key, $array2)) {
880 $value2 = (int) $array2[$key];
881 } else {
882 $value2 = 0;
884 return $value1 === $value2;
887 private static $units = array('', 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix');
888 private static $tens = array('', 'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc');
889 private static $hundreds = array('', 'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm');
890 private static $thousands = array('', 'm', 'mm', 'mmm');
893 * Convert an integer to roman numerals.
894 * @param int $number an integer between 1 and 3999 inclusive. Anything else
895 * will throw an exception.
896 * @return string the number converted to lower case roman numerals.
898 public static function int_to_roman($number) {
899 if (!is_integer($number) || $number < 1 || $number > 3999) {
900 throw new coding_exception('Only integers between 0 and 3999 can be ' .
901 'converted to roman numerals.', $number);
904 return self::$thousands[$number / 1000 % 10] . self::$hundreds[$number / 100 % 10] .
905 self::$tens[$number / 10 % 10] . self::$units[$number % 10];
909 * Typically, $mark will have come from optional_param($name, null, PARAM_RAW_TRIMMED).
910 * This method copes with:
911 * - keeping null or '' input unchanged - important to let teaches set a question back to requries grading.
912 * - numbers that were typed as either 1.00 or 1,00 form.
913 * - invalid things, which get turned into null.
915 * @param string|null $mark raw use input of a mark.
916 * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
918 public static function clean_param_mark($mark) {
919 if ($mark === '' || is_null($mark)) {
920 return $mark;
923 $mark = str_replace(',', '.', $mark);
924 // This regexp should match the one in validate_param.
925 if (!preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', $mark)) {
926 return null;
929 return clean_param($mark, PARAM_FLOAT);
933 * Get a sumitted variable (from the GET or POST data) that is a mark.
934 * @param string $parname the submitted variable name.
935 * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
937 public static function optional_param_mark($parname) {
938 return self::clean_param_mark(
939 optional_param($parname, null, PARAM_RAW_TRIMMED));
943 * Convert part of some question content to plain text.
944 * @param string $text the text.
945 * @param int $format the text format.
946 * @param array $options formatting options. Passed to {@link format_text}.
947 * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
949 public static function to_plain_text($text, $format, $options = array('noclean' => 'true')) {
950 // The following call to html_to_text uses the option that strips out
951 // all URLs, but format_text complains if it finds @@PLUGINFILE@@ tokens.
952 // So, we need to replace @@PLUGINFILE@@ with a real URL, but it doesn't
953 // matter what. We use http://example.com/.
954 $text = str_replace('@@PLUGINFILE@@/', 'http://example.com/', $text);
955 return html_to_text(format_text($text, $format, $options), 0, false);
959 * Get the options required to configure the filepicker for one of the editor
960 * toolbar buttons.
961 * @param mixed $acceptedtypes array of types of '*'.
962 * @param int $draftitemid the draft area item id.
963 * @param object $context the context.
964 * @return object the required options.
966 protected static function specific_filepicker_options($acceptedtypes, $draftitemid, $context) {
967 $filepickeroptions = new stdClass();
968 $filepickeroptions->accepted_types = $acceptedtypes;
969 $filepickeroptions->return_types = FILE_INTERNAL | FILE_EXTERNAL;
970 $filepickeroptions->context = $context;
971 $filepickeroptions->env = 'filepicker';
973 $options = initialise_filepicker($filepickeroptions);
974 $options->context = $context;
975 $options->client_id = uniqid();
976 $options->env = 'editor';
977 $options->itemid = $draftitemid;
979 return $options;
983 * Get filepicker options for question related text areas.
984 * @param object $context the context.
985 * @param int $draftitemid the draft area item id.
986 * @return array An array of options
988 public static function get_filepicker_options($context, $draftitemid) {
989 return [
990 'image' => self::specific_filepicker_options(['image'], $draftitemid, $context),
991 'media' => self::specific_filepicker_options(['video', 'audio'], $draftitemid, $context),
992 'link' => self::specific_filepicker_options('*', $draftitemid, $context),
997 * Get editor options for question related text areas.
998 * @param object $context the context.
999 * @return array An array of options
1001 public static function get_editor_options($context) {
1002 global $CFG;
1004 $editoroptions = [
1005 'subdirs' => 0,
1006 'context' => $context,
1007 'maxfiles' => EDITOR_UNLIMITED_FILES,
1008 'maxbytes' => $CFG->maxbytes,
1009 'noclean' => 0,
1010 'trusttext' => 0,
1011 'autosave' => false
1014 return $editoroptions;
1020 * The interface for strategies for controlling which variant of each question is used.
1022 * @copyright 2011 The Open University
1023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1025 interface question_variant_selection_strategy {
1027 * @param int $maxvariants the num
1028 * @param string $seed data that can be used to controls how the variant is selected
1029 * in a semi-random way.
1030 * @return int the variant to use, a number betweeb 1 and $maxvariants inclusive.
1032 public function choose_variant($maxvariants, $seed);
1037 * A {@link question_variant_selection_strategy} that is completely random.
1039 * @copyright 2011 The Open University
1040 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1042 class question_variant_random_strategy implements question_variant_selection_strategy {
1043 public function choose_variant($maxvariants, $seed) {
1044 return rand(1, $maxvariants);
1050 * A {@link question_variant_selection_strategy} that is effectively random
1051 * for the first attempt, and then after that cycles through the available
1052 * variants so that the students will not get a repeated variant until they have
1053 * seen them all.
1055 * @copyright 2011 The Open University
1056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1058 class question_variant_pseudorandom_no_repeats_strategy
1059 implements question_variant_selection_strategy {
1061 /** @var int the number of attempts this users has had, including the curent one. */
1062 protected $attemptno;
1064 /** @var int the user id the attempt belongs to. */
1065 protected $userid;
1067 /** @var string extra input fed into the pseudo-random code. */
1068 protected $extrarandomness = '';
1071 * Constructor.
1072 * @param int $attemptno The attempt number.
1073 * @param int $userid the user the attempt is for (defaults to $USER->id).
1075 public function __construct($attemptno, $userid = null, $extrarandomness = '') {
1076 $this->attemptno = $attemptno;
1077 if (is_null($userid)) {
1078 global $USER;
1079 $this->userid = $USER->id;
1080 } else {
1081 $this->userid = $userid;
1084 if ($extrarandomness) {
1085 $this->extrarandomness = '|' . $extrarandomness;
1089 public function choose_variant($maxvariants, $seed) {
1090 if ($maxvariants == 1) {
1091 return 1;
1094 $hash = sha1($seed . '|user' . $this->userid . $this->extrarandomness);
1095 $randint = hexdec(substr($hash, 17, 7));
1097 return ($randint + $this->attemptno) % $maxvariants + 1;
1102 * A {@link question_variant_selection_strategy} designed ONLY for testing.
1103 * For selected questions it wil return a specific variants. For the other
1104 * slots it will use a fallback strategy.
1106 * @copyright 2013 The Open University
1107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1109 class question_variant_forced_choices_selection_strategy
1110 implements question_variant_selection_strategy {
1112 /** @var array seed => variant to select. */
1113 protected $forcedchoices;
1115 /** @var question_variant_selection_strategy strategy used to make the non-forced choices. */
1116 protected $basestrategy;
1119 * Constructor.
1120 * @param array $forcedchoices array seed => variant to select.
1121 * @param question_variant_selection_strategy $basestrategy strategy used
1122 * to make the non-forced choices.
1124 public function __construct(array $forcedchoices, question_variant_selection_strategy $basestrategy) {
1125 $this->forcedchoices = $forcedchoices;
1126 $this->basestrategy = $basestrategy;
1129 public function choose_variant($maxvariants, $seed) {
1130 if (array_key_exists($seed, $this->forcedchoices)) {
1131 if ($this->forcedchoices[$seed] > $maxvariants) {
1132 throw new coding_exception('Forced variant out of range.');
1134 return $this->forcedchoices[$seed];
1135 } else {
1136 return $this->basestrategy->choose_variant($maxvariants, $seed);
1141 * Helper method for preparing the $forcedchoices array.
1142 * @param array $variantsbyslot slot number => variant to select.
1143 * @param question_usage_by_activity $quba the question usage we need a strategy for.
1144 * @throws coding_exception when variant cannot be forced as doesn't work.
1145 * @return array that can be passed to the constructor as $forcedchoices.
1147 public static function prepare_forced_choices_array(array $variantsbyslot,
1148 question_usage_by_activity $quba) {
1150 $forcedchoices = array();
1152 foreach ($variantsbyslot as $slot => $varianttochoose) {
1153 $question = $quba->get_question($slot);
1154 $seed = $question->get_variants_selection_seed();
1155 if (array_key_exists($seed, $forcedchoices) && $forcedchoices[$seed] != $varianttochoose) {
1156 throw new coding_exception('Inconsistent forced variant detected at slot ' . $slot);
1158 if ($varianttochoose > $question->get_num_variants()) {
1159 throw new coding_exception('Forced variant out of range at slot ' . $slot);
1161 $forcedchoices[$seed] = $varianttochoose;
1163 return $forcedchoices;