MDL-20636 Merge branch 'master' into qe2_wip
authorTim Hunt <T.J.Hunt@open.ac.uk>
Thu, 3 Feb 2011 11:07:11 +0000 (11:07 +0000)
committerTim Hunt <T.J.Hunt@open.ac.uk>
Thu, 3 Feb 2011 11:18:40 +0000 (11:18 +0000)
Conflicts:
lib/questionlib.php
question/type/calculated/lang/en/qtype_calculated.php
question/type/questiontype.php

251 files changed:
admin/qtypes.php
lang/en/question.php
lib/moodlelib.php
lib/questionlib.php
local/qedatabase/db/install.php [new file with mode: 0755]
local/qedatabase/db/upgrade.php [new file with mode: 0755]
local/qedatabase/readme.txt [new file with mode: 0755]
local/qedatabase/version.php [new file with mode: 0755]
mod/quiz/db/install.xml [changed mode: 0755->0644]
mod/quiz/locallib.php
mod/quiz/pix/icon.gif [changed mode: 0755->0644]
mod/quiz/report/statistics/db/upgrade.php
question/behaviour/adaptive/behaviour.php [new file with mode: 0644]
question/behaviour/adaptive/lang/en/qbehaviour_adaptive.php [new file with mode: 0644]
question/behaviour/adaptive/renderer.php [new file with mode: 0644]
question/behaviour/adaptive/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/adaptivenopenalty/behaviour.php [new file with mode: 0644]
question/behaviour/adaptivenopenalty/lang/en/qbehaviour_adaptivenopenalty.php [new file with mode: 0644]
question/behaviour/adaptivenopenalty/renderer.php [new file with mode: 0644]
question/behaviour/adaptivenopenalty/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/behaviourbase.php [new file with mode: 0644]
question/behaviour/deferredcbm/behaviour.php [new file with mode: 0644]
question/behaviour/deferredcbm/lang/en/qbehaviour_deferredcbm.php [new file with mode: 0644]
question/behaviour/deferredcbm/renderer.php [new file with mode: 0644]
question/behaviour/deferredcbm/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/deferredfeedback/behaviour.php [new file with mode: 0644]
question/behaviour/deferredfeedback/lang/en/qbehaviour_deferredfeedback.php [new file with mode: 0644]
question/behaviour/deferredfeedback/renderer.php [new file with mode: 0644]
question/behaviour/deferredfeedback/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/immediatecbm/behaviour.php [new file with mode: 0644]
question/behaviour/immediatecbm/lang/en/qbehaviour_immediatecbm.php [new file with mode: 0644]
question/behaviour/immediatecbm/renderer.php [new file with mode: 0644]
question/behaviour/immediatecbm/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/immediatefeedback/behaviour.php [new file with mode: 0644]
question/behaviour/immediatefeedback/lang/en/qbehaviour_immediatefeedback.php [new file with mode: 0644]
question/behaviour/immediatefeedback/renderer.php [new file with mode: 0644]
question/behaviour/immediatefeedback/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/informationitem/behaviour.php [new file with mode: 0644]
question/behaviour/informationitem/lang/en/qbehaviour_informationitem.php [new file with mode: 0644]
question/behaviour/informationitem/renderer.php [new file with mode: 0644]
question/behaviour/informationitem/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/interactive/behaviour.php [new file with mode: 0644]
question/behaviour/interactive/lang/en/qbehaviour_interactive.php [new file with mode: 0644]
question/behaviour/interactive/renderer.php [new file with mode: 0644]
question/behaviour/interactive/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/interactivecountback/behaviour.php [new file with mode: 0644]
question/behaviour/interactivecountback/lang/en/qbehaviour_interactivecountback.php [new file with mode: 0644]
question/behaviour/interactivecountback/renderer.php [new file with mode: 0644]
question/behaviour/interactivecountback/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/manualgraded/behaviour.php [new file with mode: 0644]
question/behaviour/manualgraded/lang/en/qbehaviour_manualgraded.php [new file with mode: 0644]
question/behaviour/manualgraded/renderer.php [new file with mode: 0644]
question/behaviour/manualgraded/simpletest/testwalkthrough.php [new file with mode: 0644]
question/behaviour/missing/behaviour.php [new file with mode: 0644]
question/behaviour/missing/lang/en/qbehaviour_missing.php [new file with mode: 0644]
question/behaviour/missing/renderer.php [new file with mode: 0644]
question/behaviour/missing/simpletest/testmissingbehaviour.php [new file with mode: 0644]
question/behaviour/opaque/behaviour.php [new file with mode: 0644]
question/behaviour/opaque/lang/en/qbehaviour_opaque.php [new file with mode: 0644]
question/behaviour/opaque/renderer.php [new file with mode: 0644]
question/behaviour/opaque/simpletest/testopaquebehaviour.php [new file with mode: 0644]
question/behaviour/rendererbase.php [new file with mode: 0644]
question/editlib.php
question/engine/bank.php [new file with mode: 0644]
question/engine/datalib.php [new file with mode: 0644]
question/engine/lib.php [new file with mode: 0644]
question/engine/renderer.php [new file with mode: 0644]
question/engine/simpletest/helpers.php [new file with mode: 0644]
question/engine/simpletest/testdatalib.php [new file with mode: 0644]
question/engine/simpletest/testquestionattempt.php [new file with mode: 0644]
question/engine/simpletest/testquestionattemptiterator.php [new file with mode: 0644]
question/engine/simpletest/testquestionattemptstep.php [new file with mode: 0644]
question/engine/simpletest/testquestionattemptstepiterator.php [new file with mode: 0644]
question/engine/simpletest/testquestioncbm.php [new file with mode: 0644]
question/engine/simpletest/testquestionengine.php [new file with mode: 0644]
question/engine/simpletest/testquestionstate.php [new file with mode: 0644]
question/engine/simpletest/testquestionusagebyactivity.php [new file with mode: 0644]
question/engine/simpletest/testquestionutils.php [new file with mode: 0644]
question/engine/states.php [new file with mode: 0644]
question/engine/upgradefromoldqe/upgrade.php [new file with mode: 0644]
question/file.php
question/flags.js
question/format.php
question/format/blackboard/format.php
question/format/examview/format.php [changed mode: 0755->0644]
question/format/gift/format.php [changed mode: 0755->0644]
question/format/gift/simpletest/testgiftformat.php
question/format/learnwise/format.php [changed mode: 0755->0644]
question/format/qti_two/templates/choice.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/choiceMultiple.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/composite.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/extendedText.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/extendedText_simpleEssay.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/imsmanifest.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/mmchoiceMultiple.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/notimplemented.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/numerical.tpl [changed mode: 0755->0644]
question/format/qti_two/templates/textEntry.tpl [changed mode: 0755->0644]
question/format/webct/format.php
question/format/xhtml/format.php [changed mode: 0755->0644]
question/format/xml/format.php [changed mode: 0755->0644]
question/format/xml/simpletest/testxmlformat.php [new file with mode: 0644]
question/import_form.php
question/move_form.php
question/preview.js [new file with mode: 0644]
question/preview.php
question/previewlib.php
question/qengine.js
question/question.php
question/todo/diffstat.txt [new file with mode: 0644]
question/todo/questionlib_2.0.diff.txt [new file with mode: 0644]
question/todo/questionlib_qe.diff.txt [new file with mode: 0644]
question/todo/top-level_question_changes.patch.txt [new file with mode: 0644]
question/toggleflag.php
question/type/calculated/pix/icon.gif [changed mode: 0755->0644]
question/type/ddwtos/db/install.xml [new file with mode: 0644]
question/type/ddwtos/edit_ddwtos_form.php [new file with mode: 0644]
question/type/ddwtos/lang/en/qtype_ddwtos.php [new file with mode: 0644]
question/type/ddwtos/pix/icon.gif [new file with mode: 0644]
question/type/ddwtos/question.php [new file with mode: 0644]
question/type/ddwtos/questiontype.php [new file with mode: 0644]
question/type/ddwtos/renderer.php [new file with mode: 0644]
question/type/ddwtos/script.js [new file with mode: 0644]
question/type/ddwtos/simpletest/helper.php [new file with mode: 0644]
question/type/ddwtos/simpletest/testquestion.php [new file with mode: 0644]
question/type/ddwtos/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/ddwtos/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/ddwtos/styles.css [new file with mode: 0644]
question/type/ddwtos/version.php [new file with mode: 0644]
question/type/description/edit_description_form.php
question/type/description/question.php [new file with mode: 0644]
question/type/description/questiontype.php
question/type/description/renderer.php [new file with mode: 0644]
question/type/description/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/edit_question_form.php
question/type/essay/edit_essay_form.php
question/type/essay/lang/en/qtype_essay.php
question/type/essay/question.php [new file with mode: 0644]
question/type/essay/questiontype.php
question/type/essay/renderer.php [new file with mode: 0644]
question/type/essay/simpletest/testquestion.php [new file with mode: 0644]
question/type/essay/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/essay/version.php
question/type/gapselect/db/install.xml [new file with mode: 0644]
question/type/gapselect/edit_form_base.php [new file with mode: 0644]
question/type/gapselect/edit_gapselect_form.php [new file with mode: 0644]
question/type/gapselect/lang/en/qtype_gapselect.php [new file with mode: 0644]
question/type/gapselect/pix/icon.gif [new file with mode: 0644]
question/type/gapselect/question.php [new file with mode: 0644]
question/type/gapselect/questionbase.php [new file with mode: 0644]
question/type/gapselect/questiontype.php [new file with mode: 0644]
question/type/gapselect/questiontypebase.php [new file with mode: 0644]
question/type/gapselect/renderer.php [new file with mode: 0644]
question/type/gapselect/rendererbase.php [new file with mode: 0644]
question/type/gapselect/simpletest/helper.php [new file with mode: 0644]
question/type/gapselect/simpletest/testquestion.php [new file with mode: 0644]
question/type/gapselect/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/gapselect/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/gapselect/styles.css [new file with mode: 0644]
question/type/gapselect/version.php [new file with mode: 0644]
question/type/match/db/install.xml
question/type/match/db/upgrade.php
question/type/match/display.html [deleted file]
question/type/match/edit_match_form.php
question/type/match/lang/en/qtype_match.php
question/type/match/question.php [new file with mode: 0644]
question/type/match/questiontype.php
question/type/match/renderer.php [new file with mode: 0644]
question/type/match/simpletest/testquestion.php [new file with mode: 0644]
question/type/match/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/match/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/match/version.php
question/type/missingtype/display.html [deleted file]
question/type/missingtype/edit_missingtype_form.php
question/type/missingtype/lang/en/qtype_missingtype.php
question/type/missingtype/pix/icon.gif
question/type/missingtype/question.php [new file with mode: 0644]
question/type/missingtype/questiontype.php
question/type/missingtype/renderer.php [new file with mode: 0644]
question/type/missingtype/simpletest/testmissingtype.php [new file with mode: 0644]
question/type/multichoice/db/install.xml
question/type/multichoice/db/upgrade.php
question/type/multichoice/display.html [deleted file]
question/type/multichoice/edit_multichoice_form.php
question/type/multichoice/lang/en/qtype_multichoice.php
question/type/multichoice/question.php [new file with mode: 0644]
question/type/multichoice/questiontype.php
question/type/multichoice/renderer.php [new file with mode: 0644]
question/type/multichoice/simpletest/testquestion.php [new file with mode: 0644]
question/type/multichoice/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/multichoice/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/multichoice/styles.css [new file with mode: 0644]
question/type/multichoice/version.php
question/type/numerical/question.php [new file with mode: 0644]
question/type/numerical/questiontype.php
question/type/opaque/db/install.xml [new file with mode: 0644]
question/type/opaque/edit_engine_form.php [new file with mode: 0644]
question/type/opaque/edit_opaque_form.php [new file with mode: 0644]
question/type/opaque/editengine.php [new file with mode: 0644]
question/type/opaque/engines.php [new file with mode: 0644]
question/type/opaque/file.php [new file with mode: 0644]
question/type/opaque/lang/en/qtype_opaque.php [new file with mode: 0644]
question/type/opaque/locallib.php [new file with mode: 0644]
question/type/opaque/pix/icon.gif [new file with mode: 0644]
question/type/opaque/question.php [new file with mode: 0644]
question/type/opaque/questiontype.php [new file with mode: 0644]
question/type/opaque/renderer.php [new file with mode: 0644]
question/type/opaque/settings.php [new file with mode: 0644]
question/type/opaque/simpletest/testlocallib.php [new file with mode: 0644]
question/type/opaque/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/opaque/styles.css [new file with mode: 0644]
question/type/opaque/testengine.php [new file with mode: 0644]
question/type/opaque/version.php [new file with mode: 0644]
question/type/oumultiresponse/db/install.xml [new file with mode: 0644]
question/type/oumultiresponse/edit_oumultiresponse_form.php [new file with mode: 0644]
question/type/oumultiresponse/lang/en/qtype_oumultiresponse.php [new file with mode: 0644]
question/type/oumultiresponse/pix/icon.gif [new file with mode: 0644]
question/type/oumultiresponse/question.php [new file with mode: 0644]
question/type/oumultiresponse/questiontype.php [new file with mode: 0644]
question/type/oumultiresponse/simpletest/helper.php [new file with mode: 0644]
question/type/oumultiresponse/simpletest/testquestion.php [new file with mode: 0644]
question/type/oumultiresponse/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/oumultiresponse/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/oumultiresponse/styles.css [new file with mode: 0644]
question/type/oumultiresponse/version.php [new file with mode: 0644]
question/type/question.html [deleted file]
question/type/questionbase.php [new file with mode: 0644]
question/type/questiontype.php
question/type/randomsamatch/questiontype.php
question/type/rendererbase.php [new file with mode: 0644]
question/type/shortanswer/display.html [deleted file]
question/type/shortanswer/edit_shortanswer_form.php
question/type/shortanswer/lang/en/qtype_shortanswer.php
question/type/shortanswer/question.php [new file with mode: 0644]
question/type/shortanswer/questiontype.php
question/type/shortanswer/renderer.php [new file with mode: 0644]
question/type/shortanswer/simpletest/testquestion.php [new file with mode: 0644]
question/type/shortanswer/simpletest/testquestiontype.php
question/type/shortanswer/version.php
question/type/simpletest/testquestionbase.php [new file with mode: 0644]
question/type/simpletest/testquestiontype.php
question/type/truefalse/display.html [deleted file]
question/type/truefalse/edit_truefalse_form.php
question/type/truefalse/lang/en/qtype_truefalse.php
question/type/truefalse/question.php [new file with mode: 0644]
question/type/truefalse/questiontype.php
question/type/truefalse/renderer.php [new file with mode: 0644]
question/type/truefalse/simpletest/testquestion.php [new file with mode: 0644]
question/type/truefalse/simpletest/testquestiontype.php [new file with mode: 0644]
theme/base/style/question.css
theme/canvas/style/question.css

index 33a70d8..5ce88d3 100644 (file)
 
     admin_externalpage_setup('manageqtypes');
 
+    $qtypes = question_bank::get_all_qtypes();
+
 /// Get some data we will need - question counts and which types are needed.
     $counts = $DB->get_records_sql("
             SELECT qtype, COUNT(1) as numquestions, SUM(hidden) as numhidden
             FROM {question} GROUP BY qtype", array());
     $needed = array();
-    foreach ($QTYPES as $qtypename => $qtype) {
+    foreach ($qtypes as $qtypename => $qtype) {
         if (!isset($counts[$qtypename])) {
             $counts[$qtypename] = new stdClass;
             $counts[$qtypename]->numquestions = 0;
         $counts[$qtypename]->numquestions -= $counts[$qtypename]->numhidden;
     }
     $needed['missingtype'] = true; // The system needs the missing question type.
-    foreach ($QTYPES as $qtypename => $qtype) {
+    foreach ($qtypes as $qtypename => $qtype) {
         foreach ($qtype->requires_qtypes() as $reqtype) {
             $needed[$reqtype] = true;
         }
     }
     foreach ($counts as $qtypename => $count) {
-        if (!isset($QTYPES[$qtypename])) {
+        if (!isset($qtypes[$qtypename])) {
             $counts['missingtype']->numquestions += $count->numquestions - $count->numhidden;
             $counts['missingtype']->numhidden += $count->numhidden;
         }
@@ -44,7 +46,7 @@
 /// Work of the correct sort order.
     $config = get_config('question');
     $sortedqtypes = array();
-    foreach ($QTYPES as $qtypename => $qtype) {
+    foreach ($qtypes as $qtypename => $qtype) {
         $sortedqtypes[$qtypename] = $qtype->local_name();
     }
     $sortedqtypes = question_sort_qtype_array($sortedqtypes, $config);
@@ -53,7 +55,7 @@
 
     // Disable.
     if (($disable = optional_param('disable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$disable])) {
+        if (!isset($qtypes[$disable])) {
             print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $disable);
         }
 
 
     // Enable.
     if (($enable = optional_param('enable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$enable])) {
+        if (!isset($qtypes[$enable])) {
             print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $enable);
         }
 
-        if (!$QTYPES[$enable]->menu_name()) {
+        if (!$qtypes[$enable]->menu_name()) {
             print_error('cannotenable', 'question', admin_url('qtypes.php'), $enable);
         }
 
@@ -77,7 +79,7 @@
 
     // Move up in order.
     if (($up = optional_param('up', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$up])) {
+        if (!isset($qtypes[$up])) {
             print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $up);
         }
 
@@ -88,7 +90,7 @@
 
     // Move down in order.
     if (($down = optional_param('down', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$down])) {
+        if (!isset($qtypes[$down])) {
             print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $down);
         }
 
             print_error('cannotdeletemissingqtype', 'admin', admin_url('qtypes.php'));
         }
 
-        if (!isset($QTYPES[$delete])) {
+        if (!isset($qtypes[$delete])) {
             print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $delete);
         }
 
-        $qtypename = $QTYPES[$delete]->local_name();
+        $qtypename = $qtypes[$delete]->local_name();
         if ($counts[$delete]->numquestions + $counts[$delete]->numhidden > 0) {
             print_error('cannotdeleteqtypeinuse', 'admin', admin_url('qtypes.php'), $qtypename);
         }
 
         // If not yet confirmed, display a confirmation message.
         if (!optional_param('confirm', '', PARAM_BOOL)) {
-            $qtypename = $QTYPES[$delete]->local_name();
+            $qtypename = $qtypes[$delete]->local_name();
             echo $OUTPUT->header();
             echo $OUTPUT->heading(get_string('deleteqtypeareyousure', 'admin', $qtypename));
             echo $OUTPUT->confirm(get_string('deleteqtypeareyousuremessage', 'admin', $qtypename),
         unset_config($delete . '_sortorder', 'question');
 
         // Then the tables themselves
-        drop_plugin_tables($delete, $QTYPES[$delete]->plugin_dir() . '/db/install.xml', false);
+        drop_plugin_tables($delete, $qtypes[$delete]->plugin_dir() . '/db/install.xml', false);
 
         // Remove event handlers and dequeue pending events
         events_uninstall('qtype/' . $delete);
 
         $a->qtype = $qtypename;
-        $a->directory = $QTYPES[$delete]->plugin_dir();
+        $a->directory = $qtypes[$delete]->plugin_dir();
         echo $OUTPUT->box(get_string('qtypedeletefiles', 'admin', $a), 'generalbox', 'notice');
         echo $OUTPUT->continue_button(admin_url('qtypes.php'));
         echo $OUTPUT->footer();
 /// Add a row for each question type.
     $createabletypes = question_type_menu();
     foreach ($sortedqtypes as $qtypename => $localname) {
-        $qtype = $QTYPES[$qtypename];
+        $qtype = $qtypes[$qtypename];
         $row = array();
 
         // Question icon and name.
         $strtypes = array();
         if (!empty($requiredtypes)) {
             foreach ($requiredtypes as $required) {
-                $strtypes[] = $QTYPES[$required]->local_name();
+                $strtypes[] = $qtypes[$required]->local_name();
             }
             $row[] = implode(', ', $strtypes);
         } else {
index e262ae3..e902df5 100644 (file)
@@ -232,3 +232,109 @@ $string['upgradeproblemunknowncategory'] = 'Problem detected when upgrading ques
 $string['wrongprefix'] = 'Wrongly formatted nameprefix {$a}';
 $string['youmustselectaqtype'] = 'You must select a question type.';
 $string['yourfileshoulddownload'] = 'Your export file should start to download shortly. If not, please <a href="{$a}">click here</a>.';
+
+$string['action'] = 'Action';
+$string['addanotherhint'] = 'Add another hint';
+$string['answer'] = 'Answer';
+$string['answersaved'] = 'Answer saved';
+$string['attemptfinished'] = 'Attempt finished';
+$string['attemptfinishedsubmitting'] = 'Attempt finished submitting: ';
+$string['behaviourbeingused'] = 'behaviour being used: {$a}';
+$string['cannotloadquestion'] = 'Could not load question';
+$string['cannotpreview'] = 'You can\'t preview these questions!';
+$string['category'] = 'Category';
+$string['changeoptions'] = 'Change options';
+$string['check'] = 'Check';
+$string['clearwrongparts'] = 'Clear incorrect responses';
+$string['clicktoflag'] = 'Click to flag this question';
+$string['clicktounflag'] = 'Click to un-flag this question';
+$string['closepreview'] = 'Close preview';
+$string['combinedfeedback'] = 'Combined feedback';
+$string['commented'] = 'Commented: {$a}';
+$string['comment'] = 'Comment';
+$string['commentormark'] = 'Make comment or override mark';
+$string['comments'] = 'Comments';
+$string['commentx'] = 'Comment: {$a}';
+$string['complete'] = 'Complete';
+$string['contexterror'] = 'You shouldn\'t have got here if you\'re not moving a category to another context.';
+$string['correct'] = 'Correct';
+$string['correctfeedback'] = 'For any correct response';
+$string['decimalplacesingrades'] = 'Decimal places in grades';
+$string['defaultmark'] = 'Default mark';
+$string['feedback'] = 'Feedback';
+$string['fillincorrect'] = 'Fill in correct responses';
+$string['flagged'] = 'Flagged';
+$string['flagthisquestion'] = 'Flag this question';
+$string['generalfeedback'] = 'General feedback';
+$string['generalfeedback_help'] = 'General feedback is shown to the student after they have attempted the question. Unlike feedback, which depends on the question type and what response the student gave, the same general feedback text is shown to all students.
+
+You can use the general feedback to give students some background to what knowledge the question was testing, or give them a link to more information they can use if they did not understand the questions.';
+$string['hidden'] = 'Hidden';
+$string['hintn'] = 'Hint {no}';
+$string['hinttext'] = 'Hint text';
+$string['howquestionsbehave'] = 'How questions behave';
+$string['howquestionsbehave_help'] = 'Students can interact with the questions in the quiz in various different ways. For example, you may wish the students to enter an answer to each question and then submit the entire quiz, before anything is graded or they get any feedback. That would be \'Deferred feedback\' mode. Alternatively, you may wish for students to submit each question as they go along to get immediate feedback, and if they do not get it right immediately, have another try for fewer marks. That would be \'Interactive with multiple tries\' mode.';
+$string['importfromcoursefiles'] = '... or choose a course file to import.';
+$string['importfromupload'] = 'Select a file to upload ...';
+$string['incorrect'] = 'Incorrect';
+$string['incorrectfeedback'] = 'For any incorrect response';
+$string['information'] = 'Information';
+$string['invalidanswer'] = 'Incomplete answer';
+$string['makecopy'] = 'Make copy';
+$string['manualgradeoutofrange'] = 'This grade is outside the valid range.';
+$string['manuallygraded'] = 'Manually graded {$a->mark} with comment: {$a->comment}';
+$string['mark'] = 'Mark';
+$string['markedoutof'] = 'Marked out of';
+$string['markedoutofmax'] = 'Marked out of {$a}';
+$string['markoutofmax'] = 'Mark {$a->mark} out of {$a->max}';
+$string['marks'] = 'Marks';
+$string['noresponse'] = '[No response]';
+$string['notanswered'] = 'Not answered';
+$string['notflagged'] = 'Not flagged';
+$string['notgraded'] = 'Not graded';
+$string['notshown'] = 'Not shown';
+$string['notyetanswered'] = 'Not yet answered';
+$string['notyourpreview'] = 'This preview does not belong to you';
+$string['options'] = 'Options';
+$string['partiallycorrect'] = 'Partially correct';
+$string['partiallycorrectfeedback'] = 'For any partially correct response';
+$string['penaltyforeachincorrecttry'] = 'Penalty for each incorrect try';
+$string['penaltyforeachincorrecttry_help'] = 'When you run your questions using the \'Interactive with multiple tries\' or \'Adaptive mode\' behaviour, so that the the student will have several tries to get the question right, then this option controls how much they are penalised for each incorrect try.
+
+The penalty is a proportion of the total question grade, so if the question is worth three marks, and the penalty is 0.3333333, then the student will score 3 if they get the question right first time, 2 if they get it right second try, and 1 of they get it right on the third try.';
+$string['previewquestion'] = 'Preview question: {$a}';
+$string['questionbehaviouradminsetting'] = 'Question behaviour settings';
+$string['questionbehavioursdisabled'] = 'Question behaviours to disable';
+$string['questionbehavioursdisabledexplained'] = 'Enter a comma separated list of behaviours you do not want to appear in dropdown menu';
+$string['questionbehavioursorder'] = 'Question behaviours order';
+$string['questionbehavioursorderexplained'] = 'Enter a comma separated list of behaviours in the order you want them to appear in dropdown menu';
+$string['questionidmismatch'] = 'Question ids mismatch';
+$string['questionname'] = 'Question name';
+$string['questionx'] = 'Question {$a}';
+$string['questiontext'] = 'Question text';
+$string['requiresgrading'] = 'Requires grading';
+$string['responsehistory'] = 'Response history';
+$string['restart'] = 'Start again';
+$string['restartwiththeseoptions'] = 'Start again with these options';
+$string['rightanswer'] = 'Right answer';
+$string['saved'] = 'Saved: {$a}';
+$string['saveflags'] = 'Save the state of the flags';
+$string['settingsformultipletries'] = 'Settings for multiple tries';
+$string['showmarkandmax'] = 'Show mark and max';
+$string['showmaxmarkonly'] = 'Show max mark only';
+$string['shown'] = 'Shown';
+$string['shownumpartscorrect'] = 'Show the number of correct responses';
+$string['specificfeedback'] = 'Specific feedback';
+$string['started'] = 'Started';
+$string['state'] = 'State';
+$string['step'] = 'Step';
+$string['submissionoutofsequence'] = 'Access out of sequence. Please do not click the back button when working on quiz questions.';
+$string['submissionoutofsequencefriendlymessage'] = "You have entered data outside the normal sequence. This can occur if you use your browser's Back or Forward buttons; please don't use these during the test. It can also happen if you click on something while a page is loading. Click <strong>Continue</strong> to resume.";
+$string['submit'] = 'Submit';
+$string['submitandfinish'] = 'Submit and finish';
+$string['submitted'] = 'Submit: {$a}';
+$string['unknownquestion'] = 'Unknown question: {$a}.';
+$string['unknownquestioncatregory'] = 'Unknown question category: {$a}.';
+$string['whethercorrect'] = 'Whether correct';
+$string['xoutofmax'] = '{$a->mark} out of {$a->max}';
+$string['yougotnright'] = 'You have correctly selected {$a->num}.';
index c59449a..8a187e9 100644 (file)
@@ -7021,8 +7021,9 @@ function get_plugin_types($fullpaths=true) {
                       'webservice'    => 'webservice',
                       'repository'    => 'repository',
                       'portfolio'     => 'portfolio',
-                      'qtype'         => 'question/type',
+                      'qbehaviour'    => 'question/behaviour',
                       'qformat'       => 'question/format',
+                      'qtype'         => 'question/type',
                       'plagiarism'    => 'plagiarism',
                       'theme'         => 'theme'); // this is a bit hacky, themes may be in dataroot too
 
index dc3805f..f8f6b29 100644 (file)
  * TODO: separate those functions which form part of the API
  *       from the helper functions.
  *
- * Major Contributors
- *     - Alex Smith, Julian Sedding and Gustav Delius {@link http://maths.york.ac.uk/serving_maths}
- *
- * @package    core
- * @subpackage question
- * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
- * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-/// CONSTANTS ///////////////////////////////////
-
-/**#@+
- * The different types of events that can create question states
+ * @package moodlecore
+ * @subpackage questionbank
+ * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
-define('QUESTION_EVENTOPEN', '0');      // The state was created by Moodle
-define('QUESTION_EVENTNAVIGATE', '1');  // The responses were saved because the student navigated to another page (this is not currently used)
-define('QUESTION_EVENTSAVE', '2');      // The student has requested that the responses should be saved but not submitted or validated
-define('QUESTION_EVENTGRADE', '3');     // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
-define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
-define('QUESTION_EVENTVALIDATE', '5');  // The student has requested a validation. This causes the responses to be saved as well, but not graded.
-define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
-define('QUESTION_EVENTSUBMIT', '7');    // The student response has been submitted but it has not yet been marked
-define('QUESTION_EVENTCLOSE', '8');     // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded.
-define('QUESTION_EVENTMANUALGRADE', '9');   // Grade was entered by teacher
 
-define('QUESTION_EVENTS_GRADED', QUESTION_EVENTGRADE.','.
-                    QUESTION_EVENTCLOSEANDGRADE.','.
-                    QUESTION_EVENTMANUALGRADE);
 
+require_once($CFG->dirroot . '/question/engine/lib.php');
+require_once($CFG->dirroot . '/question/type/questiontype.php');
 
-define('QUESTION_EVENTS_CLOSED', QUESTION_EVENTCLOSE.','.
-                    QUESTION_EVENTCLOSEANDGRADE.','.
-                    QUESTION_EVENTMANUALGRADE);
 
-define('QUESTION_EVENTS_CLOSED_OR_GRADED', QUESTION_EVENTGRADE.','.
-                    QUESTION_EVENTS_CLOSED);
+defined('MOODLE_INTERNAL') || die();
 
-/**#@-*/
+/// CONSTANTS ///////////////////////////////////
 
 /**#@+
  * The core question types.
@@ -87,7 +61,7 @@ define("ESSAY",         "essay");
  * Constant determines the number of answer boxes supplied in the editing
  * form for multiple choice and similar question types.
  */
-define("QUESTION_NUMANS", "10");
+define("QUESTION_NUMANS", 10);
 
 /**
  * Constant determines the number of answer boxes supplied in the editing
@@ -106,66 +80,21 @@ define("QUESTION_NUMANS_ADD", 3);
 /**
  * The options used when popping up a question preview window in Javascript.
  */
-define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes&resizable=yes&width=700&height=540');
+define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=800,height=600');
 
-/**#@+
- * Option flags for ->optionflags
- * The options are read out via bitwise operation using these constants
- */
 /**
- * Whether the questions is to be run in adaptive mode. If this is not set then
- * a question closes immediately after the first submission of responses. This
- * is how question is Moodle always worked before version 1.5
- */
-define('QUESTION_ADAPTIVE', 1);
-/**#@-*/
-
-/**#@+
- * Options for whether flags are shown/editable when rendering questions.
- */
-define('QUESTION_FLAGSHIDDEN', 0);
-define('QUESTION_FLAGSSHOWN', 1);
-define('QUESTION_FLAGSEDITABLE', 2);
-/**#@-*/
-
-/**
- * GLOBAL VARAIBLES
- * @global array $QTYPES
- * @name $QTYPES
+ * @global array holding question type objects
+ * @deprecated
  */
 global $QTYPES;
-/**
- * Array holding question type objects. Initialised via calls to
- * question_register_questiontype as the question type classes are included.
- */
-$QTYPES = array();
-
-/**
- * Add a new question type to the various global arrays above.
- *
- * @global object
- * @param object $qtype An instance of the new question type class.
- */
-function question_register_questiontype($qtype) {
-    global $QTYPES;
-
-    $name = $qtype->name();
-    $QTYPES[$name] = $qtype;
+$QTYPES = question_bank::get_all_qtypes();
+function question_register_questiontype() {
+    // TODO kill this.
 }
-
-require_once("$CFG->dirroot/question/type/questiontype.php");
-
-// Load the questiontype.php file for each question type
-// These files in turn call question_register_questiontype()
-// with a new instance of each qtype class.
-$qtypenames = get_plugin_list('qtype');
-foreach($qtypenames as $qtypename => $qdir) {
-    // Instanciates all plug-in question types
-    $qtypefilepath= "$qdir/questiontype.php";
-
-    // echo "Loading $qtypename<br/>"; // Uncomment for debugging
-    if (is_readable($qtypefilepath)) {
-        require_once($qtypefilepath);
+// TODO kill this.
+class default_questiontype {
+    function plugin_dir() {
+        return '';
     }
 }
 
@@ -177,17 +106,14 @@ foreach($qtypenames as $qtypename => $qdir) {
  * The array returned will only hold the names of all the question types that the user should
  * be able to create directly. Some internal question types like random questions are excluded.
  *
- * @global object
  * @return array an array of question type names translated to the user's language.
  */
 function question_type_menu() {
-    global $QTYPES;
     static $menuoptions = null;
     if (is_null($menuoptions)) {
         $config = get_config('question');
         $menuoptions = array();
-        foreach ($QTYPES as $name => $qtype) {
-            // Get the name if this qtype is enabled.
+        foreach (question_bank::get_all_qtypes() as $name => $qtype) {
             $menuname = $qtype->menu_name();
             $enabledvar = $name . '_disabled';
             if ($menuname && !isset($config->$enabledvar)) {
@@ -282,93 +208,58 @@ function question_save_qtype_order($neworder, $config = null) {
     }
 }
 
-/// OTHER CLASSES /////////////////////////////////////////////////////////
-
-/**
- * This holds the options that are set by the course module
- *
- * @package moodlecore
- * @subpackage question
- * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cmoptions {
-    /**
-    * Whether a new attempt should be based on the previous one. If true
-    * then a new attempt will start in a state where all responses are set
-    * to the last responses from the previous attempt.
-    */
-    var $attemptonlast = false;
-
-    /**
-    * Various option flags. The flags are accessed via bitwise operations
-    * using the constants defined in the CONSTANTS section above.
-    */
-    var $optionflags = QUESTION_ADAPTIVE;
-
-    /**
-    * Determines whether in the calculation of the score for a question
-    * penalties for earlier wrong responses within the same attempt will
-    * be subtracted.
-    */
-    var $penaltyscheme = true;
-
-    /**
-    * The maximum time the user is allowed to answer the questions withing
-    * an attempt. This is measured in minutes so needs to be multiplied by
-    * 60 before compared to timestamps. If set to 0 no timelimit will be applied
-    */
-    var $timelimit = 0;
-
-    /**
-    * Timestamp for the closing time. Responses submitted after this time will
-    * be saved but no credit will be given for them.
-    */
-    var $timeclose = 9999999999;
-
-    /**
-    * The id of the course from withing which the question is currently being used
-    */
-    var $course = SITEID;
-
-    /**
-    * Whether the answers in a multiple choice question should be randomly
-    * shuffled when a new attempt is started.
-    */
-    var $shuffleanswers = true;
-
-    /**
-    * The number of decimals to be shown when scores are printed
-    */
-    var $decimalpoints = 2;
-}
-
-
 /// FUNCTIONS //////////////////////////////////////////////////////
 
 /**
  * Returns an array of names of activity modules that use this question
  *
- * @global object
- * @global object
+ * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
+
  * @param object $questionid
  * @return array of strings
  */
 function question_list_instances($questionid) {
-    global $CFG, $DB;
-    $instances = array();
-    $modules = $DB->get_records('modules');
-    foreach ($modules as $module) {
-        $fullmod = $CFG->dirroot . '/mod/' . $module->name;
-        if (file_exists($fullmod . '/lib.php')) {
-            include_once($fullmod . '/lib.php');
-            $fn = $module->name.'_question_list_instances';
+    throw new coding_exception('question_list_instances has been deprectated. Please use questions_in_use instead.');
+}
+
+/**
+ * @param array $questionids of question ids.
+ * @return boolean whether any of these questions are being used by any part of Moodle.
+ */
+function questions_in_use($questionids) {
+    global $CFG;
+
+    if (question_engine::questions_in_use($questionids)) {
+        return true;
+    }
+
+    foreach (get_plugin_list('mod') as $module => $path) {
+        $lib = $path . '/lib.php';
+        if (is_readable($lib)) {
+            include_once($lib);
+
+            $fn = $module . '_questions_in_use';
             if (function_exists($fn)) {
-                $instances = $instances + $fn($questionid);
+                if ($fn($questionids)) {
+                    return true;
+                }
+            } else {
+
+                // Fallback for legacy modules.
+                $fn = $module . '_question_list_instances';
+                if (function_exists($fn)) {
+                    foreach ($questionids as $questionid) {
+                        $instances = $fn($questionid);
+                        if (!empty($instances)) {
+                            return true;
+                        }
+                    }
+                }
             }
         }
     }
-    return $instances;
+
+    return false;
 }
 
 /**
@@ -376,7 +267,6 @@ function question_list_instances($questionid) {
  * question categories contain any questions. This will return true even if all the questions are
  * hidden.
  *
- * @global object
  * @param mixed $context either a context object, or a context id.
  * @return boolean whether any of the question categories beloning to this context have
  *         any questions in them.
@@ -435,12 +325,11 @@ function get_grade_options() {
     $gradeoptions = array();
     foreach ($grades as $grade) {
         $percentage = 100 * $grade;
-        $neggrade = -$grade;
-        $gradeoptions["$grade"] = "$percentage %";
-        $gradeoptionsfull["$grade"] = "$percentage %";
-        $gradeoptionsfull["$neggrade"] = -$percentage." %";
+        $gradeoptions["$grade"] = $percentage . '%';
+        $gradeoptionsfull["$grade"] = $percentage . '%';
+        $gradeoptionsfull['' . (-$grade)] = (-$percentage) . '%';
     }
-    $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
+    $gradeoptionsfull['0'] = $gradeoptions['0'] = get_string('none');
 
     // sort lists
     arsort($gradeoptions, SORT_NUMERIC);
@@ -494,32 +383,40 @@ function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
 }
 
 /**
- * Tests whether a category is in use by any activity module
- *
- * @global object
- * @return boolean
- * @param integer $categoryid
- * @param boolean $recursive Whether to examine category children recursively
+ * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
+ * @param integer $categoryid a question category id.
+ * @param boolean $recursive whether to check child categories too.
+ * @return boolean whether any question in this category is in use.
  */
 function question_category_isused($categoryid, $recursive = false) {
+    throw new coding_exception('question_category_isused has been deprectated. Please use question_category_in_use instead.');
+}
+
+/**
+ * Tests whether any question in a category is used by any part of Moodle.
+ *
+ * @param integer $categoryid a question category id.
+ * @param boolean $recursive whether to check child categories too.
+ * @return boolean whether any question in this category is in use.
+ */
+function question_category_in_use($categoryid, $recursive = false) {
     global $DB;
 
     //Look at each question in the category
-    if ($questions = $DB->get_records('question', array('category'=>$categoryid), '', 'id,qtype')) {
-        foreach ($questions as $question) {
-            if (count(question_list_instances($question->id))) {
-                return true;
-            }
+    if ($questions = $DB->get_records_menu('question', array('category' => $categoryid), '', 'id,1')) {
+        if (questions_in_use(array_keys($questions))) {
+            return true;
         }
     }
+    if (!$recursive) {
+        return false;
+    }
 
     //Look under child categories recursively
-    if ($recursive) {
-        if ($children = $DB->get_records('question_categories', array('parent'=>$categoryid))) {
-            foreach ($children as $child) {
-                if (question_category_isused($child->id, $recursive)) {
-                    return true;
-                }
+    if ($children = $DB->get_records('question_categories', array('parent' => $categoryid), '', 'id,1')) {
+        foreach ($children as $child) {
+            if (question_category_in_use($child->id, $recursive)) {
+                return true;
             }
         }
     }
@@ -527,43 +424,13 @@ function question_category_isused($categoryid, $recursive = false) {
     return false;
 }
 
-/**
- * Deletes all data associated to an attempt from the database
- *
- * @global object
- * @global object
- * @param integer $attemptid The id of the attempt being deleted
- */
-function delete_attempt($attemptid) {
-    global $QTYPES, $DB;
-
-    $states = $DB->get_records('question_states', array('attempt'=>$attemptid));
-    if ($states) {
-        $stateslist = implode(',', array_keys($states));
-
-        // delete question-type specific data
-        foreach ($QTYPES as $qtype) {
-            $qtype->delete_states($stateslist);
-        }
-    }
-
-    // delete entries from all other question tables
-    // It is important that this is done only after calling the questiontype functions
-    $DB->delete_records("question_states", array("attempt"=>$attemptid));
-    $DB->delete_records("question_sessions", array("attemptid"=>$attemptid));
-    $DB->delete_records("question_attempts", array("id"=>$attemptid));
-}
-
 /**
  * Deletes question and all associated data from the database
  *
  * It will not delete a question if it is used by an activity module
- *
- * @global object
- * @global object
  * @param object $question  The question being deleted
  */
-function delete_question($questionid) {
+function question_delete_question($questionid) {
     global $QTYPES, $DB;
 
     $question = $DB->get_record_sql('
@@ -579,30 +446,19 @@ function delete_question($questionid) {
     }
 
     // Do not delete a question if it is used by an activity module
-    if (count(question_list_instances($questionid))) {
+    if (questions_in_use(array($questionid))) {
         return;
     }
 
-    // delete questiontype-specific data
+    // Check permissions.
     question_require_capability_on($question, 'edit');
-    if (isset($QTYPES[$question->qtype])) {
-        $QTYPES[$question->qtype]->delete_question($questionid, $question->contextid);
-    }
-
-    if ($states = $DB->get_records('question_states', array('question'=>$questionid))) {
-        $stateslist = implode(',', array_keys($states));
 
-        // delete questiontype-specific data
-        foreach ($QTYPES as $qtype) {
-            $qtype->delete_states($stateslist);
-        }
-    }
+    $dm = new question_engine_data_mapper();
+    $dm->delete_previews($questionid);
 
-    // Delete entries from all other question tables
-    // It is important that this is done only after calling the questiontype functions
-    $DB->delete_records('question_answers', array('question' => $questionid));
-    $DB->delete_records('question_states', array('question' => $questionid));
-    $DB->delete_records('question_sessions', array('questionid' => $questionid));
+    // delete questiontype-specific data
+    question_bank::get_qtype($question->qtype, false)->delete_question(
+            $questionid, $question->contextid);
 
     // Now recursively delete all child questions
     if ($children = $DB->get_records('question', array('parent' => $questionid), '', 'id,qtype')) {
@@ -614,13 +470,12 @@ function delete_question($questionid) {
     }
 
     // Finally delete the question record itself
-    $DB->delete_records('question', array('id'=>$questionid));
+    $DB->delete_records('question', array('id' => $questionid));
 }
 
 /**
  * All question categories and their questions are deleted for this course.
  *
- * @global object
  * @param object $mod an object representing the activity
  * @param boolean $feedback to specify if the process must output a summary of its work
  * @return boolean
@@ -674,7 +529,6 @@ function question_delete_course($course, $feedback=true) {
  * 1/ All question categories and their questions are deleted for this course category.
  * 2/ All questions are moved to new category
  *
- * @global object
  * @param object $category course category object
  * @param object $newcategory empty means everything deleted, otherwise id of category where content moved
  * @param boolean $feedback to specify if the process must output a summary of its work
@@ -752,7 +606,6 @@ function question_delete_course_category($category, $newcategory, $feedback=true
 /**
  * Enter description here...
  *
- * @global object
  * @param string $questionids list of questionids
  * @param object $newcontext the context to create the saved category in.
  * @param string $oldplace a textual description of the think being deleted, e.g. from get_context_name
@@ -784,7 +637,6 @@ function question_save_from_deletion($questionids, $newcontextid, $oldplace, $ne
 /**
  * All question categories and their questions are deleted for this activity.
  *
- * @global object
  * @param object $cm the course module object representing the activity
  * @param boolean $feedback to specify if the process must output a summary of its work
  * @return boolean
@@ -836,7 +688,6 @@ function question_delete_activity($cm, $feedback=true) {
  * acutally moving questions and associated data. However, callers of this function also have to
  * do other work, which is why you should not call this method directly from outside the questionbank.
  *
- * @global object
  * @param string $questionids a comma-separated list of question ids.
  * @param integer $newcategoryid the id of the category to move to.
  */
@@ -894,6 +745,28 @@ function question_move_category_to_context($categoryid, $oldcontextid, $newconte
     }
 }
 
+/**
+ * Generate the URL for starting a new preview of a given question with the given options.
+ * @param integer $questionid the question to preview.
+ * @param string $preferredbehaviour the behaviour to use for the preview.
+ * @param float $maxmark the maximum to mark the question out of.
+ * @param question_display_options $displayoptions the display options to use.
+ * @return string the URL.
+ */
+function question_preview_url($questionid, $preferredbehaviour, $maxmark, $displayoptions) {
+    return new moodle_url('/question/preview.php', array(
+            'id'              => $questionid,
+            'behaviour'       => $preferredbehaviour,
+            'maxmark'         => $maxmark,
+            'correctness'     => $displayoptions->correctness,
+            'marks'           => $displayoptions->marks,
+            'markdp'          => $displayoptions->markdp,
+            'feedback'        => (bool) $displayoptions->feedback,
+            'generalfeedback' => (bool) $displayoptions->generalfeedback,
+            'rightanswer'     => (bool) $displayoptions->rightanswer,
+            'history'         => (bool) $displayoptions->history));
+}
+
 /**
  * Given a list of ids, load the basic information about a set of questions from the questions table.
  * The $join and $extrafields arguments can be used together to pull in extra data.
@@ -912,7 +785,7 @@ function question_move_category_to_context($categoryid, $oldcontextid, $newconte
  * on them before they can be properly used.
  */
 function question_preload_questions($questionids, $extrafields = '', $join = '', $extraparams = array()) {
-    global $CFG, $DB;
+    global $DB;
     if (empty($questionids)) {
         return array();
     }
@@ -929,7 +802,7 @@ function question_preload_questions($questionids, $extrafields = '', $join = '',
 
     // Load the questions
     if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
-        return 'Could not load questions.';
+        return array();
     }
 
     foreach ($questions as $question) {
@@ -972,1073 +845,71 @@ function question_load_questions($questionids, $extrafields = '', $join = '') {
 /**
  * Private function to factor common code out of get_question_options().
  *
- * @global object
- * @global object
  * @param object $question the question to tidy.
  * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
  * @return boolean true if successful, else false.
  */
-function _tidy_question(&$question, $loadtags = false) {
+function _tidy_question($question, $loadtags = false) {
     global $CFG, $QTYPES;
     if (!array_key_exists($question->qtype, $QTYPES)) {
         $question->qtype = 'missingtype';
         $question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext;
     }
-    $question->name_prefix = question_make_name_prefix($question->id);
     if ($success = $QTYPES[$question->qtype]->get_question_options($question)) {
         if (isset($question->_partiallyloaded)) {
             unset($question->_partiallyloaded);
         }
     }
-    if ($loadtags && !empty($CFG->usetags)) {
-        require_once($CFG->dirroot . '/tag/lib.php');
-        $question->tags = tag_get_tags_array('question', $question->id);
-    }
-    return $success;
-}
-
-/**
- * Updates the question objects with question type specific
- * information by calling {@link get_question_options()}
- *
- * Can be called either with an array of question objects or with a single
- * question object.
- *
- * @param mixed $questions Either an array of question objects to be updated
- *         or just a single question object
- * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
- * @return bool Indicates success or failure.
- */
-function get_question_options(&$questions, $loadtags = false) {
-    if (is_array($questions)) { // deal with an array of questions
-        foreach ($questions as $i => $notused) {
-            if (!_tidy_question($questions[$i], $loadtags)) {
-                return false;
-            }
-        }
-        return true;
-    } else { // deal with single question
-        return _tidy_question($questions, $loadtags);
-    }
-}
-
-/**
- * Load the basic state information for
- *
- * @global object
- * @param integer $attemptid the attempt id to load the states for.
- * @return array an array of state data from the database, you will subsequently
- *      need to call question_load_states to get fully loaded states that can be
- *      used by the question types. The states here should be sufficient for
- *      basic tasks like rendering navigation.
- */
-function question_preload_states($attemptid) {
-    global $DB;
-    // Note, changes here probably also need to be reflected in
-    // regrade_question_in_attempt and question_load_specific_state.
-
-    // The questionid field must be listed first so that it is used as the
-    // array index in the array returned by $DB->get_records_sql
-    $statefields = 'n.questionid as question, s.id, s.attempt, ' .
-            's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' .
-            's.penalty, n.sumpenalty, n.manualcomment, n.manualcommentformat, ' .
-            'n.flagged, n.id as questionsessionid';
-
-    // Load the newest states for the questions
-    $sql = "SELECT $statefields
-              FROM {question_states} s, {question_sessions} n
-             WHERE s.id = n.newest AND n.attemptid = ?";
-    $states = $DB->get_records_sql($sql, array($attemptid));
-    if (!$states) {
-        return false;
-    }
-
-    // Load the newest graded states for the questions
-    $sql = "SELECT $statefields
-              FROM {question_states} s, {question_sessions} n
-             WHERE s.id = n.newgraded AND n.attemptid = ?";
-    $gradedstates = $DB->get_records_sql($sql, array($attemptid));
-
-    // Hook the two together.
-    foreach ($states as $questionid => $state) {
-        $states[$questionid]->_partiallyloaded = true;
-        if ($gradedstates[$questionid]) {
-            $states[$questionid]->last_graded = $gradedstates[$questionid];
-            $states[$questionid]->last_graded->_partiallyloaded = true;
-        }
-    }
-
-    return $states;
-}
-
-/**
- * Finish loading the question states that were extracted from the database with
- * question_preload_states, creating new states for any question where there
- * is not a state in the database.
- *
- * @global object
- * @global object
- * @param array $questions the questions to load state for.
- * @param array $states the partially loaded states this array is updated.
- * @param object $cmoptions options from the module we are loading the states for. E.g. $quiz.
- * @param object $attempt The attempt for which the question sessions are
- *      to be restored or created.
- * @param mixed either the id of a previous attempt, if this attmpt is
- *      building on a previous one, or false for a clean attempt.
- * @return true or false for success or failure.
- */
-function question_load_states(&$questions, &$states, $cmoptions, $attempt, $lastattemptid = false) {
-    global $QTYPES, $DB;
-
-    // loop through all questions and set the last_graded states
-    foreach (array_keys($questions) as $qid) {
-        if (isset($states[$qid])) {
-            restore_question_state($questions[$qid], $states[$qid]);
-            if (isset($states[$qid]->_partiallyloaded)) {
-                unset($states[$qid]->_partiallyloaded);
-            }
-            if (isset($states[$qid]->last_graded)) {
-                restore_question_state($questions[$qid], $states[$qid]->last_graded);
-                if (isset($states[$qid]->last_graded->_partiallyloaded)) {
-                    unset($states[$qid]->last_graded->_partiallyloaded);
-                }
-            } else {
-                $states[$qid]->last_graded = clone($states[$qid]);
-            }
-        } else {
-
-            if ($lastattemptid) {
-                // If the new attempt is to be based on this previous attempt.
-                // Find the responses from the previous attempt and save them to the new session
-
-                // Load the last graded state for the question. Note, $statefields is
-                // the same as above, except that we don't want n.manualcomment.
-                $statefields = 'n.questionid as question, s.id, s.attempt, ' .
-                        's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' .
-                        's.penalty, n.sumpenalty';
-                $sql = "SELECT $statefields
-                          FROM {question_states} s, {question_sessions} n
-                         WHERE s.id = n.newest
-                               AND n.attemptid = ?
-                               AND n.questionid = ?";
-                if (!$laststate = $DB->get_record_sql($sql, array($lastattemptid, $qid))) {
-                    // Only restore previous responses that have been graded
-                    continue;
-                }
-                // Restore the state so that the responses will be restored
-                restore_question_state($questions[$qid], $laststate);
-                $states[$qid] = clone($laststate);
-                unset($states[$qid]->id);
-            } else {
-                // create a new empty state
-                $states[$qid] = new stdClass();
-                $states[$qid]->question = $qid;
-                $states[$qid]->responses = array('' => '');
-                $states[$qid]->raw_grade = 0;
-            }
-
-            // now fill/overide initial values
-            $states[$qid]->attempt = $attempt->uniqueid;
-            $states[$qid]->seq_number = 0;
-            $states[$qid]->timestamp = $attempt->timestart;
-            $states[$qid]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN;
-            $states[$qid]->grade = 0;
-            $states[$qid]->penalty = 0;
-            $states[$qid]->sumpenalty = 0;
-            $states[$qid]->manualcomment = '';
-            $states[$qid]->manualcommentformat = FORMAT_HTML;
-            $states[$qid]->flagged = 0;
-
-            // Prevent further changes to the session from incrementing the
-            // sequence number
-            $states[$qid]->changed = true;
-
-            if ($lastattemptid) {
-                // prepare the previous responses for new processing
-                $action = new stdClass;
-                $action->responses = $laststate->responses;
-                $action->timestamp = $laststate->timestamp;
-                $action->event = QUESTION_EVENTSAVE; //emulate save of questions from all pages MDL-7631
-
-                // Process these responses ...
-                question_process_responses($questions[$qid], $states[$qid], $action, $cmoptions, $attempt);
-
-                // Fix for Bug #5506: When each attempt is built on the last one,
-                // preserve the options from any previous attempt.
-                if ( isset($laststate->options) ) {
-                    $states[$qid]->options = $laststate->options;
-                }
-            } else {
-                // Create the empty question type specific information
-                if (!$QTYPES[$questions[$qid]->qtype]->create_session_and_responses(
-                        $questions[$qid], $states[$qid], $cmoptions, $attempt)) {
-                    return false;
-                }
-            }
-            $states[$qid]->last_graded = clone($states[$qid]);
-        }
-    }
-    return true;
-}
-
-/**
-* Loads the most recent state of each question session from the database
-* or create new one.
-*
-* For each question the most recent session state for the current attempt
-* is loaded from the question_states table and the question type specific data and
-* responses are added by calling {@link restore_question_state()} which in turn
-* calls {@link restore_session_and_responses()} for each question.
-* If no states exist for the question instance an empty state object is
-* created representing the start of a session and empty question
-* type specific information and responses are created by calling
-* {@link create_session_and_responses()}.
-*
-* @return array           An array of state objects representing the most recent
-*                         states of the question sessions.
-* @param array $questions The questions for which sessions are to be restored or
-*                         created.
-* @param object $cmoptions
-* @param object $attempt  The attempt for which the question sessions are
-*                         to be restored or created.
-* @param mixed either the id of a previous attempt, if this attmpt is
-*                         building on a previous one, or false for a clean attempt.
-*/
-function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
-    // Preload the states.
-    $states = question_preload_states($attempt->uniqueid);
-    if (!$states) {
-        $states = array();
-    }
-
-    // Then finish the job.
-    if (!question_load_states($questions, $states, $cmoptions, $attempt, $lastattemptid)) {
-        return false;
-    }
-
-    return $states;
-}
-
-/**
- * Load a particular previous state of a question.
- *
- * @global object
- * @param array $question The question to load the state for.
- * @param object $cmoptions Options from the specifica activity module, e.g. $quiz.
- * @param integer $attemptid The question_attempts this is part of.
- * @param integer $stateid The id of a specific state of this question.
- * @return object the requested state. False on error.
- */
-function question_load_specific_state($question, $cmoptions, $attemptid, $stateid) {
-    global $DB;
-
-    // Load specified states for the question.
-    // sess.sumpenalty is probably wrong here shoul really be a sum of penalties from before the one we are asking for.
-    $sql = 'SELECT st.*, sess.sumpenalty, sess.manualcomment, sess.manualcommentformat,
-                        sess.flagged, sess.id as questionsessionid
-              FROM {question_states} st, {question_sessions} sess
-             WHERE st.id = ?
-               AND st.attempt = ?
-               AND sess.attemptid = st.attempt
-               AND st.question = ?
-               AND sess.questionid = st.question';
-    $state = $DB->get_record_sql($sql, array($stateid, $attemptid, $question->id));
-    if (!$state) {
-        return false;
-    }
-    restore_question_state($question, $state);
-
-    // Load the most recent graded states for the questions before the specified one.
-    $sql = 'SELECT st.*, sess.sumpenalty, sess.manualcomment, sess.manualcommentformat,
-                        sess.flagged, sess.id as questionsessionid
-              FROM {question_states} st, {question_sessions} sess
-             WHERE st.seq_number <= ?
-               AND st.attempt = ?
-               AND sess.attemptid = st.attempt
-               AND st.question = ?
-               AND sess.questionid = st.question
-               AND st.event IN ('.QUESTION_EVENTS_GRADED.') '.
-           'ORDER BY st.seq_number DESC';
-    $gradedstates = $DB->get_records_sql($sql, array($state->seq_number, $attemptid, $question->id), 0, 1);
-    if (empty($gradedstates)) {
-        $state->last_graded = clone($state);
-    } else {
-        $gradedstate = reset($gradedstates);
-        restore_question_state($question, $gradedstate);
-        $state->last_graded = $gradedstate;
-    }
-    return $state;
-}
-
-/**
-* Creates the run-time fields for the states
-*
-* Extends the state objects for a question by calling
-* {@link restore_session_and_responses()}
- *
- * @global object
-* @param object $question The question for which the state is needed
-* @param object $state The state as loaded from the database
-* @return boolean Represents success or failure
-*/
-function restore_question_state(&$question, &$state) {
-    global $QTYPES;
-
-    // initialise response to the value in the answer field
-    $state->responses = array('' => $state->answer);
-
-    // Set the changed field to false; any code which changes the
-    // question session must set this to true and must increment
-    // ->seq_number. The save_question_session
-    // function will save the new state object to the database if the field is
-    // set to true.
-    $state->changed = false;
-
-    // Load the question type specific data
-    return $QTYPES[$question->qtype]->restore_session_and_responses($question, $state);
-
-}
-
-/**
-* Saves the current state of the question session to the database
-*
-* The state object representing the current state of the session for the
-* question is saved to the question_states table with ->responses[''] saved
-* to the answer field of the database table. The information in the
-* question_sessions table is updated.
-* The question type specific data is then saved.
- *
- * @global array
- * @global object
-* @return mixed           The id of the saved or updated state or false
-* @param object $question The question for which session is to be saved.
-* @param object $state    The state information to be saved. In particular the
-*                         most recent responses are in ->responses. The object
-*                         is updated to hold the new ->id.
-*/
-function save_question_session($question, $state) {
-    global $QTYPES, $DB;
-
-    // Check if the state has changed
-    if (!$state->changed && isset($state->id)) {
-        if (isset($state->newflaggedstate) &&  $state->flagged != $state->newflaggedstate) {
-            // If this fails, don't worry too much, it is not critical data.
-            question_update_flag($state->questionsessionid, $state->newflaggedstate);
-        }
-        return $state->id;
-    }
-    // Set the legacy answer field
-    $state->answer = isset($state->responses['']) ? $state->responses[''] : '';
-
-    // Save the state
-    if (!empty($state->update)) { // this forces the old state record to be overwritten
-        $DB->update_record('question_states', $state);
-    } else {
-        $state->id = $DB->insert_record('question_states', $state);
-    }
-
-    // create or update the session
-    if (!$session = $DB->get_record('question_sessions', array('attemptid' => $state->attempt, 'questionid' => $question->id))) {
-        $session = new stdClass;
-        $session->attemptid = $state->attempt;
-        $session->questionid = $question->id;
-        $session->newest = $state->id;
-        // The following may seem weird, but the newgraded field needs to be set
-        // already even if there is no graded state yet.
-        $session->newgraded = $state->id;
-        $session->sumpenalty = $state->sumpenalty;
-        $session->manualcomment = $state->manualcomment;
-        $session->manualcommentformat = $state->manualcommentformat;
-        $session->flagged = !empty($state->newflaggedstate);
-        $DB->insert_record('question_sessions', $session);
-    } else {
-        $session->newest = $state->id;
-        if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) {
-            // this state is graded or newly opened, so it goes into the lastgraded field as well
-            $session->newgraded = $state->id;
-            $session->sumpenalty = $state->sumpenalty;
-            $session->manualcomment = $state->manualcomment;
-            $session->manualcommentformat = $state->manualcommentformat;
-        }
-        $session->flagged = !empty($state->newflaggedstate);
-        $DB->update_record('question_sessions', $session);
-    }
-
-    unset($state->answer);
-
-    // Save the question type specific state information and responses
-    if (!$QTYPES[$question->qtype]->save_session_and_responses($question, $state)) {
-        return false;
-    }
-
-    // Reset the changed flag
-    $state->changed = false;
-    return $state->id;
-}
-
-/**
-* Determines whether a state has been graded by looking at the event field
-*
-* @return boolean         true if the state has been graded
-* @param object $state
-*/
-function question_state_is_graded($state) {
-    static $question_events_graded = array();
-    if (!$question_events_graded){
-        $question_events_graded = explode(',', QUESTION_EVENTS_GRADED);
-    }
-    return (in_array($state->event, $question_events_graded));
-}
-
-/**
-* Determines whether a state has been closed by looking at the event field
-*
-* @return boolean         true if the state has been closed
-* @param object $state
-*/
-function question_state_is_closed($state) {
-    static $question_events_closed = array();
-    if (!$question_events_closed){
-        $question_events_closed = explode(',', QUESTION_EVENTS_CLOSED);
-    }
-    return (in_array($state->event, $question_events_closed));
-}
-
-
-/**
- * Extracts responses from submitted form
- *
- * This can extract the responses given to one or several questions present on a page
- * It returns an array with one entry for each question, indexed by question id
- * Each entry is an object with the properties
- *  ->event     The event that has triggered the submission. This is determined by which button
- *               the user has pressed.
- *  ->responses An array holding the responses to an individual question, indexed by the
- *               name of the corresponding form element.
- *  ->timestamp A unix timestamp
- * @return array            array of action objects, indexed by question ids.
- * @param array $questions  an array containing at least all questions that are used on the form
- * @param array $formdata   the data submitted by the form on the question page
- * @param integer $defaultevent  the event type used if no 'mark' or 'validate' is submitted
- */
-function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) {
-
-    $time = time();
-    $actions = array();
-    foreach ($formdata as $key => $response) {
-        // Get the question id from the response name
-        if (false !== ($quid = question_get_id_from_name_prefix($key))) {
-            // check if this is a valid id
-            if (!isset($questions[$quid])) {
-                print_error('formquestionnotinids', 'question');
-            }
-
-            // Remove the name prefix from the name
-            //decrypt trying
-            $key = substr($key, strlen($questions[$quid]->name_prefix));
-            if (false === $key) {
-                $key = '';
-            }
-            // Check for question validate and mark buttons & set events
-            if ($key === 'validate') {
-                $actions[$quid]->event = QUESTION_EVENTVALIDATE;
-            } else if ($key === 'submit') {
-                $actions[$quid]->event = QUESTION_EVENTSUBMIT;
-            } else {
-                $actions[$quid]->event = $defaultevent;
-            }
-            // Update the state with the new response
-            $actions[$quid]->responses[$key] = $response;
-
-            // Set the timestamp
-            $actions[$quid]->timestamp = $time;
-        }
-    }
-    foreach ($actions as $quid => $notused) {
-        ksort($actions[$quid]->responses);
-    }
-    return $actions;
-}
-
-
-/**
- * Returns the html for question feedback image.
- *
- * @global object
- * @param float   $fraction  value representing the correctness of the user's
- *                           response to a question.
- * @param boolean $selected  whether or not the answer is the one that the
- *                           user picked.
- * @return string
- */
-function question_get_feedback_image($fraction, $selected=true) {
-    global $CFG, $OUTPUT;
-    static $icons = array('correct' => 'tick_green', 'partiallycorrect' => 'tick_amber',
-            'incorrect' => 'cross_red');
-
-    if ($selected) {
-        $size = 'big';
-    } else {
-        $size = 'small';
-    }
-    $class = question_get_feedback_class($fraction);
-    return '<img src="' . $OUTPUT->pix_url('i/' . $icons[$class] . '_' . $size) .
-            '" alt="' . get_string($class, 'quiz') . '" class="icon" />';
-}
-
-/**
- * Returns the class name for question feedback.
- * @param float  $fraction  value representing the correctness of the user's
- *                          response to a question.
- * @return string
- */
-function question_get_feedback_class($fraction) {
-    if ($fraction >= 1/1.01) {
-        return 'correct';
-    } else if ($fraction > 0.0) {
-        return 'partiallycorrect';
-    } else {
-        return 'incorrect';
-    }
-}
-
-
-/**
-* For a given question in an attempt we walk the complete history of states
-* and recalculate the grades as we go along.
-*
-* This is used when a question is changed and old student
-* responses need to be marked with the new version of a question.
-*
-* @todo Make sure this is not quiz-specific
-*
- * @global object
-* @return boolean            Indicates whether the grade has changed
-* @param object  $question   A question object
-* @param object  $attempt    The attempt, in which the question needs to be regraded.
-* @param object  $cmoptions
-* @param boolean $verbose    Optional. Whether to print progress information or not.
-* @param boolean $dryrun     Optional. Whether to make changes to grades records
-* or record that changes need to be made for a later regrade.
-*/
-function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false, $dryrun=false) {
-    global $DB, $OUTPUT;
-
-    // load all states for this question in this attempt, ordered in sequence
-    if ($states = $DB->get_records('question_states',
-            array('attempt'=>$attempt->uniqueid, 'question'=>$question->id),
-            'seq_number ASC')) {
-        $states = array_values($states);
-
-        // Subtract the grade for the latest state from $attempt->sumgrades to get the
-        // sumgrades for the attempt without this question.
-        $attempt->sumgrades -= $states[count($states)-1]->grade;
-
-        // Initialise the replaystate
-        $replaystate = question_load_specific_state($question, $cmoptions, $attempt->uniqueid, $states[0]->id);
-        $replaystate->sumpenalty = 0;
-        $replaystate->last_graded->sumpenalty = 0;
-
-        $changed = false;
-        for($j = 1; $j < count($states); $j++) {
-            restore_question_state($question, $states[$j]);
-            $action = new stdClass;
-            $action->responses = $states[$j]->responses;
-            $action->timestamp = $states[$j]->timestamp;
-
-            // Change event to submit so that it will be reprocessed
-            if (in_array($states[$j]->event, array(QUESTION_EVENTCLOSE,
-                    QUESTION_EVENTGRADE, QUESTION_EVENTCLOSEANDGRADE))) {
-                $action->event = QUESTION_EVENTSUBMIT;
-
-            // By default take the event that was saved in the database
-            } else {
-                $action->event = $states[$j]->event;
-            }
-
-            if ($action->event == QUESTION_EVENTMANUALGRADE) {
-                // Ensure that the grade is in range - in the past this was not checked,
-                // but now it is (MDL-14835) - so we need to ensure the data is valid before
-                // proceeding.
-                if ($states[$j]->grade < 0) {
-                    $states[$j]->grade = 0;
-                    $changed = true;
-                } else if ($states[$j]->grade > $question->maxgrade) {
-                    $states[$j]->grade = $question->maxgrade;
-                    $changed = true;
-
-                }
-                if (!$dryrun){
-                    $error = question_process_comment($question, $replaystate, $attempt,
-                            $replaystate->manualcomment, $replaystate->manualcommentformat, $states[$j]->grade);
-                    if (is_string($error)) {
-                         echo $OUTPUT->notification($error);
-                    }
-                } else {
-                    $replaystate->grade = $states[$j]->grade;
-                }
-            } else {
-                // Reprocess (regrade) responses
-                if (!question_process_responses($question, $replaystate,
-                        $action, $cmoptions, $attempt) && $verbose) {
-                    $a = new stdClass;
-                    $a->qid = $question->id;
-                    $a->stateid = $states[$j]->id;
-                    echo $OUTPUT->notification(get_string('errorduringregrade', 'question', $a));
-                }
-                // We need rounding here because grades in the DB get truncated
-                // e.g. 0.33333 != 0.3333333, but we want them to be equal here
-                if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5))
-                        or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5))
-                        or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) {
-                    $changed = true;
-                }
-                // If this was previously a closed state, and it has been knoced back to
-                // graded, then fix up the state again.
-                if ($replaystate->event == QUESTION_EVENTGRADE &&
-                        ($states[$j]->event == QUESTION_EVENTCLOSE ||
-                        $states[$j]->event == QUESTION_EVENTCLOSEANDGRADE)) {
-                    $replaystate->event = $states[$j]->event;
-                }
-            }
-
-            $replaystate->id = $states[$j]->id;
-            $replaystate->changed = true;
-            $replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created
-            if (!$dryrun){
-                save_question_session($question, $replaystate);
-            }
-        }
-        if ($changed) {
-            if (!$dryrun){
-                // TODO, call a method in quiz to do this, where 'quiz' comes from
-                // the question_attempts table.
-                $DB->update_record('quiz_attempts', $attempt);
-            }
-        }
-        if ($changed){
-            $toinsert = new stdClass();
-            $toinsert->oldgrade = round((float)$states[count($states)-1]->grade, 5);
-            $toinsert->newgrade = round((float)$replaystate->grade, 5);
-            $toinsert->attemptid = $attempt->uniqueid;
-            $toinsert->questionid = $question->id;
-            //the grade saved is the old grade if the new grade is saved
-            //it is the new grade if this is a dry run.
-            $toinsert->regraded = $dryrun?0:1;
-            $toinsert->timemodified = time();
-            $DB->insert_record('quiz_question_regrade', $toinsert);
-            return true;
-        } else {
-            return false;
-        }
-    }
-    return false;
-}
-
-/**
-* Processes an array of student responses, grading and saving them as appropriate
-*
- * @global array
-* @param object $question Full question object, passed by reference
-* @param object $state    Full state object, passed by reference
-* @param object $action   object with the fields ->responses which
-*                         is an array holding the student responses,
-*                         ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
-*                         and ->timestamp which is a timestamp from when the responses
-*                         were submitted by the student.
-* @param object $cmoptions
-* @param object $attempt  The attempt is passed by reference so that
-*                         during grading its ->sumgrades field can be updated
-* @return boolean         Indicates success/failure
-*/
-function question_process_responses($question, &$state, $action, $cmoptions, &$attempt) {
-    global $QTYPES;
-
-    // if no responses are set initialise to empty response
-    if (!isset($action->responses)) {
-        $action->responses = array('' => '');
-    }
-
-    $state->newflaggedstate = !empty($action->responses['_flagged']);
-
-    // make sure these are gone!
-    unset($action->responses['submit'], $action->responses['validate'], $action->responses['_flagged']);
-
-    // Check the question session is still open
-    if (question_state_is_closed($state)) {
-        return true;
-    }
-
-    // If $action->event is not set that implies saving
-    if (! isset($action->event)) {
-        debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER);
-        $action->event = QUESTION_EVENTSAVE;
-    }
-    // If submitted then compare against last graded
-    // responses, not last given responses in this case
-    if (question_isgradingevent($action->event)) {
-        $state->responses = $state->last_graded->responses;
-    }
-
-    // Check for unchanged responses (exactly unchanged, not equivalent).
-    // We also have to catch questions that the student has not yet attempted
-    $sameresponses = $QTYPES[$question->qtype]->compare_responses($question, $action, $state);
-    if (!empty($state->last_graded) && $state->last_graded->event == QUESTION_EVENTOPEN &&
-            question_isgradingevent($action->event)) {
-        $sameresponses = false;
-    }
-
-    // If the response has not been changed then we do not have to process it again
-    // unless the attempt is closing or validation is requested
-    if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
-            and QUESTION_EVENTVALIDATE != $action->event) {
-        return true;
-    }
-
-    // Roll back grading information to last graded state and set the new
-    // responses
-    $newstate = clone($state->last_graded);
-    $newstate->responses = $action->responses;
-    $newstate->seq_number = $state->seq_number + 1;
-    $newstate->changed = true; // will assure that it gets saved to the database
-    $newstate->last_graded = clone($state->last_graded);
-    $newstate->timestamp = $action->timestamp;
-    $newstate->newflaggedstate = $state->newflaggedstate;
-    $newstate->flagged = $state->flagged;
-    $newstate->questionsessionid = $state->questionsessionid;
-    $state = $newstate;
-
-    // Set the event to the action we will perform. The question type specific
-    // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
-    // attempt at the question causes the session to close
-    $state->event = $action->event;
-
-    if (!question_isgradingevent($action->event)) {
-        // Grade the response but don't update the overall grade
-        if (!$QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions)) {
-            return false;
-        }
-
-        // Temporary hack because question types are not given enough control over what is going
-        // on. Used by Opaque questions.
-        // TODO fix this code properly.
-        if (!empty($state->believeevent)) {
-            // If the state was graded we need to ...
-            if (question_state_is_graded($state)) {
-                question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
-
-                // update the attempt grade
-                $attempt->sumgrades -= (float)$state->last_graded->grade;
-                $attempt->sumgrades += (float)$state->grade;
-
-                // and update the last_graded field.
-                unset($state->last_graded);
-                $state->last_graded = clone($state);
-                unset($state->last_graded->changed);
-            }
-        } else {
-            // Don't allow the processing to change the event type
-            $state->event = $action->event;
-        }
-
-    } else { // grading event
-
-        // Unless the attempt is closing, we want to work out if the current responses
-        // (or equivalent responses) were already given in the last graded attempt.
-        if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event &&
-                $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) {
-            $state->event = QUESTION_EVENTDUPLICATE;
-        }
-
-        // If we did not find a duplicate or if the attempt is closing, perform grading
-        if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or
-                QUESTION_EVENTCLOSE == $action->event) {
-            if (!$QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions)) {
-                return false;
-            }
-
-            // Calculate overall grade using correct penalty method
-            question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
-        }
-
-        // If the state was graded we need to ...
-        if (question_state_is_graded($state)) {
-            // update the attempt grade
-            $attempt->sumgrades -= (float)$state->last_graded->grade;
-            $attempt->sumgrades += (float)$state->grade;
-
-            // and update the last_graded field.
-            unset($state->last_graded);
-            $state->last_graded = clone($state);
-            unset($state->last_graded->changed);
-        }
-    }
-    $attempt->timemodified = $action->timestamp;
-
-    return true;
-}
-
-/**
-* Determine if event requires grading
-*/
-function question_isgradingevent($event) {
-    return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event);
-}
-
-/**
-* Applies the penalty from the previous graded responses to the raw grade
-* for the current responses
-*
-* The grade for the question in the current state is computed by subtracting the
-* penalty accumulated over the previous graded responses at the question from the
-* raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
-* the grade is set to zero. The ->grade field of the state object is modified to
-* reflect the new grade but is never allowed to decrease.
-* @param object $question The question for which the penalty is to be applied.
-* @param object $state    The state for which the grade is to be set from the
-*                         raw grade and the cumulative penalty from the last
-*                         graded state. The ->grade field is updated by applying
-*                         the penalty scheme determined in $cmoptions to the ->raw_grade and
-*                         ->last_graded->penalty fields.
-* @param object $cmoptions  The options set by the course module.
-*                           The ->penaltyscheme field determines whether penalties
-*                           for incorrect earlier responses are subtracted.
-*/
-function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
-    // TODO. Quiz dependancy. The fact that the attempt that is passed in here
-    // is from quiz_attempts, and we use things like $cmoptions->timelimit.
-
-    // deal with penalty
-    if ($cmoptions->penaltyscheme) {
-        $state->grade = $state->raw_grade - $state->sumpenalty;
-        $state->sumpenalty += (float) $state->penalty;
-    } else {
-        $state->grade = $state->raw_grade;
-    }
-
-    // deal with timelimit
-    if ($cmoptions->timelimit) {
-        // We allow for 5% uncertainty in the following test
-        if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 1.05) {
-            $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
-            if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id),
-                    $attempt->userid, false)) {
-                $state->grade = 0;
-            }
-        }
-    }
-
-    // deal with closing time
-    if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness
-             and !$attempt->preview) { // ignore closing time for previews
-        $state->grade = 0;
-    }
-
-    // Ensure that the grade does not go down
-    $state->grade = max($state->grade, $state->last_graded->grade);
-}
-
-/**
-* Print the icon for the question type
-*
- * @global array
- * @global object
-* @param object $question The question object for which the icon is required
-*       only $question->qtype is used.
-* @param boolean $return If true the functions returns the link as a string
-*/
-function print_question_icon($question, $return = false) {
-    global $QTYPES, $CFG, $OUTPUT;
-
-    if (array_key_exists($question->qtype, $QTYPES)) {
-        $namestr = $QTYPES[$question->qtype]->local_name();
-    } else {
-        $namestr = 'missingtype';
-    }
-    $html = '<img src="' . $OUTPUT->pix_url('icon', 'qtype_'.$question->qtype) . '" alt="' .
-            $namestr . '" title="' . $namestr . '" />';
-    if ($return) {
-        return $html;
-    } else {
-        echo $html;
-    }
-}
-
-/**
- * @param $question
- * @param $state
- * @param $prefix
- * @param $cmoptions
- * @param $caption
- */
-function question_print_comment_fields($question, $state, $prefix, $cmoptions, $caption = '') {
-    global $QTYPES;
-    $idprefix = preg_replace('/[^-_a-zA-Z0-9]/', '', $prefix);
-    $otherquestionsinuse = '';
-    if (!empty($cmoptions->questions)) {
-        $otherquestionsinuse = $cmoptions->questions;
-    }
-    if (!question_state_is_graded($state) && $QTYPES[$question->qtype]->is_question_manual_graded($question, $otherquestionsinuse)) {
-        $grade = '';
-    } else {
-        $grade = question_format_grade($cmoptions, $state->last_graded->grade);
-    }
-    $maxgrade = question_format_grade($cmoptions, $question->maxgrade);
-    $fieldsize = strlen($maxgrade) - 1;
-    if (empty($caption)) {
-        $caption = format_string($question->name);
-    }
-    ?>
-<fieldset class="que comment clearfix">
-    <legend class="ftoggler"><?php echo $caption; ?></legend>
-    <div class="fcontainer clearfix">
-        <div class="fitem">
-            <div class="fitemtitle">
-                <label for="<?php echo $idprefix; ?>_comment_box"><?php print_string('comment', 'quiz'); ?></label>
-            </div>
-            <div class="felement fhtmleditor">
-                <?php print_textarea(can_use_html_editor(), 15, 60, 630, 300, $prefix . '[comment]',
-                        $state->manualcomment, 0, false, $idprefix . '_comment_box'); ?>
-            </div>
-        </div>
-        <div class="fitem">
-            <div class="fitemtitle">
-                <label for="<?php echo $idprefix; ?>_grade_field"><?php print_string('grade', 'quiz'); ?></label>
-            </div>
-            <div class="felement ftext">
-                <input type="text" name="<?php echo $prefix; ?>[grade]" size="<?php echo $fieldsize; ?>" id="<?php echo $idprefix; ?>_grade_field" value="<?php echo $grade; ?>" /> / <?php echo $maxgrade; ?>
-            </div>
-        </div>
-    </div>
-</fieldset>
-    <?php
-}
-
-/**
- * Process a manual grading action. That is, use $comment and $grade to update
- * $state and $attempt. The attempt and the comment text are stored in the
- * database. $state is only updated in memory, it is up to the call to store
- * that, if appropriate.
- *
- * @global object
- * @param object $question the question
- * @param object $state the state to be updated.
- * @param object $attempt the attempt the state belongs to, to be updated.
- * @param string $comment the new comment from the teacher.
- * @param mixed $grade the grade the teacher assigned, or '' to not change the grade.
- * @return mixed true on success, a string error message if a problem is detected
- *         (for example score out of range).
- */
-function question_process_comment($question, &$state, &$attempt, $comment, $commentformat, $grade) {
-    global $DB;
-
-    $grade = trim($grade);
-    if ($grade < 0 || $grade > $question->maxgrade) {
-        $a = new stdClass;
-        $a->grade = $grade;
-        $a->maxgrade = $question->maxgrade;
-        $a->name = $question->name;
-        return get_string('errormanualgradeoutofrange', 'question', $a);
-    }
-
-    // Update the comment and save it in the database
-    $comment = trim($comment);
-    $state->manualcomment = $comment;
-    $state->manualcommentformat = $commentformat;
-    $state->newflaggedstate = $state->flagged;
-    $DB->set_field('question_sessions', 'manualcomment', $comment, array('attemptid'=>$attempt->uniqueid, 'questionid'=>$question->id));
-
-    // Update the attempt if the score has changed.
-    if ($grade !== '' && (abs($state->last_graded->grade - $grade) > 0.002 || $state->last_graded->event != QUESTION_EVENTMANUALGRADE)) {
-        $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade;
-        $attempt->timemodified = time();
-        $DB->update_record('quiz_attempts', $attempt);
-
-        // We want to update existing state (rather than creating new one) if it
-        // was itself created by a manual grading event.
-        $state->update = $state->event == QUESTION_EVENTMANUALGRADE;
-
-        // Update the other parts of the state object.
-        $state->raw_grade = $grade;
-        $state->grade = $grade;
-        $state->penalty = 0;
-        $state->timestamp = time();
-        $state->seq_number++;
-        $state->event = QUESTION_EVENTMANUALGRADE;
-
-        // Update the last graded state (don't simplify!)
-        unset($state->last_graded);
-        $state->last_graded = clone($state);
-
-        // We need to indicate that the state has changed in order for it to be saved.
-        $state->changed = 1;
-    }
-
-    return true;
-}
-
-/**
-* Construct name prefixes for question form element names
-*
-* Construct the name prefix that should be used for example in the
-* names of form elements created by questions.
-* This is called by {@link get_question_options()}
-* to set $question->name_prefix.
-* This name prefix includes the question id which can be
-* extracted from it with {@link question_get_id_from_name_prefix()}.
-*
-* @return string
-* @param integer $id  The question id
-*/
-function question_make_name_prefix($id) {
-    return 'resp' . $id . '_';
-}
-
-/**
- * Extract question id from the prefix of form element names
- *
- * @return integer      The question id
- * @param string $name  The name that contains a prefix that was
- *                      constructed with {@link question_make_name_prefix()}
- */
-function question_get_id_from_name_prefix($name) {
-    if (!preg_match('/^resp([0-9]+)_/', $name, $matches)) {
-        return false;
-    }
-    return (integer) $matches[1];
+    if ($loadtags && !empty($CFG->usetags)) {
+        require_once($CFG->dirroot . '/tag/lib.php');
+        $question->tags = tag_get_tags_array('question', $question->id);
+    }
+    return $success;
 }
 
 /**
- * Extract question id from the prefix of form element names
+ * Updates the question objects with question type specific
+ * information by calling {@link get_question_options()}
+ *
+ * Can be called either with an array of question objects or with a single
+ * question object.
  *
- * @return integer      The question id
- * @param string $name  The name that contains a prefix that was
- *                      constructed with {@link question_make_name_prefix()}
+ * @param mixed $questions Either an array of question objects to be updated
+ *         or just a single question object
+ * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
+ * @return bool Indicates success or failure.
  */
-function question_id_and_key_from_post_name($name) {
-    if (!preg_match('/^resp([0-9]+)_(.*)$/', $name, $matches)) {
-        return array(false, false);
+function get_question_options(&$questions, $loadtags = false) {
+    if (is_array($questions)) { // deal with an array of questions
+        foreach ($questions as $i => $notused) {
+            if (!_tidy_question($questions[$i], $loadtags)) {
+                return false;
+            }
+        }
+        return true;
+    } else { // deal with single question
+        return _tidy_question($questions, $loadtags);
     }
-    return array((integer) $matches[1], $matches[2]);
 }
 
 /**
- * Returns the unique id for a new attempt
- *
- * Every module can keep their own attempts table with their own sequential ids but
- * the question code needs to also have a unique id by which to identify all these
- * attempts. Hence a module, when creating a new attempt, calls this function and
- * stores the return value in the 'uniqueid' field of its attempts table.
- *
- * @global object
- */
-function question_new_attempt_uniqueid($modulename='quiz') {
-    global $DB;
+* Print the icon for the question type
+*
+* @param object $question The question object for which the icon is required.
+*       Only $question->qtype is used.
+* @return string the HTML for the img tag.
+*/
+function print_question_icon($question) {
+    global $OUTPUT;
+
+    $qtype = question_bank::get_qtype($question->qtype, false);
+    $namestr = $qtype->menu_name();
+
+    // TODO convert to return a moodle_icon object, or whatever the class is.
+    $html = '<img src="' . $OUTPUT->pix_url('icon', $qtype->plugin_name()) . '" alt="' .
+            $namestr . '" title="' . $namestr . '" />';
 
-    $attempt = new stdClass;
-    $attempt->modulename = $modulename;
-    $id = $DB->insert_record('question_attempts', $attempt);
-    return $id;
+    return $html;
 }
 
 /**
@@ -2054,124 +925,22 @@ function question_hash($question) {
     return make_unique_id_code();
 }
 
-/**
- * Round a grade to to the correct number of decimal places, and format it for display.
- * If $cmoptions->questiondecimalpoints is set, that is used, otherwise
- * else if $cmoptions->decimalpoints is used,
- * otherwise a default of 2 is used, but this should not be relied upon, and generated a developer debug warning.
- * However, if $cmoptions->questiondecimalpoints is -1, the means use $cmoptions->decimalpoints.
- *
- * @param object $cmoptions The modules settings.
- * @param float $grade The grade to round.
- */
-function question_format_grade($cmoptions, $grade) {
-    if (isset($cmoptions->questiondecimalpoints) && $cmoptions->questiondecimalpoints != -1) {
-        $decimalplaces = $cmoptions->questiondecimalpoints;
-    } else if (isset($cmoptions->decimalpoints)) {
-        $decimalplaces = $cmoptions->decimalpoints;
-    } else {
-        $decimalplaces = 2;
-        debugging('Code that leads to question_format_grade being called should set ' .
-                '$cmoptions->questiondecimalpoints or $cmoptions->decimalpoints', DEBUG_DEVELOPER);
-    }
-    return format_float($grade, $decimalplaces);
-}
-
-/**
- * @return string An inline script that creates a JavaScript object storing
- * various strings and bits of configuration that the scripts in qengine.js need
- * to get from PHP.
- */
-function question_init_qengine_js() {
-    global $CFG, $PAGE, $OUTPUT;
-    static $done = false;
-    if ($done) {
-        return;
-    }
-    $module = array(
-        'name' => 'core_question_flags',
-        'fullpath' => '/question/flags.js',
-        'requires' => array('base', 'dom', 'event-delegate', 'io-base'),
-    );
-    $actionurl = $CFG->wwwroot . '/question/toggleflag.php';
-    $flagattributes = array(
-        0 => array(
-            'src' => $OUTPUT->pix_url('i/unflagged') . '',
-            'title' => get_string('clicktoflag', 'question'),
-            'alt' => get_string('notflagged', 'question'),
-        ),
-        1 => array(
-            'src' => $OUTPUT->pix_url('i/flagged') . '',
-            'title' => get_string('clicktounflag', 'question'),
-            'alt' => get_string('flagged', 'question'),
-        ),
-    );
-    $PAGE->requires->js_init_call('M.core_question_flags.init',
-            array($actionurl, $flagattributes), false, $module);
-    $done = true;
-}
-
 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
 /**
- * Give the questions in $questionlist a chance to request the CSS or JavaScript
- * they need, before the header is printed.
- *
- * If your code is going to call the print_question function, it must call this
- * funciton before print_header.
- *
- * @param array $questionlist a list of questionids of the questions what will appear on this page.
- * @param array $questions an array of question objects, whose keys are question ids.
- *      Must contain all the questions in $questionlist
- * @param array $states an array of question state objects, whose keys are question ids.
- *      Must contain the state of all the questions in $questionlist
- */
-function question_get_html_head_contributions($questionlist, &$questions, &$states) {
-    global $CFG, $PAGE, $QTYPES;
-
-    // The question engine's own JavaScript.
-    question_init_qengine_js();
-
-    // Anything that questions on this page need.
-    foreach ($questionlist as $questionid) {
-        $question = $questions[$questionid];
-        $QTYPES[$question->qtype]->get_html_head_contributions($question, $states[$questionid]);
-    }
-}
-
-/**
- * Like {@link get_html_head_contributions()} but for the editing page
- * question/question.php.
+ * Get anything that needs to be included in the head of the question editing page
+ * for a particular question type. This function is called by question/question.php.
  *
  * @param $question A question object. Only $question->qtype is used.
  * @return string Deprecated. Some HTML code that can go inside the head tag.
  */
 function question_get_editing_head_contributions($question) {
-    global $QTYPES;
-    $QTYPES[$question->qtype]->get_editing_head_contributions();
+    question_bank::get_qtype($question->qtype, false)->get_editing_head_contributions();
 }
 
-/**
- * Prints a question
- *
- * Simply calls the question type specific print_question() method.
- *
- * @global array
- * @param object $question The question to be rendered.
- * @param object $state    The state to render the question in.
- * @param integer $number  The number for this question.
- * @param object $cmoptions  The options specified by the course module
- * @param object $options  An object specifying the rendering options.
- */
-function print_question(&$question, &$state, $number, $cmoptions, $options=null, $context=null) {
-    global $QTYPES;
-    $QTYPES[$question->qtype]->print_question($question, $state, $number, $cmoptions, $options, $context);
-}
 /**
  * Saves question options
  *
  * Simply calls the question type specific save_question_options() method.
- *
- * @global array
  */
 function save_question_options($question) {
     global $QTYPES;
@@ -2179,66 +948,12 @@ function save_question_options($question) {
     $QTYPES[$question->qtype]->save_question_options($question);
 }
 
-/**
-* Gets all teacher stored answers for a given question
-*
-* Simply calls the question type specific get_all_responses() method.
- *
- * @global array
-*/
-// ULPGC ecastro
-function get_question_responses($question, $state) {
-    global $QTYPES;
-    $r = $QTYPES[$question->qtype]->get_all_responses($question, $state);
-    return $r;
-}
-
-/**
-* Gets the response given by the user in a particular state
-*
-* Simply calls the question type specific get_actual_response() method.
- *
- * @global array
-*/
-// ULPGC ecastro
-function get_question_actual_response($question, $state) {
-    global $QTYPES;
-
-    $r = $QTYPES[$question->qtype]->get_actual_response($question, $state);
-    return $r;
-}
-
-/**
-* TODO: document this
- *
- * @global array
-*/
-// ULPGc ecastro
-function get_question_fraction_grade($question, $state) {
-    global $QTYPES;
-
-    $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state);
-    return $r;
-}
-/**
- * @global array
-* @return integer grade out of 1 that a random guess by a student might score.
-*/
-// ULPGc ecastro
-function question_get_random_guess_score($question) {
-    global $QTYPES;
-
-    $r = $QTYPES[$question->qtype]->get_random_guess_score($question);
-    return $r;
-}
 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
 
 /**
  * returns the categories with their names ordered following parent-child relationships
  * finally it tries to return pending categories (those being orphaned, whose parent is
  * incorrect) to avoid missing any category from original array.
- *
- * @global object
  */
 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
     global $DB;
@@ -2365,7 +1080,6 @@ function question_category_select_menu($contexts, $top = false, $currentcat = 0,
 }
 
 /**
- * @global object
  * @param integer $contextid a context id.
  * @return object the default question category for that context, or false if none.
  */
@@ -2379,42 +1093,10 @@ function question_get_default_category($contextid) {
     }
 }
 
-/**
- * @global object
- * @global object
- * @param object $context a context
- * @return string A URL for editing questions in this context.
- */
-function question_edit_url($context) {
-    global $CFG, $SITE;
-    if (!has_any_capability(question_get_question_capabilities(), $context)) {
-        return false;
-    }
-    $baseurl = $CFG->wwwroot . '/question/edit.php?';
-    $defaultcategory = question_get_default_category($context->id);
-    if ($defaultcategory) {
-        $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
-    }
-    switch ($context->contextlevel) {
-        case CONTEXT_SYSTEM:
-            return $baseurl . 'courseid=' . $SITE->id;
-        case CONTEXT_COURSECAT:
-            // This is nasty, becuase we can only edit questions in a course
-            // context at the moment, so for now we just return false.
-            return false;
-        case CONTEXT_COURSE:
-            return $baseurl . 'courseid=' . $context->instanceid;
-        case CONTEXT_MODULE:
-            return $baseurl . 'cmid=' . $context->instanceid;
-    }
-
-}
-
 /**
 * Gets the default category in the most specific context.
 * If no categories exist yet then default ones are created in all contexts.
 *
- * @global object
 * @param array $contexts  The context objects for this context and all parent contexts.
 * @return object The default category - the category in the course context
 */
@@ -2462,7 +1144,6 @@ function question_make_default_categories($contexts) {
  * Get all the category objects, including a count of the number of questions in that category,
  * for all the categories in the lists $contexts.
  *
- * @global object
  * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
  * @param string $sortorder used as the ORDER BY clause in the select statement.
  * @return array of category objects.
@@ -2479,7 +1160,6 @@ function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder,
 
 /**
  * Output an array of question categories.
- * @global object
  */
 function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false, $nochildrenof = -1) {
     global $CFG;
@@ -2537,6 +1217,7 @@ function question_add_context_in_key($categories){
     }
     return $newcatarray;
 }
+
 function question_add_tops($categories, $pcontexts){
     $topcats = array();
     foreach ($pcontexts as $context){
@@ -2553,14 +1234,13 @@ function question_add_tops($categories, $pcontexts){
 
 /**
  * Returns a comma separated list of ids of the category and all subcategories
- * @global object
  */
 function question_categorylist($categoryid) {
     global $DB;
 
     // returns a comma separated list of ids of the category and all subcategories
     $categorylist = $categoryid;
-    if ($subcategories = $DB->get_records('question_categories', array('parent'=>$categoryid), 'sortorder ASC', 'id, 1')) {
+    if ($subcategories = $DB->get_records('question_categories', array('parent' => $categoryid), 'sortorder ASC', 'id, 1')) {
         foreach ($subcategories as $subcategory) {
             $categorylist .= ','. question_categorylist($subcategory->id);
         }
@@ -2568,52 +1248,40 @@ function question_categorylist($categoryid) {
     return $categorylist;
 }
 
-
-
-
 //===========================
 // Import/Export Functions
 //===========================
 
 /**
  * Get list of available import or export formats
- *
- * @global object
  * @param string $type 'import' if import list, otherwise export list assumed
  * @return array sorted list of import/export formats available
  */
-function get_import_export_formats( $type ) {
+function get_import_export_formats($type) {
 
     global $CFG;
-    $fileformats = get_plugin_list("qformat");
+    $fileformats = get_plugin_list('qformat');
 
     $fileformatname=array();
     require_once( "{$CFG->dirroot}/question/format.php" );
-    foreach ($fileformats as $fileformat=>$fdir) {
-        $format_file = "$fdir/format.php";
-        if (file_exists($format_file) ) {
-            require_once($format_file);
-        }
-        else {
+    foreach ($fileformats as $fileformat => $fdir) {
+        $formatfile = $fdir . '/format.php';
+        if (is_readable($formatfile)) {
+            include_once($formatfile);
+        } else {
             continue;
         }
+
         $classname = "qformat_$fileformat";
-        $format_class = new $classname();
-        if ($type=='import') {
+        $formatclass = new $classname();
+        if ($type == 'import') {
             $provided = $format_class->provide_import();
-        }
-        else {
+        } else {
             $provided = $format_class->provide_export();
         }
+
         if ($provided) {
-            $formatname = get_string($fileformat, 'quiz');
-            if ($formatname == "[[$fileformat]]") {
-                $formatname = get_string($fileformat, 'qformat_'.$fileformat);
-                if ($formatname == "[[$fileformat]]") {
-                    $formatname = $fileformat;  // Just use the raw folder name
-                }
-            }
-            $fileformatnames[$fileformat] = $formatname;
+            $fileformatnames[$fileformat] = get_string($fileformat, 'qformat_'.$fileformat);
         }
     }
     natcasesort($fileformatnames);
@@ -2651,8 +1319,9 @@ function question_default_export_filename($course, $category) {
 }
 
 /**
- * @package moodlecore
- * @subpackage question
+ * Converts contextlevels to strings and back to help with reading/writing contexts
+ * to/from import/export files.
+ *
  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
@@ -2660,26 +1329,26 @@ class context_to_string_translator{
     /**
      * @var array used to translate between contextids and strings for this context.
      */
-    var $contexttostringarray = array();
+    protected $contexttostringarray = array();
 
-    function context_to_string_translator($contexts){
+    public function __construct($contexts) {
         $this->generate_context_to_string_array($contexts);
     }
 
-    function context_to_string($contextid){
+    public function context_to_string($contextid) {
         return $this->contexttostringarray[$contextid];
     }
 
-    function string_to_context($contextname){
+    public function string_to_context($contextname) {
         $contextid = array_search($contextname, $this->contexttostringarray);
         return $contextid;
     }
 
-    function generate_context_to_string_array($contexts){
+    protected function generate_context_to_string_array($contexts) {
         if (!$this->contexttostringarray){
             $catno = 1;
             foreach ($contexts as $context){
-                switch  ($context->contextlevel){
+                switch ($context->contextlevel){
                     case CONTEXT_MODULE :
                         $contextstring = 'module';
                         break;
@@ -2701,38 +1370,9 @@ class context_to_string_translator{
 
 }
 
-/**
- * @return array all the capabilities that relate to accessing particular questions.
- */
-function question_get_question_capabilities() {
-    return array(
-        'moodle/question:add',
-        'moodle/question:editmine',
-        'moodle/question:editall',
-        'moodle/question:viewmine',
-        'moodle/question:viewall',
-        'moodle/question:usemine',
-        'moodle/question:useall',
-        'moodle/question:movemine',
-        'moodle/question:moveall',
-    );
-}
-
-/**
- * @return array all the question bank capabilities.
- */
-function question_get_all_capabilities() {
-    $caps = question_get_question_capabilities();
-    $caps[] = 'moodle/question:managecategory';
-    $caps[] = 'moodle/question:flag';
-    return $caps;
-}
-
 /**
  * Check capability on category
  *
- * @global object
- * @global object
  * @param mixed $question object or id
  * @param string $cap 'add', 'edit', 'view', 'use', 'move'
  * @param integer $cachecat useful to cache all question records in a category
@@ -2741,11 +1381,6 @@ function question_get_all_capabilities() {
 function question_has_capability_on($question, $cap, $cachecat = -1){
     global $USER, $DB;
 
-    // nicolasconnault@gmail.com In some cases I get $question === false. Since no such object exists, it can't be deleted, we can safely return true
-    if ($question === false) {
-        return true;
-    }
-
     // these are capabilities on existing questions capabilties are
     //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
     $question_questioncaps = array('edit', 'view', 'use', 'move');
@@ -2820,62 +1455,32 @@ function question_get_real_state($state) {
 }
 
 /**
- * Update the flagged state of a particular question session.
- *
- * @global object
- * @param integer $sessionid question_session id.
- * @param boolean $newstate the new state for the flag.
- * @return boolean success or failure.
- */
-function question_update_flag($sessionid, $newstate) {
-    global $DB;
-    return $DB->set_field('question_sessions', 'flagged', $newstate, array('id' => $sessionid));
-}
-
-/**
- * Update the flagged state of all the questions in an attempt, where a new .
- *
- * @global object
- * @param integer $sessionid question_session id.
- * @param boolean $newstate the new state for the flag.
- * @return boolean success or failure.
+ * @param object $context a context
+ * @return string A URL for editing questions in this context.
  */
-function question_save_flags($formdata, $attemptid, $questionids) {
-    global $DB;
-    $donequestionids = array();
-    foreach ($formdata as $postvariable => $value) {
-        list($qid, $key) = question_id_and_key_from_post_name($postvariable);
-        if ($qid !== false && in_array($qid, $questionids)) {
-            if ($key == '_flagged') {
-                $DB->set_field('question_sessions', 'flagged', !empty($value),
-                        array('attemptid' => $attemptid, 'questionid' => $qid));
-                $donequestionids[$qid] = 1;
-            }
-        }
+function question_edit_url($context) {
+    global $CFG, $SITE;
+    if (!has_any_capability(question_get_question_capabilities(), $context)) {
+        return false;
     }
-    foreach ($questionids as $qid) {
-        if (!isset($donequestionids[$qid])) {
-            $DB->set_field('question_sessions', 'flagged', 0,
-                    array('attemptid' => $attemptid, 'questionid' => $qid));
-        }
+    $baseurl = $CFG->wwwroot . '/question/edit.php?';
+    $defaultcategory = question_get_default_category($context->id);
+    if ($defaultcategory) {
+        $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
     }
-}
-
-/**
- *
- * @global object
- * @param integer $attemptid the question_attempt id.
- * @param integer $questionid the question id.
- * @param integer $sessionid the question_session id.
- * @param object $user a user, or null to use $USER.
- * @return string that needs to be sent to question/toggleflag.php for it to work.
- */
-function question_get_toggleflag_checksum($attemptid, $questionid, $sessionid, $user = null) {
-    if (is_null($user)) {
-        global $USER;
-        $user = $USER;
+    switch ($context->contextlevel) {
+        case CONTEXT_SYSTEM:
+            return $baseurl . 'courseid=' . $SITE->id;
+        case CONTEXT_COURSECAT:
+            // This is nasty, becuase we can only edit questions in a course
+            // context at the moment, so for now we just return false.
+            return false;
+        case CONTEXT_COURSE:
+            return $baseurl . 'courseid=' . $context->instanceid;
+        case CONTEXT_MODULE:
+            return $baseurl . 'cmid=' . $context->instanceid;
     }
-    return md5($attemptid . "_" . $user->secret . "_" . $questionid . "_" . $sessionid);
+
 }
 
 /**
@@ -2915,6 +1520,33 @@ function question_extend_settings_navigation(navigation_node $navigationnode, $c
     return $questionnode;
 }
 
+/**
+ * @return array all the capabilities that relate to accessing particular questions.
+ */
+function question_get_question_capabilities() {
+    return array(
+        'moodle/question:add',
+        'moodle/question:editmine',
+        'moodle/question:editall',
+        'moodle/question:viewmine',
+        'moodle/question:viewall',
+        'moodle/question:usemine',
+        'moodle/question:useall',
+        'moodle/question:movemine',
+        'moodle/question:moveall',
+    );
+}
+
+/**
+ * @return array all the question bank capabilities.
+ */
+function question_get_all_capabilities() {
+    $caps = question_get_question_capabilities();
+    $caps[] = 'moodle/question:managecategory';
+    $caps[] = 'moodle/question:flag';
+    return $caps;
+}
+
 class question_edit_contexts {
 
     public static $CAPS = array(
@@ -2943,7 +1575,7 @@ class question_edit_contexts {
     /**
      * @param current context
      */
-    public function question_edit_contexts($thiscontext){
+    public function question_edit_contexts($thiscontext) {
         $pcontextids = get_parent_contexts($thiscontext);
         $contexts = array($thiscontext);
         foreach ($pcontextids as $pcontextid){
@@ -2954,20 +1586,20 @@ class question_edit_contexts {
     /**
      * @return array all parent contexts
      */
-    public function all(){
+    public function all() {
         return $this->allcontexts;
     }
     /**
      * @return object lowest context which must be either the module or course context
      */
-    public function lowest(){
+    public function lowest() {
         return $this->allcontexts[0];
     }
     /**
      * @param string $cap capability
      * @return array parent contexts having capability, zero based index
      */
-    public function having_cap($cap){
+    public function having_cap($cap) {
         $contextswithcap = array();
         foreach ($this->allcontexts as $context){
             if (has_capability($cap, $context)){
@@ -2980,7 +1612,7 @@ class question_edit_contexts {
      * @param array $caps capabilities
      * @return array parent contexts having at least one of $caps, zero based index
      */
-    public function having_one_cap($caps){
+    public function having_one_cap($caps) {
         $contextswithacap = array();
         foreach ($this->allcontexts as $context){
             foreach ($caps as $cap){
@@ -2996,7 +1628,7 @@ class question_edit_contexts {
      * @param string $tabname edit tab name
      * @return array parent contexts having at least one of $caps, zero based index
      */
-    public function having_one_edit_tab_cap($tabname){
+    public function having_one_edit_tab_cap($tabname) {
         return $this->having_one_cap(self::$CAPS[$tabname]);
     }
     /**
@@ -3005,7 +1637,7 @@ class question_edit_contexts {
      * @param string $cap capability
      * @return boolean
      */
-    public function have_cap($cap){
+    public function have_cap($cap) {
         return (count($this->having_cap($cap)));
     }
 
@@ -3015,7 +1647,7 @@ class question_edit_contexts {
      * @param array $caps capability
      * @return boolean
      */
-    public function have_one_cap($caps){
+    public function have_one_cap($caps) {
         foreach ($caps as $cap) {
             if ($this->have_cap($cap)) {
                 return true;
@@ -3023,6 +1655,7 @@ class question_edit_contexts {
         }
         return false;
     }
+
     /**
      * Has at least one parent context got one of the caps for actions on $tabname
      *
@@ -3032,6 +1665,7 @@ class question_edit_contexts {
     public function have_one_edit_tab_cap($tabname){
         return $this->have_one_cap(self::$CAPS[$tabname]);
     }
+
     /**
      * Throw error if at least one parent context hasn't got the cap $cap
      *
@@ -3042,6 +1676,7 @@ class question_edit_contexts {
             print_error('nopermissions', '', '', $cap);
         }
     }
+
     /**
      * Throw error if at least one parent context hasn't got one of the caps $caps
      *
@@ -3082,7 +1717,7 @@ class question_edit_contexts {
  * @param array $options
  * @return string
  */
-function quiz_rewrite_question_urls($text, $file, $contextid, $component, $filearea, array $ids, $itemid, array $options=null) {
+function question_rewrite_question_urls($text, $file, $contextid, $component, $filearea, array $ids, $itemid, array $options=null) {
     global $CFG;
 
     $options = (array)$options;
@@ -3198,20 +1833,18 @@ function question_pluginfile($course, $context, $component, $filearea, $args, $f
         send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
     }
 
-    $attemptid = (int)array_shift($args);
-    $questionid = (int)array_shift($args);
+    $qubaid = (int)array_shift($args);
+    $slot = (int)array_shift($args);
 
+    $module = $DB->get_field('question_usages', 'component',
+            array('id' => $qubaid));
 
-    if ($attemptid === 0) {
-        // preview
+    if ($module === 'core_question_preview') {
         require_once($CFG->dirroot . '/question/previewlib.php');
         return question_preview_question_pluginfile($course, $context,
-                $component, $filearea, $attemptid, $questionid, $args, $forcedownload);
+                $component, $filearea, $qubaid, $slot, $args, $forcedownload);
 
     } else {
-        $module = $DB->get_field('question_attempts', 'modulename',
-                array('id' => $attemptid));
-
         $dir = get_component_directory($module);
         if (!file_exists("$dir/lib.php")) {
             send_file_not_found();
@@ -3223,7 +1856,7 @@ function question_pluginfile($course, $context, $component, $filearea, $args, $f
             send_file_not_found();
         }
 
-        $filefunction($course, $context, $component, $filearea, $attemptid, $questionid,
+        $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
                 $args, $forcedownload);
 
         send_file_not_found();
@@ -3231,6 +1864,8 @@ function question_pluginfile($course, $context, $component, $filearea, $args, $f
 }
 
 /**
+ * TODO delete this. Replaced by $quba->check_file_access.
+ *
  * Final test for whether a studnet should be allowed to see a particular file.
  * This delegates the decision to the question type plugin.
  *
diff --git a/local/qedatabase/db/install.php b/local/qedatabase/db/install.php
new file mode 100755 (executable)
index 0000000..1ced515
--- /dev/null
@@ -0,0 +1,735 @@
+<?php
+
+function xmldb_local_qedatabase_install() {
+    global $DB;
+    $dbman = $DB->get_manager();
+
+    // TODO quiz default settings are now in config_plugins.
+
+    // Bit of a hack to prevent errors like "Cannot downgrade local_qedatabase from ... to ...".
+    $oldversion = 2008000000;
+    $DB->set_field('config_plugins', 'value', $oldversion,
+            array('plugin' => 'local_qedatabase', 'name' => 'version'));
+
+    // Add new preferredbehaviour column to the quiz table.
+    if ($oldversion < 2008000100) {
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('preferredbehaviour');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, null, null, null, 'timeclose');
+        if (!$dbman->field_exists($table, $field)) {
+            $dbman->add_field($table, $field);
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000100, 'local', 'qedatabase');
+    }
+
+    // Populate preferredbehaviour column based on old optionflags column.
+    if ($oldversion < 2008000101) {
+        $DB->set_field_select('quiz', 'preferredbehaviour', 'deferredfeedback',
+                'optionflags = 0');
+        $DB->set_field_select('quiz', 'preferredbehaviour', 'adaptive',
+                'optionflags <> 0 AND penaltyscheme <> 0');
+        $DB->set_field_select('quiz', 'preferredbehaviour', 'adaptivenopenalty',
+                'optionflags <> 0 AND penaltyscheme = 0');
+
+        set_config('quiz_preferredbehaviour', 'deferredfeedback');
+        set_config('quiz_fix_preferredbehaviour', 0);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000101, 'local', 'qedatabase');
+    }
+
+    // Add a not-NULL constraint to the preferredmodel field now that it is populated.
+    if ($oldversion < 2008000102) {
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('preferredbehaviour');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'timeclose');
+
+        $dbman->change_field_notnull($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000102, 'local', 'qedatabase');
+    }
+
+    // Drop the old optionflags field.
+    if ($oldversion < 2008000103) {
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('optionflags');
+        $dbman->drop_field($table, $field);
+
+        unset_config('quiz_optionflags');
+        unset_config('quiz_fix_optionflags');
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000103, 'local', 'qedatabase');
+    }
+
+    // Drop the old penaltyscheme field.
+    if ($oldversion < 2008000104) {
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('penaltyscheme');
+        $dbman->drop_field($table, $field);
+
+        unset_config('quiz_penaltyscheme');
+        unset_config('quiz_fix_penaltyscheme');
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000104, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000110) {
+
+        // Changing nullability of field sumgrades on table quiz_attempts to null
+        $table = new xmldb_table('quiz_attempts');
+        $field = new xmldb_field('sumgrades');
+        $field->set_attributes(XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, 'attempt');
+
+        // Launch change of nullability for field sumgrades
+        $dbman->change_field_notnull($table, $field);
+
+        // Launch change of default for field sumgrades
+        $dbman->change_field_default($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000110, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000111) {
+
+        // Changing the default of field penalty on table question to 0.3333333
+        $table = new xmldb_table('question');
+        $field = new xmldb_field('penalty');
+        $field->set_attributes(XMLDB_TYPE_FLOAT, null, null, XMLDB_NOTNULL, null, '0.3333333', 'defaultgrade');
+
+        // Launch change of default for field penalty
+        $dbman->change_field_default($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000111, 'local', 'qedatabase');
+    }
+
+// Update the quiz from the old single review column to seven new columns.
+
+    if ($oldversion < 2008000200) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewattempt');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'review');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000200, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000201) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewcorrectness');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewattempt');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000201, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000202) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewmarks');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewcorrectness');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000202, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000203) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewspecificfeedback');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewmarks');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000203, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000204) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewgeneralfeedback');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewspecificfeedback');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000204, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000205) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewrightanswer');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewgeneralfeedback');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000205, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000206) {
+
+        // Define field reviewattempt to be added to quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('reviewoverallfeedback');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewrightanswer');
+
+        // Launch add field reviewattempt
+        $dbman->add_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000206, 'local', 'qedatabase');
+    }
+
+    define('QUIZ_NEW_DURING',            0x10000);
+    define('QUIZ_NEW_IMMEDIATELY_AFTER', 0x01000);
+    define('QUIZ_NEW_LATER_WHILE_OPEN',  0x00100);
+    define('QUIZ_NEW_AFTER_CLOSE',       0x00010);
+
+    define('QUIZ_OLD_IMMEDIATELY', 0x3c003f);
+    define('QUIZ_OLD_OPEN',        0x3c00fc0);
+    define('QUIZ_OLD_CLOSED',      0x3c03f000);
+
+    define('QUIZ_OLD_RESPONSES',       1*0x1041); // Show responses
+    define('QUIZ_OLD_SCORES',          2*0x1041); // Show scores
+    define('QUIZ_OLD_FEEDBACK',        4*0x1041); // Show question feedback
+    define('QUIZ_OLD_ANSWERS',         8*0x1041); // Show correct answers
+    define('QUIZ_OLD_SOLUTIONS',      16*0x1041); // Show solutions
+    define('QUIZ_OLD_GENERALFEEDBACK',32*0x1041); // Show question general feedback
+    define('QUIZ_OLD_OVERALLFEEDBACK', 1*0x4440000); // Show quiz overall feedback
+
+    // Copy the old review settings
+    if ($oldversion < 2008000210) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewattempt = " . $DB->sql_bitor($DB->sql_bitor(
+                    QUIZ_NEW_DURING,
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_RESPONSES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_RESPONSES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_RESPONSES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000210, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000211) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewcorrectness = " . $DB->sql_bitor($DB->sql_bitor(
+                    QUIZ_NEW_DURING,
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000211, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000212) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewmarks = " . $DB->sql_bitor($DB->sql_bitor(
+                    QUIZ_NEW_DURING,
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000212, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000213) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewspecificfeedback = " . $DB->sql_bitor($DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_FEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_FEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000213, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000214) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewgeneralfeedback = " . $DB->sql_bitor($DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_GENERALFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_GENERALFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000214, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000215) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewrightanswer = " . $DB->sql_bitor($DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS) .
+                        ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_ANSWERS) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_ANSWERS) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000215, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000216) {
+        $DB->execute("
+            UPDATE {quiz}
+            SET reviewoverallfeedback = " . $DB->sql_bitor($DB->sql_bitor(
+                    0,
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_OVERALLFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor(
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_OVERALLFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END',
+                    'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_OVERALLFEEDBACK) .
+                        ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . "
+        ");
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000216, 'local', 'qedatabase');
+    }
+
+    // And, do the same for the defaults
+    if ($oldversion < 2008000217) {
+        if (empty($CFG->quiz_review)) {
+            $CFG->quiz_review = 0;
+        }
+
+        set_config('quiz_reviewattempt',
+                QUIZ_NEW_DURING |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_RESPONSES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_RESPONSES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_RESPONSES ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewcorrectness',
+                QUIZ_NEW_DURING |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_SCORES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewmarks',
+                QUIZ_NEW_DURING |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_SCORES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewspecificfeedback',
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_DURING : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewgeneralfeedback',
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_DURING : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewrightanswer',
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS ? QUIZ_NEW_DURING : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_ANSWERS ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_ANSWERS ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        set_config('quiz_reviewoverallfeedback',
+                0 |
+                ($CFG->quiz_review & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_OPEN & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) |
+                ($CFG->quiz_review & QUIZ_OLD_CLOSED & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0));
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000217, 'local', 'qedatabase');
+    }
+
+    // Finally drop the old column
+    if ($oldversion < 2008000220) {
+        // Define field review to be dropped from quiz
+        $table = new xmldb_table('quiz');
+        $field = new xmldb_field('review');
+
+        // Launch drop field review
+        $dbman->drop_field($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000220, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000221) {
+        unset_config('quiz_review');
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000221, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000501) {
+
+        // Rename field defaultgrade on table question to defaultmark
+        $table = new xmldb_table('question');
+        $field = new xmldb_field('defaultgrade');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', 'generalfeedback');
+
+        // Launch rename field defaultmark
+        $dbman->rename_field($table, $field, 'defaultmark');
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000501, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000505) {
+
+        // Rename the question_attempts table to question_usages.
+        $table = new xmldb_table('question_attempts');
+        if ($dbman->table_exists($table)) {
+            $dbman->rename_table($table, 'question_usages');
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000505, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000507) {
+
+        // Rename the modulename field to component ...
+        $table = new xmldb_table('question_usages');
+        $field = new xmldb_field('modulename');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'contextid');
+        $dbman->rename_field($table, $field, 'component');
+
+        // ... and update its contents.
+        $DB->set_field('question_usages', 'component', 'mod_quiz', array('component' => 'quiz'));
+
+        // Add the contextid field.
+        $field = new xmldb_field('contextid');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'id');
+        $dbman->add_field($table, $field);
+
+        // And populate it.
+        $quizmoduleid = $DB->get_field('modules', 'id', array('name' => 'quiz'));
+        $DB->execute("
+            UPDATE {question_usages} SET contextid = (
+                SELECT ctx.id
+                FROM {context} ctx
+                JOIN {course_modules} cm ON cm.id = ctx.instanceid AND cm.module = $quizmoduleid
+                JOIN {quiz_attempts} quiza ON quiza.quiz = cm.instance
+                WHERE ctx.contextlevel = " . CONTEXT_MODULE . "
+                AND quiza.uniqueid = {question_usages}.id
+            )
+        ");
+
+        // Then make it NOT NULL.
+        $field = new xmldb_field('contextid');
+        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, 'id');
+        $dbman->change_field_notnull($table, $field);
+
+        // Add the preferredbehaviour column. Populate it with a dummy value
+        // for now. We will fill in the appropriate behaviour name when
+        // updating all the rest of the attempt data.
+        $field = new xmldb_field('preferredbehaviour');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, null, null, null, null, 'to_be_set_later', 'component');
+        $dbman->add_field($table, $field);
+
+        // Then remove the default value, now the column is populated.
+        $field = new xmldb_field('preferredbehaviour');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'component');
+        $dbman->change_field_default($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000507, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000513) {
+
+        // Define key contextid (foreign) to be added to question_usages
+        $table = new xmldb_table('question_usages');
+        $key = new XMLDBKey('contextid');
+        $key->set_attributes(XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
+
+        // Launch add key contextid
+        $dbman->add_key($table, $key);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000513, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000514) {
+
+        // Changing precision of field component on table question_usages to (255)
+        // This was missed during the upgrade from old versions.
+        $table = new xmldb_table('question_usages');
+        $field = new xmldb_field('component');
+        $field->set_attributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'contextid');
+
+        // Launch change of precision for field component
+        $dbman->change_field_precision($table, $field);
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000514, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000520) {
+
+        // Define table question_attempts to be created
+        $table = new xmldb_table('question_attempts');
+        if (!$dbman->table_exists($table)) {
+
+            // Adding fields to table question_attempts
+            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+            $table->add_field('questionusageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('slot', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('behaviour', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null);
+            $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('maxmark', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, null);
+            $table->add_field('minfraction', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, null);
+            $table->add_field('flagged', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
+            $table->add_field('questionsummary', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
+            $table->add_field('rightanswer', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
+            $table->add_field('responsesummary', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
+            $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+
+            // Adding keys to table question_attempts
+            $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+            $table->add_key('questionid', XMLDB_KEY_FOREIGN, array('questionid'), 'question', array('id'));
+            $table->add_key('questionusageid', XMLDB_KEY_FOREIGN, array('questionusageid'), 'question_usages', array('id'));
+
+            // Adding indexes to table question_attempts
+            $table->add_index('questionusageid-slot', XMLDB_INDEX_UNIQUE, array('questionusageid', 'slot'));
+
+            // Launch create table for question_attempts
+            $dbman->create_table($table);
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000520, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000521) {
+
+        // Define table question_attempt_steps to be created
+        $table = new xmldb_table('question_attempt_steps');
+        if (!$dbman->table_exists($table)) {
+
+            // Adding fields to table question_attempt_steps
+            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+            $table->add_field('questionattemptid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('sequencenumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('state', XMLDB_TYPE_CHAR, '13', null, XMLDB_NOTNULL, null, null);
+            $table->add_field('fraction', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
+            $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
+
+            // Adding keys to table question_attempt_steps
+            $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+            $table->add_key('questionattemptid', XMLDB_KEY_FOREIGN, array('questionattemptid'), 'question_attempts_new', array('id'));
+            $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
+
+            // Adding indexes to table question_attempt_steps
+            $table->add_index('questionattemptid-sequencenumber', XMLDB_INDEX_UNIQUE, array('questionattemptid', 'sequencenumber'));
+
+            // Launch create table for question_attempt_steps
+            $dbman->create_table($table);
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000521, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000522) {
+
+        // Define table question_attempt_step_data to be created
+        $table = new xmldb_table('question_attempt_step_data');
+        if (!$dbman->table_exists($table)) {
+
+            // Adding fields to table question_attempt_step_data
+            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+            $table->add_field('attemptstepid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+            $table->add_field('name', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null);
+            $table->add_field('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
+
+            // Adding keys to table question_attempt_step_data
+            $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+            $table->add_key('attemptstepid', XMLDB_KEY_FOREIGN, array('attemptstepid'), 'question_attempt_steps', array('id'));
+
+            // Adding indexes to table question_attempt_step_data
+            $table->add_index('attemptstepid-name', XMLDB_INDEX_UNIQUE, array('attemptstepid', 'name'));
+
+            // Launch create table for question_attempt_step_data
+            $dbman->create_table($table);
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000522, 'local', 'qedatabase');
+    }
+
+//    if ($oldversion < 2008000550) {
+//        // Define field needsupgradetonewqe to be added to quiz_attempts
+//        $table = new xmldb_table('quiz_attempts');
+//        $field = new xmldb_field('needsupgradetonewqe');
+//        $field->set_attributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'preview');
+//
+//        // Launch add field needsupgradetonewqe
+//        if (!field_exists($table, $field)) {
+//            $dbman->add_field($table, $field);
+//        }
+//
+//        set_field_select('quiz_attempts', 'needsupgradetonewqe', 1, '', '');
+//
+//        // quiz savepoint reached
+//        upgrade_plugin_savepoint(true, 2008000550, 'local', 'qedatabase');
+//    }
+
+//    if ($oldversion < 2008000551) {
+//        $table = new xmldb_table('question_states');
+//        if ($dbman->table_exists($table)) {
+//            // First delete all data from preview attempts.
+//            delete_records_select('question_states',
+//                    "attempt IN (SELECT uniqueid FROM {quiz_attempts} WHERE preview = 1)");
+//            delete_records_select('question_sessions',
+//                    "attemptid IN (SELECT uniqueid FROM {quiz_attempts} WHERE preview = 1)");
+//            delete_records('quiz_attempts', 'preview', 1);
+//
+//            // Now update all the old attempt data.
+//            $db->debug = false;
+//            $oldrcachesetting = $CFG->rcache;
+//            $CFG->rcache = false;
+//
+//            require_once($CFG->dirroot . '/question/engine/upgradefromoldqe/upgrade.php');
+//            $upgrader = new question_engine_attempt_upgrader();
+//            $upgrader->convert_all_quiz_attempts();
+//
+//            $CFG->rcache = $oldrcachesetting;
+//            $db->debug = true;
+//        }
+//
+//        // quiz savepoint reached
+//        upgrade_plugin_savepoint(true, 2008000551, 'local', 'qedatabase');
+//    }
+
+    if ($oldversion < 2008000600) {
+
+        // Define table question_hints to be created
+        $table = new xmldb_table('question_hints');
+
+        // Adding fields to table question_hints
+        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+        $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+        $table->add_field('hint', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null);
+        $table->add_field('hintformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
+        $table->add_field('shownumcorrect', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null);
+        $table->add_field('clearwrong', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null);
+        $table->add_field('options', XMLDB_TYPE_CHAR, '255', null, null, null, null);
+
+        // Adding keys to table question_hints
+        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+        $table->add_key('questionid', XMLDB_KEY_FOREIGN, array('questionid'), 'question', array('id'));
+
+        // Conditionally launch create table for question_hints
+        if (!$dbman->table_exists($table)) {
+            $dbman->create_table($table);
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000600, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000601) {
+
+        // In the past, question_answer fractions were stored with rather
+        // sloppy rounding. Now update them to the new standard of 7 d.p.
+        $changes = array(
+            '-0.66666'  => '-0.6666667',
+            '-0.33333'  => '-0.3333333',
+            '-0.16666'  => '-0.1666667',
+            '-0.142857' => '-0.1428571',
+             '0.11111'  =>  '0.1111111',
+             '0.142857' =>  '0.1428571',
+             '0.16666'  =>  '0.1666667',
+             '0.33333'  =>  '0.3333333',
+             '0.333333' =>  '0.3333333',
+             '0.66666'  =>  '0.6666667',
+        );
+        foreach ($changes as $from => $to) {
+            $DB->set_field('question_answers',
+                    'fraction', $to, array('fraction' => $from));
+        }
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000601, 'local', 'qedatabase');
+    }
+
+    if ($oldversion < 2008000602) {
+
+        // In the past, question penalties were stored with rather
+        // sloppy rounding. Now update them to the new standard of 7 d.p.
+        $DB->set_field('question',
+                'penalty', 0.3333333, array('penalty' => 33.3));
+        $DB->set_field_select('question',
+                'penalty', 0.3333333, 'penalty >= 0.33 AND penalty <= 0.34');
+        $DB->set_field_select('question',
+                'penalty', 0.6666667, 'penalty >= 0.66 AND penalty <= 0.67');
+        $DB->set_field_select('question',
+                'penalty', 1, 'penalty > 1');
+
+        // quiz savepoint reached
+        upgrade_plugin_savepoint(true, 2008000602, 'local', 'qedatabase');
+    }
+}
diff --git a/local/qedatabase/db/upgrade.php b/local/qedatabase/db/upgrade.php
new file mode 100755 (executable)
index 0000000..1bfac5d
--- /dev/null
@@ -0,0 +1,21 @@
+<?php
+
+function xmldb_local_qedatabase_upgrade($oldversion) {
+    global $CFG, $DB, $QTYPES;
+
+    $dbman = $DB->get_manager();
+
+    if ($oldversion < 2008000700) {
+
+        // Define field hintformat to be added to question_hints table.
+        $table = new xmldb_table('question_hints');
+        $field = new xmldb_field('hintformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
+
+        // Conditionally launch add field partiallycorrectfeedbackformat
+        if (!$dbman->field_exists($table, $field)) {
+            $dbman->add_field($table, $field);
+        }
+
+        upgrade_plugin_savepoint(true, 2008000700, 'local', 'qedatabase');
+    }
+}
diff --git a/local/qedatabase/readme.txt b/local/qedatabase/readme.txt
new file mode 100755 (executable)
index 0000000..d77cb90
--- /dev/null
@@ -0,0 +1,2 @@
+This local plugin exists simply to create and update the database as required
+by the new Question Engine.
diff --git a/local/qedatabase/version.php b/local/qedatabase/version.php
new file mode 100755 (executable)
index 0000000..10ccc93
--- /dev/null
@@ -0,0 +1,30 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Question engine database upgrade version information
+ *
+ * @package    moodlecore
+ * @subpackage questionengine
+ * @copyright  2010 The Open University
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die;
+
+$plugin->version  = 2008000700;
+$plugin->requires = 2010080300;
old mode 100755 (executable)
new mode 100644 (file)
index e085c18..59dac0b 100644 (file)
@@ -175,6 +175,7 @@ function quiz_load_attempt($attemptid) {
         return false;
     }
 
+    // TODO kill this.
     if (!$DB->record_exists('question_sessions', array('attemptid' => $attempt->uniqueid))) {
     /// this attempt has not yet been upgraded to the new model
         quiz_upgrade_states($attempt);
old mode 100755 (executable)
new mode 100644 (file)
index 0d6795d..8fe4976 100644 (file)
@@ -85,7 +85,7 @@ function xmldb_quiz_statistics_upgrade($oldversion) {
         $table->add_field('anssubqid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
         $table->add_field('response', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
         $table->add_field('rcount', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
-        $table->add_field('credit', XMLDB_TYPE_NUMBER, '15, 5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+        $table->add_field('credit', XMLDB_TYPE_NUMBER, '15, 5', null, XMLDB_NOTNULL, null, null);
 
     /// Adding keys to table quiz_question_response_stats
         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
diff --git a/question/behaviour/adaptive/behaviour.php b/question/behaviour/adaptive/behaviour.php
new file mode 100644 (file)
index 0000000..9f7db58
--- /dev/null
@@ -0,0 +1,178 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour for the old adaptive mode.
+ *
+ * @package qbehaviour_adaptive
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+/**
+ * Question behaviour for adaptive mode.
+ *
+ * This is the old version of interactive mode.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_adaptive extends question_behaviour_with_save {
+    const IS_ARCHETYPAL = true;
+
+    public function required_question_definition_type() {
+        return 'question_automatically_gradable';
+    }
+
+    public function get_expected_data() {
+        if ($this->qa->get_state()->is_active()) {
+            return array('submit' => PARAM_BOOL);
+        }
+        return parent::get_expected_data();
+    }
+
+    public function get_right_answer_summary() {
+        return $this->question->get_right_answer_summary();
+    }
+
+    public function adjust_display_options(question_display_options $options) {
+        parent::adjust_display_options($options);
+        if (!$this->qa->get_state()->is_finished() &&
+                $this->qa->get_last_behaviour_var('_try')) {
+            $options->feedback = true;
+        }
+    }
+
+    public function get_state_string($showcorrectness) {
+        $state = $this->qa->get_state();
+
+        $laststep = $this->qa->get_last_step();
+        if ($laststep->has_behaviour_var('_try')) {
+            $state = question_state::graded_state_for_fraction(
+                    $laststep->get_behaviour_var('_rawfraction'));
+        }
+
+        return $state->default_string($showcorrectness);
+    }
+
+    public function process_action(question_attempt_pending_step $pendingstep) {
+        if ($pendingstep->has_behaviour_var('comment')) {
+            return $this->process_comment($pendingstep);
+        } else if ($pendingstep->has_behaviour_var('finish')) {
+            return $this->process_finish($pendingstep);
+        } else if ($pendingstep->has_behaviour_var('submit')) {
+            return $this->process_submit($pendingstep);
+        } else {
+            return $this->process_save($pendingstep);
+        }
+    }
+
+    public function summarise_action(question_attempt_step $step) {
+        if ($step->has_behaviour_var('comment')) {
+            return $this->summarise_manual_comment($step);
+        } else if ($step->has_behaviour_var('finish')) {
+            return $this->summarise_finish($step);
+        } else if ($step->has_behaviour_var('submit')) {
+            return $this->summarise_submit($step);
+        } else {
+            return $this->summarise_save($step);
+        }
+    }
+
+    public function process_save(question_attempt_pending_step $pendingstep) {
+        $status = parent::process_save($pendingstep);
+        $prevgrade = $this->qa->get_fraction();
+        if (!is_null($prevgrade)) {
+            $pendingstep->set_fraction($prevgrade);
+        }
+        $pendingstep->set_state(question_state::$todo);
+        return $status;
+    }
+
+    protected function adjusted_fraction($fraction, $prevtries) {
+        return $fraction - $this->question->penalty * $prevtries;
+    }
+
+    public function process_submit(question_attempt_pending_step $pendingstep) {
+        $status = $this->process_save($pendingstep);
+
+        $response = $pendingstep->get_qt_data();
+        if (!$this->question->is_gradable_response($response)) {
+            $pendingstep->set_state(question_state::$invalid);
+            if ($this->qa->get_state() != question_state::$invalid) {
+                $status = question_attempt::KEEP;
+            }
+            return $status;
+        }
+
+        $prevtries = $this->qa->get_last_behaviour_var('_try', 0);
+        $prevbest = $pendingstep->get_fraction();
+        if (is_null($prevbest)) {
+            $prevbest = 0;
+        }
+
+        list($fraction, $state) = $this->question->grade_response($response);
+
+        $pendingstep->set_fraction(max($prevbest, $this->adjusted_fraction($fraction, $prevtries)));
+        if ($state == question_state::$gradedright) {
+            $pendingstep->set_state(question_state::$complete);
+        } else {
+            $pendingstep->set_state(question_state::$todo);
+        }
+        $pendingstep->set_behaviour_var('_try', $prevtries + 1);
+        $pendingstep->set_behaviour_var('_rawfraction', $fraction);
+        $pendingstep->set_new_response_summary($this->question->summarise_response($response));
+
+        return question_attempt::KEEP;
+    }
+
+    public function process_finish(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        $laststep = $this->qa->get_last_step();
+        $response = $laststep->get_qt_data();
+        if (!$this->question->is_gradable_response($response)) {
+            $pendingstep->set_state(question_state::$gaveup);
+            return question_attempt::KEEP;
+        }
+
+        $prevtries = $this->qa->get_last_behaviour_var('_try', 0);
+        $prevbest = $pendingstep->get_fraction();
+        if (is_null($prevbest)) {
+            $prevbest = 0;
+        }
+
+        if ($laststep->has_behaviour_var('_try')) {
+            // Last answer was graded, we want to regrade it. Otherwise the answer
+            // has changed, and we are grading a new try.
+            $prevtries -= 1;
+        }
+
+        list($fraction, $state) = $this->question->grade_response($response);
+
+        $pendingstep->set_fraction(max($prevbest, $this->adjusted_fraction($fraction, $prevtries)));
+        $pendingstep->set_state($state);
+        $pendingstep->set_behaviour_var('_try', $prevtries + 1);
+        $pendingstep->set_behaviour_var('_rawfraction', $fraction);
+        $pendingstep->set_new_response_summary($this->question->summarise_response($response));
+        return question_attempt::KEEP;
+    }
+}
diff --git a/question/behaviour/adaptive/lang/en/qbehaviour_adaptive.php b/question/behaviour/adaptive/lang/en/qbehaviour_adaptive.php
new file mode 100644 (file)
index 0000000..c96fc12
--- /dev/null
@@ -0,0 +1,6 @@
+<?php
+
+$string['adaptive'] = 'Adaptive mode';
+$string['gradingdetails'] = 'Marks for this submission: {$a->raw}/{$a->max}.';
+$string['gradingdetailsadjustment'] = 'With previous penalties this gives <strong>{$a->cur}/{$a->max}</strong>.';
+$string['gradingdetailspenalty'] = 'This submission attracted a penalty of {$a}.';
diff --git a/question/behaviour/adaptive/renderer.php b/question/behaviour/adaptive/renderer.php
new file mode 100644 (file)
index 0000000..7393d63
--- /dev/null
@@ -0,0 +1,98 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the legacy
+ * adaptive behaviour.
+ *
+ * @package qbehaviour_adaptive
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+class qbehaviour_adaptive_renderer extends qbehaviour_renderer {
+    protected function get_graded_step(question_attempt $qa) {
+        foreach ($qa->get_reverse_step_iterator() as $step) {
+            if ($step->has_behaviour_var('_try')) {
+                return $step;
+            }
+        }
+    }
+
+    public function controls(question_attempt $qa, question_display_options $options) {
+        return $this->submit_button($qa, $options);
+    }
+
+    public function feedback(question_attempt $qa, question_display_options $options) {
+        // Try to find the last graded step.
+
+        $gradedstep = $this->get_graded_step($qa);
+        if (is_null($gradedstep) || $qa->get_max_mark() == 0 || !$options->marks) {
+            return '';
+        }
+
+        // Display the grading details from the last graded state
+        $mark = new stdClass;
+        $mark->max = $qa->format_max_mark($options->markdp);
+
+        $actualmark = $gradedstep->get_fraction() * $qa->get_max_mark();
+        $mark->cur = format_float($actualmark, $options->markdp);
+
+        $rawmark = $gradedstep->get_behaviour_var('_rawfraction') * $qa->get_max_mark();
+        $mark->raw = format_float($rawmark, $options->markdp);
+
+        // let student know wether the answer was correct
+        if ($qa->get_state()->is_commented()) {
+            $class = $qa->get_state()->get_feedback_class();
+        } else {
+            $class = question_state::graded_state_for_fraction(
+                    $gradedstep->get_behaviour_var('_rawfraction'))->get_feedback_class();
+        }
+
+        $gradingdetails = get_string('gradingdetails', 'qbehaviour_adaptive', $mark);
+
+        $gradingdetails .= $this->penalty_info($qa, $mark);
+
+        $output = '';
+        $output .= html_writer::tag('div', get_string($class, 'question'),
+                array('class' => 'correctness ' . $class));
+        $output .= html_writer::tag('div', $gradingdetails,
+                array('class' => 'gradingdetails'));
+        return $output;
+    }
+
+    protected function penalty_info($qa, $mark) {
+        if (!$qa->get_question()->penalty) {
+            return '';
+        }
+        $output = '';
+
+        // print details of grade adjustment due to penalties
+        if ($mark->raw != $mark->cur) {
+            $output .= ' ' . get_string('gradingdetailsadjustment', 'qbehaviour_adaptive', $mark);
+        }
+
+        // print info about new penalty
+        // penalty is relevant only if the answer is not correct and further attempts are possible
+        if (!$qa->get_state()->is_finished()) {
+            $output .= ' ' . get_string('gradingdetailspenalty', 'qbehaviour_adaptive', $qa->get_question()->penalty);
+        }
+
+        return $output;
+    }
+}
diff --git a/question/behaviour/adaptive/simpletest/testwalkthrough.php b/question/behaviour/adaptive/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..c097f3d
--- /dev/null
@@ -0,0 +1,239 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the adaptive
+ * behaviour.
+ *
+ * @package qbehaviour_adaptive
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_adaptive_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_adaptive_multichoice() {
+
+        // Create a multiple choice, single response question.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $mc->penalty = 0.3333333;
+        $this->start_attempt_at_question($mc, 'adaptive', 3);
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process a submit.
+        $this->process_submission(array('answer' => $wrongindex, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(0);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0),
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 2) % 3, true, false),
+                $this->get_contains_incorrect_expectation());
+        $this->assertPattern('/B|C/',
+                $this->quba->get_response_summary($this->slot));
+
+        // Process a change of answer to the right one, but not sumbitted.
+        $this->process_submission(array('answer' => $rightindex));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(0);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0),
+                $this->get_contains_mc_radio_expectation($rightindex, true, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, true, false));
+        $this->assertPattern('/B|C/',
+                $this->quba->get_response_summary($this->slot));
+
+        // Now submit the right answer.
+        $this->process_submission(array('answer' => $rightindex, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(3 * (1 - $mc->penalty));
+        $this->check_current_output(
+                $this->get_contains_mark_summary(3 * (1 - $mc->penalty)),
+                $this->get_contains_mc_radio_expectation($rightindex, true, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, true, false),
+                $this->get_contains_correct_expectation());
+        $this->assertEqual('A',
+                $this->quba->get_response_summary($this->slot));
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(3 * (1 - $mc->penalty));
+        $this->check_current_output(
+                $this->get_contains_mark_summary(3 * (1 - $mc->penalty)),
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, false, false),
+                $this->get_contains_correct_expectation());
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 1);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(1),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $mc->answers[13]->fraction = -0.33333333;
+        $mc->answers[15]->fraction = 1;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(1),
+                $this->get_contains_partcorrect_expectation());
+
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), 0, 0.0000001);
+    }
+
+    public function test_adaptive_multichoice2() {
+
+        // Create a multiple choice, multiple response question.
+        $mc = test_question_maker::make_a_multichoice_multi_question();
+        $mc->penalty = 0.3333333;
+        $mc->shuffleanswers = 0;
+        $this->start_attempt_at_question($mc, 'adaptive', 2);
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process a submit.
+        $this->process_submission(array('choice0' => 1, 'choice2' => 1, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(2);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(2),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_contains_correct_expectation());
+
+        // Save the same correct answer again. Should no do anything.
+        $numsteps = $this->get_step_count();
+        $this->process_submission(array('choice0' => 1, 'choice2' => 1));
+
+        // Verify.
+        $this->check_step_count($numsteps);
+        $this->check_current_state(question_state::$complete);
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_step_count($numsteps + 1);
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(2),
+                $this->get_contains_submit_button_expectation(false),
+                $this->get_contains_correct_expectation());
+    }
+
+    public function test_adaptive_shortanswer_try_to_submit_blank() {
+
+        // Create a short answer question with correct answer true.
+        $sa = test_question_maker::make_a_shortanswer_question();
+        $this->start_attempt_at_question($sa, 'adaptive');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit with blank answer.
+        $this->process_submission(array('-submit' => 1, 'answer' => ''));
+
+        // Verify.
+        $this->check_current_state(question_state::$invalid);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_validation_error_expectation());
+        $this->assertNull($this->quba->get_response_summary($this->slot));
+
+        // Now get it wrong.
+        $this->process_submission(array('-submit' => 1, 'answer' => 'toad'));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(0.8);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0.8),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_contains_partcorrect_expectation(),
+                $this->get_does_not_contain_validation_error_expectation());
+
+
+        // Now submit blank again.
+        $this->process_submission(array('-submit' => 1, 'answer' => ''));
+
+        // Verify.
+        $this->check_current_state(question_state::$invalid);
+        $this->check_current_mark(0.8);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0.8),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_contains_partcorrect_expectation(),
+                $this->get_contains_validation_error_expectation());
+    }
+}
diff --git a/question/behaviour/adaptivenopenalty/behaviour.php b/question/behaviour/adaptivenopenalty/behaviour.php
new file mode 100644 (file)
index 0000000..9a6dee2
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour for the old adaptive mode, with no penalties.
+ *
+ * @package qbehaviour_adaptivenopenalty
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require_once(dirname(__FILE__) . '/../adaptive/behaviour.php');
+
+/**
+ * Question behaviour for adaptive mode, with no penalties.
+ *
+ * This is the old version of interactive mode, without penalties.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_adaptivenopenalty extends qbehaviour_adaptive {
+    const IS_ARCHETYPAL = true;
+
+    protected function adjusted_fraction($fraction, $prevtries) {
+        return $fraction;
+    }
+}
diff --git a/question/behaviour/adaptivenopenalty/lang/en/qbehaviour_adaptivenopenalty.php b/question/behaviour/adaptivenopenalty/lang/en/qbehaviour_adaptivenopenalty.php
new file mode 100644 (file)
index 0000000..a785810
--- /dev/null
@@ -0,0 +1,3 @@
+<?php
+
+$string['adaptivenopenalty'] = 'Adaptive mode (no penalties)';
diff --git a/question/behaviour/adaptivenopenalty/renderer.php b/question/behaviour/adaptivenopenalty/renderer.php
new file mode 100644 (file)
index 0000000..cd02a10
--- /dev/null
@@ -0,0 +1,34 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the legacy
+ * adaptive (no penalties) behaviour.
+ *
+ * @package qbehaviour_adaptivenopenalty
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require_once(dirname(__FILE__) . '/../adaptive/renderer.php');
+
+class qbehaviour_adaptivenopenalty_renderer extends qbehaviour_adaptive_renderer {
+    protected function penalty_info($qa, $mark) {
+        return '';
+    }
+}
diff --git a/question/behaviour/adaptivenopenalty/simpletest/testwalkthrough.php b/question/behaviour/adaptivenopenalty/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..fe9cdef
--- /dev/null
@@ -0,0 +1,186 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the adaptive (no penalties)k
+ * behaviour.
+ *
+ * @package qbehaviour_adaptivenopenalty
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_adaptivenopenalty_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_multichoice() {
+
+        // Create a multiple choice, single response question.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $mc->penalty = 0.3333333;
+        $this->start_attempt_at_question($mc, 'adaptivenopenalty', 3);
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process a submit.
+        $this->process_submission(array('answer' => $wrongindex, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(0);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0),
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 2) % 3, true, false),
+                $this->get_contains_incorrect_expectation());
+        $this->assertPattern('/B|C/',
+                $this->quba->get_response_summary($this->slot));
+
+        // Process a change of answer to the right one, but not sumbitted.
+        $this->process_submission(array('answer' => $rightindex));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(0);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(0),
+                $this->get_contains_mc_radio_expectation($rightindex, true, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, true, false));
+        $this->assertPattern('/B|C/',
+                $this->quba->get_response_summary($this->slot));
+
+        // Now submit the right answer.
+        $this->process_submission(array('answer' => $rightindex, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(3);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(3),
+                $this->get_contains_mc_radio_expectation($rightindex, true, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, true, false),
+                $this->get_contains_correct_expectation());
+        $this->assertEqual('A',
+                $this->quba->get_response_summary($this->slot));
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(3);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(3),
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 2) % 3, false, false),
+                $this->get_contains_correct_expectation());
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 1);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(1),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $mc->answers[13]->fraction = -0.33333333;
+        $mc->answers[15]->fraction = 1;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(1),
+                $this->get_contains_partcorrect_expectation());
+
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), 0, 0.0000001);
+    }
+
+    public function test_multichoice2() {
+
+        // Create a multiple choice, multiple response question.
+        $mc = test_question_maker::make_a_multichoice_multi_question();
+        $mc->penalty = 0.3333333;
+        $mc->shuffleanswers = 0;
+        $this->start_attempt_at_question($mc, 'adaptivenopenalty', 2);
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_marked_out_of_summary(),
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process a submit.
+        $this->process_submission(array('choice0' => 1, 'choice2' => 1, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(2);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(2),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_contains_correct_expectation());
+
+        // Save the same correct answer again. Should no do anything.
+        $numsteps = $this->get_step_count();
+        $this->process_submission(array('choice0' => 1, 'choice2' => 1));
+
+        // Verify.
+        $this->check_step_count($numsteps);
+        $this->check_current_state(question_state::$complete);
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_step_count($numsteps + 1);
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2);
+        $this->check_current_output(
+                $this->get_contains_mark_summary(2),
+                $this->get_contains_submit_button_expectation(false),
+                $this->get_contains_correct_expectation());
+    }
+}
diff --git a/question/behaviour/behaviourbase.php b/question/behaviour/behaviourbase.php
new file mode 100644 (file)
index 0000000..46add1d
--- /dev/null
@@ -0,0 +1,647 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Defines the quetsion behaviour base class
+ *
+ * @package moodlecore
+ * @subpackage questionbehaviours
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+/**
+ * The base class for question behaviours.
+ *
+ * A question behaviour is used by the question engine, specifically by
+ * a {@link question_attempt} to manage the flow of actions a student can take
+ * as they work through a question, and later, as a teacher manually grades it.
+ * In turn, the behaviour will delegate certain processing to the
+ * relevant {@link question_definition}.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+abstract class question_behaviour {
+    /**
+     * Certain behaviours are definitive of a  way that questions can
+     * behave when attempted. For example deferredfeedback model, interactive
+     * model, etc. These are the options that should be listed in the
+     * user-interface. These models should define the class constant
+     * IS_ARCHETYPAL as true. Other models are more implementation details, for
+     * example the informationitem model, or a special subclass like
+     * interactive_adapted_for_my_qtype. These models should IS_ARCHETYPAL as
+     * false.
+     * @var boolean
+     */
+    const IS_ARCHETYPAL = false;
+
+    /** @var question_attempt the question attempt we are managing. */
+    protected $qa;
+    /** @var question_definition shortcut to $qa->get_question(). */
+    protected $question;
+
+    /**
+     * Normally you should not call this constuctor directly. The appropriate
+     * behaviour object is created automatically as part of
+     * {@link question_attempt::start()}.
+     * @param question_attempt $qa the question attempt we will be managing.
+     * @param string $preferredbehaviour the type of behaviour that was actually
+     *      requested. This information is not needed in most cases, the type of
+     *      subclass is enough, but occasionally it is needed.
+     */
+    public function __construct(question_attempt $qa, $preferredbehaviour) {
+        $this->qa = $qa;
+        $this->question = $qa->get_question();
+        $requiredclass = $this->required_question_definition_type();
+        if (!$this->question instanceof $requiredclass) {
+            throw new Exception('This behaviour (' . $this->get_name() .
+                    ') cannot work with this question (' . get_class($this->question) . ')');
+        }
+    }
+
+    /**
+     * Most behaviours can only work with {@link question_definition}s
+     * of a particular subtype, or that implement a particular interface.
+     * This method lets the behaviour document that. The type of
+     * question passed to the constructor is then checked against this type.
+     * @return string class/interface name.
+     */
+    public abstract function required_question_definition_type();
+
+    /**
+     * @return string the name of this behaviour. For example the name of
+     * qbehaviour_mymodle is 'mymodel'.
+     */
+    public function get_name() {
+        return substr(get_class($this), 11);
+    }
+
+    /**
+     * 'Override' this method if there are some display options that do not make
+     * sense 'during the attempt'.
+     * @return array of {@link question_display_options} field names, that are
+     * not relevant to this behaviour before a 'finish' action.
+     */
+    public static function get_unused_display_options() {
+        return array();
+    }
+
+    /**
+     * Cause the question to be renderered. This gets the appropriate behaviour
+     * renderer using {@link get_renderer()}, and adjusts the display
+     * options using {@link adjust_display_options()} and then calls
+     * {@link core_question_renderer::question()} to do the work.
+     * @param question_display_options $options controls what should and should not be displayed.
+     * @param unknown_type $number the question number to display.
+     * @param core_question_renderer $qoutput the question renderer that will coordinate everything.
+     * @param qtype_renderer $qtoutput the question type renderer that will be helping.
+     * @return HTML fragment.
+     */
+    public function render(question_display_options $options, $number,
+            core_question_renderer $qoutput, qtype_renderer $qtoutput) {
+        $behaviouroutput = $this->get_renderer();
+        $options = clone($options);
+        $this->adjust_display_options($options);
+        return $qoutput->question($this->qa, $behaviouroutput, $qtoutput, $options, $number);
+    }
+
+    /**
+     * Checks whether the users is allow to be served a particular file.
+     * @param question_display_options $options the options that control display of the question.
+     * @param string $component the name of the component we are serving files for.
+     * @param string $filearea the name of the file area.
+     * @param array $args the remaining bits of the file path.
+     * @param boolean $forcedownload whether the user must be forced to download the file.
+     * @return boolean true if the user can access this file.
+     */
+    public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
+        $this->adjust_display_options($options);
+        return $this->question->check_file_access($this->qa, $options, $component, $filearea, $args, $forcedownload);
+    }
+
+    /**
+     * @return qbehaviour_renderer get the appropriate renderer to use for this model.
+     */
+    public function get_renderer() {
+        global $PAGE;
+        return $PAGE->get_renderer(get_class($this));
+    }
+
+    /**
+     * Make any changes to the display options before a question is rendered, so
+     * that it can be displayed in a way that is appropriate for the statue it is
+     * currently in. For example, by default, if the question is finished, we
+     * ensure that it is only ever displayed read-only.
+     * @param question_display_options $options the options to adjust. Just change
+     * the properties of this object - objects are passed by referece.
+     */
+    public function adjust_display_options(question_display_options $options) {
+        if (!$this->qa->has_marks()) {
+            $options->correctness = false;
+            $options->numpartscorrect = false;
+        }
+        if ($this->qa->get_state()->is_finished()) {
+            $options->readonly = true;
+            $options->numpartscorrect = $options->numpartscorrect &&
+                    $this->qa->get_state()->is_partially_correct() &&
+                    !empty($this->question->shownumcorrect);
+        } else {
+            $options->hide_all_feedback();
+        }
+    }
+
+    /**
+     * Get the most applicable hint for the question in its current state.
+     * @return question_hint the most applicable hint, or null, if none.
+     */
+    public function get_applicable_hint() {
+        return null;
+    }
+
+    /**
+     * What is the minimum fraction that can be scored for this question.
+     * Normally this will be based on $this->question->init_first_step($step),
+     * but may be modified in some way by the model.
+     *
+     * @return number the minimum fraction when this question is attempted under
+     * this model.
+     */
+    public function get_min_fraction() {
+        return 0;
+    }
+
+    /**
+     * Adjust a random guess score for a question using this model. You have to
+     * do this without knowing details of the specific question, or which usage
+     * it is in.
+     * @param number $fraction the random guess score from the question type.
+     * @return number the adjusted fraction.
+     */
+    public static function adjust_random_guess_score($fraction) {
+        return $fraction;
+    }
+
+    /**
+     * Return an array of the behaviour variables that could be submitted
+     * as part of a question of this type, with their types, so they can be
+     * properly cleaned.
+     * @return array variable name => PARAM_... constant.
+     */
+    public function get_expected_data() {
+        if (!$this->qa->get_state()->is_finished()) {
+            return array();
+        }
+
+        $vars = array('comment' => PARAM_RAW);
+        if ($this->qa->get_max_mark()) {
+            $vars['mark'] = question_attempt::PARAM_MARK;
+            $vars['maxmark'] = PARAM_NUMBER;
+        }
+        return $vars;
+    }
+
+    /**
+     * Return an array of question type variables for the question in its current
+     * state. Normally, if {@link adjust_display_options()} would set
+     * {@link question_display_options::$readonly} to true, then this method
+     * should return an empty array, otherwise it should return
+     * $this->question->get_expected_data(). Thus, there should be little need to
+     * override this method.
+     * @return array|string variable name => PARAM_... constant, or, as a special case
+     *      that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
+     *      meaning take all the raw submitted data belonging to this question.
+     */
+    public function get_expected_qt_data() {
+        $fakeoptions = new question_display_options();
+        $fakeoptions->readonly = false;
+        $this->adjust_display_options($fakeoptions);
+        if ($fakeoptions->readonly) {
+            return array();
+        } else {
+            return $this->question->get_expected_data();
+        }
+    }
+
+    /**
+     * Return an array of any im variables, and the value required to get full
+     * marks.
+     * @return array variable name => value.
+     */
+    public function get_correct_response() {
+        return array();
+    }
+
+    /**
+     * Generate a brief, plain-text, summary of this question. This is used by
+     * various reports. This should show the particular variant of the question
+     * as presented to students. For example, the calculated quetsion type would
+     * fill in the particular numbers that were presented to the student.
+     * This method will return null if such a summary is not possible, or
+     * inappropriate.
+     *
+     * Normally, this method delegates to {question_definition::get_question_summary()}.
+     *
+     * @return string|null a plain text summary of this question.
+     */
+    public function get_question_summary() {
+        return $this->question->get_question_summary();
+    }
+
+    /**
+     * Generate a brief, plain-text, summary of the correct answer to this question.
+     * This is used by various reports, and can also be useful when testing.
+     * This method will return null if such a summary is not possible, or
+     * inappropriate.
+     *
+     * @return string|null a plain text summary of the right answer to this question.
+     */
+    public function get_right_answer_summary() {
+        return null;
+    }
+
+    /**
+     * Used by {@link start_based_on()} to get the data needed to start a new
+     * attempt from the point this attempt has go to.
+     * @return array name => value pairs.
+     */
+    public function get_resume_data() {
+        $olddata = $this->qa->get_step(0)->get_all_data();
+        $olddata = $this->qa->get_last_qt_data() + $olddata;
+        $olddata = $this->get_our_resume_data() + $olddata;
+        return $olddata;
+    }
+
+    /**
+     * Used by {@link start_based_on()} to get the data needed to start a new
+     * attempt from the point this attempt has go to.
+     * @return unknown_type
+     */
+    protected function get_our_resume_data() {
+        return array();
+    }
+
+    /**
+     * @return array subpartid => object with fields
+     *      ->responseclassid the 
+     *      ->response the actual response the student gave to this part, as a string.
+     *      ->fraction the credit awarded for this subpart, may be null.
+     *      returns an empty array if no analysis is possible.
+     */
+    public function classify_response() {
+        return $this->question->classify_response($this->qa->get_last_qt_data());
+    }
+
+    /**
+     * Generate a brief textual description of the current state of the question,
+     * normally displayed under the question number.
+     *
+     * @param boolean $showcorrectness Whether right/partial/wrong states should
+     * be distinguised.
+     * @return string a brief summary of the current state of the qestion attempt.
+     */
+    public function get_state_string($showcorrectness) {
+        return $this->qa->get_state()->default_string($showcorrectness);
+    }
+
+    abstract public function summarise_action(question_attempt_step $step);
+
+    /**
+     * Initialise the first step in a question attempt.
+     *
+     * This method must call $this->question->init_first_step($step), and may
+     * perform additional processing if the model requries it.
+     *
+     * @param question_attempt_step $step the step being initialised.
+     */
+    public function init_first_step(question_attempt_step $step) {
+        $this->question->init_first_step($step);
+    }
+
+    /**
+     * Checks whether two manual grading actions are the same. That is, whether
+     * the comment, and the mark (if given) is the same.
+     *
+     * @param question_attempt_step $pendingstep contains the new responses.
+     * @return boolean whether the new response is the same as we already have.
+     */
+    protected function is_same_comment($pendingstep) {
+        $previouscomment = $this->qa->get_last_behaviour_var('comment');
+        $newcomment = $pendingstep->get_behaviour_var('comment');
+
+        if (is_null($previouscomment) && !html_is_blank($newcomment) ||
+                $previouscomment != $newcomment) {
+            return false;
+        }
+
+        // So, now we know the comment is the same, so check the mark, if present.
+        $previousfraction = $this->qa->get_fraction();
+        $newmark = $pendingstep->get_behaviour_var('mark');
+
+        if (is_null($previousfraction)) {
+            return is_null($newmark) || $newmark === '';
+        } else if (is_null($newmark) || $newmark === '') {
+            return false;
+        }
+
+        $newfraction = $newmark / $pendingstep->get_behaviour_var('maxmark');
+
+        return abs($newfraction - $previousfraction) < 0.0000001;
+    }
+
+    /**
+     * The main entry point for processing an action.
+     *
+     * All the various operations that can be performed on a
+     * {@link question_attempt} get channeled through this function, except for
+     * {@link question_attempt::start()} which goes to {@link init_first_step()}.
+     * {@link question_attempt::finish()} becomes an action with im vars
+     * finish => 1, and manual comment/grade becomes an action with im vars
+     * comment => comment text, and mark => ..., max_mark => ... if the question
+     * is graded.
+     *
+     * This method should first determine whether the action is significant. For
+     * example, if no actual action is being performed, but instead the current
+     * responses are being saved, and there has been no change since the last
+     * set of responses that were saved, this the action is not significatn. In
+     * this case, this method should return {@link question_attempt::DISCARD}.
+     * Otherwise it should return {@link question_attempt::KEEP}.
+     *
+     * If the action is significant, this method should also perform any
+     * necessary updates to $pendingstep. For example, it should call
+     * {@link question_attempt_step::set_state()} to set the state that results
+     * from this action, and if this is a grading action, it should call
+     * {@link question_attempt_step::set_fraction()}.
+     *
+     * This method can also call {@link question_attempt_step::set_behaviour_var()} to
+     * store additional infomation. There are two main uses for this. This can
+     * be used to store the result of any randomisation done. It is important to
+     * store the result of randomisation once, and then in future use the same
+     * outcome if the actions are ever replayed. This is how regrading works.
+     * The other use is to cache the result of expensive computations performed
+     * on the raw response data, so that subsequent display and review of the
+     * question does not have to repeat the same expensive computations.
+     *
+     * Often this method is implemented as a dispatching method that examines
+     * the pending step to determine the kind of action being performed, and
+     * then calls a more specific method like {@link process_save()} or
+     * {@link process_comment()}. Look at some of the standard behaviours
+     * for examples.
+     *
+     * @param question_attempt_pending_step $pendingstep a partially initialised step
+     *      containing all the information about the action that is being peformed.
+     *      This information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
+     * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
+     */
+    public abstract function process_action(question_attempt_pending_step $pendingstep);
+
+    /**
+     * Implementation of processing a manual comment/grade action that should
+     * be suitable for most subclasses.
+     * @param question_attempt_pending_step $pendingstep a partially initialised step
+     *      containing all the information about the action that is being peformed.
+     * @return boolean either {@link question_attempt::KEEP}
+     */
+    public function process_comment(question_attempt_pending_step $pendingstep) {
+        if (!$this->qa->get_state()->is_finished()) {
+            throw new coding_exception('Cannot manually grade a question before it is finshed.');
+        }
+
+        if ($this->is_same_comment($pendingstep)) {
+            return question_attempt::DISCARD;
+        }
+
+        if ($pendingstep->has_behaviour_var('mark')) {
+            $fraction = $pendingstep->get_behaviour_var('mark') / $pendingstep->get_behaviour_var('maxmark');
+            if ($pendingstep->get_behaviour_var('mark') === '') {
+                $fraction = null;
+            } else if ($fraction > 1 || $fraction < $this->qa->get_min_fraction()) {
+                throw new coding_exception('Score out of range when processing ' .
+                        'a manual grading action.', $pendingstep);
+            }
+            $pendingstep->set_fraction($fraction);
+        }
+
+        $pendingstep->set_state($this->qa->get_state()->
+                corresponding_commented_state($pendingstep->get_fraction()));
+        return question_attempt::KEEP;
+    }
+
+    /**
+     * @param $comment the comment text to format. If omitted,
+     *      $this->qa->get_manual_comment() is used.
+     * @param $commentformat the format of the comment, one of the FORMAT_... constants.
+     * @return string the comment, ready to be output.
+     */
+    public function format_comment($comment = null, $commentformat = null) {
+        $formatoptions = new stdClass;
+        $formatoptions->noclean = true;
+        $formatoptions->para = false;
+
+        if (is_null($comment)) {
+            list($comment, $commentformat) = $this->qa->get_manual_comment();
+        }
+
+        return format_text($comment, $commentformat, $formatoptions);
+    }
+
+    /**
+     * @return string a summary of a manual comment action.
+     * @param unknown_type $step
+     */
+    protected function summarise_manual_comment($step) {
+        $a = new stdClass;
+        if ($step->has_behaviour_var('comment')) {
+            $a->comment = shorten_text(html_to_text($this->format_comment(
+                    $step->get_behaviour_var('comment')), 0, false), 200);
+        } else {
+            $a->comment = '';
+        }
+
+        $mark = $step->get_behaviour_var('mark');
+        if (is_null($mark) || $mark === '') {
+            return get_string('commented', 'question', $a->comment);
+        } else {
+            $a->mark = $mark / $step->get_behaviour_var('maxmark') * $this->qa->get_max_mark();
+            return get_string('manuallygraded', 'question', $a);
+        }
+    }
+
+    public function summarise_start($step) {
+        return get_string('started', 'question');
+    }
+
+    public function summarise_finish($step) {
+        return get_string('attemptfinished', 'question');
+    }
+}
+
+
+/**
+ * A subclass of {@link question_behaviour} that implements a save
+ * action that is suitable for most questions that implement the
+ * {@link question_manually_gradable} interface.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+abstract class question_behaviour_with_save extends question_behaviour {
+    public function required_question_definition_type() {
+        return 'question_manually_gradable';
+    }
+
+    /**
+     * Work out whether the response in $pendingstep are significantly different
+     * from the last set of responses we have stored.
+     * @param question_attempt_step $pendingstep contains the new responses.
+     * @return boolean whether the new response is the same as we already have.
+     */
+    protected function is_same_response(question_attempt_step $pendingstep) {
+        return $this->question->is_same_response(
+                $this->qa->get_last_step()->get_qt_data(), $pendingstep->get_qt_data());
+    }
+
+    /**
+     * Work out whether the response in $pendingstep represent a complete answer
+     * to the question. Normally this will call
+     * {@link question_manually_gradable::is_complete_response}, but some
+     * behaviours, for example the CBM ones, have their own parts to the
+     * response.
+     * @param question_attempt_step $pendingstep contains the new responses.
+     * @return boolean whether the new response is complete.
+     */
+    protected function is_complete_response(question_attempt_step $pendingstep) {
+        return $this->question->is_complete_response($pendingstep->get_qt_data());
+    }
+
+    /**
+     * Implementation of processing a save action that should be suitable for
+     * most subclasses.
+     * @param question_attempt_pending_step $pendingstep a partially initialised step
+     *      containing all the information about the action that is being peformed.
+     * @return boolean either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
+     */
+    public function process_save(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        } else if (!$this->qa->get_state()->is_active()) {
+            throw new Exception('Question is not active, cannot process_actions.');
+        }
+
+        if ($this->is_same_response($pendingstep)) {
+            return question_attempt::DISCARD;
+        }
+
+        if ($this->is_complete_response($pendingstep)) {
+            $pendingstep->set_state(question_state::$complete);
+        } else {
+            $pendingstep->set_state(question_state::$todo);
+        }
+        return question_attempt::KEEP;
+    }
+
+    public function summarise_submit(question_attempt_step $step) {
+        return get_string('submitted', 'question',
+                $this->question->summarise_response($step->get_qt_data()));
+    }
+
+    public function summarise_save(question_attempt_step $step) {
+        $data = $step->get_submitted_data();
+        if (empty($data)) {
+            return $this->summarise_start($step);
+        }
+        return get_string('saved', 'question',
+                $this->question->summarise_response($step->get_qt_data()));
+    }
+
+
+    public function summarise_finish($step) {
+        $data = $step->get_qt_data();
+        if ($data) {
+            return get_string('attemptfinishedsubmitting', 'question',
+                    $this->question->summarise_response($data));
+        }
+        return get_string('attemptfinished', 'question');
+    }
+}
+
+
+/**
+ * This helper class contains the constants and methods required for
+ * manipulating scores for certainly based marking.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+abstract class question_cbm {
+    /**#@+ @var integer named constants for the certainty levels. */
+    const LOW = 1;
+    const MED = 2;
+    const HIGH = 3;
+    /**#@-*/
+
+    /** @var array list of all the certainty levels. */
+    public static $certainties = array(self::LOW, self::MED, self::HIGH);
+
+    /**#@+ @var array coefficients used to adjust the fraction based on certainty.. */
+    protected static $factor = array(
+        self::LOW => 0.333333333333333,
+        self::MED => 1.333333333333333,
+        self::HIGH => 3,
+    );
+    protected static $offset = array(
+        self::LOW => 0,
+        self::MED => -0.666666666666667,
+        self::HIGH => -2,
+    );
+    /**#@-*/
+
+    /**
+     * @return integer the default certaintly level that should be assuemd if
+     * the student does not choose one.
+     */
+    public static function default_certainty() {
+        return self::LOW;
+    }
+
+    /**
+     * Given a fraction, and a certainly, compute the adjusted fraction.
+     * @param number $fraction the raw fraction for this question.
+     * @param integer $certainty one of the certainly level constants.
+     * @return number the adjusted fraction taking the certainly into account.
+     */
+    public static function adjust_fraction($fraction, $certainty) {
+        return self::$offset[$certainty] + self::$factor[$certainty] * $fraction;
+    }
+
+    /**
+     * @param integer $certainty one of the LOW/MED/HIGH constants.
+     * @return string a textual desciption of this certainly.
+     */
+    public static function get_string($certainty) {
+        return get_string('certainty' . $certainty, 'qbehaviour_deferredcbm');
+    }
+
+    public static function summary_with_certainty($summary, $certainty) {
+        if (is_null($certainty)) {
+            return $summary;
+        }
+        return $summary . ' [' . self::get_string($certainty) . ']';
+    }
+}
diff --git a/question/behaviour/deferredcbm/behaviour.php b/question/behaviour/deferredcbm/behaviour.php
new file mode 100644 (file)
index 0000000..02c4600
--- /dev/null
@@ -0,0 +1,125 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour that is like the deferred feedback model, but with
+ * certainly based marking. That is, in addition to the other controls, there are
+ * where the student can indicate how certain they are that their answer is right.
+ *
+ * @package qbehaviour_deferredcbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../deferredfeedback/behaviour.php');
+
+/**
+ * Question behaviour for deferred feedback with certainty based marking.
+ *
+ * The student enters their response during the attempt, along with a certainty,
+ * that is, how sure they are that they are right, and it is saved. Later,
+ * when the whole attempt is finished, their answer is graded. Their degree
+ * of certainty affects their score.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_deferredcbm extends qbehaviour_deferredfeedback {
+    const IS_ARCHETYPAL = true;
+
+    public static function get_unused_display_options() {
+        return array('correctness', 'marks', 'specificfeedback', 'generalfeedback',
+                'rightanswer');
+    }
+
+    public function get_min_fraction() {
+        return question_cbm::adjust_fraction(parent::get_min_fraction(), question_cbm::HIGH);
+    }
+
+    public function get_expected_data() {
+        if ($this->qa->get_state()->is_active()) {
+            return array('certainty' => PARAM_INT);
+        }
+        return parent::get_expected_data();
+    }
+
+    public function get_right_answer_summary() {
+        $summary = parent::get_right_answer_summary();
+        return $summary . ' [' . question_cbm::get_string(question_cbm::HIGH) . ']';
+    }
+
+    public function get_correct_response() {
+        if ($this->qa->get_state()->is_active()) {
+            return array('certainty' => question_cbm::HIGH);
+        }
+        return array();
+    }
+
+    protected function get_our_resume_data() {
+        $lastcertainty = $this->qa->get_last_behaviour_var('certainty');
+        if ($lastcertainty) {
+            return array('-certainty' => $lastcertainty);
+        } else {
+            return array();
+        }
+    }
+
+    protected function is_same_response($pendingstep) {
+        return parent::is_same_response($pendingstep) &&
+                $this->qa->get_last_behaviour_var('certainty') == $pendingstep->get_behaviour_var('certainty');
+    }
+
+    protected function is_complete_response($pendingstep) {
+        return parent::is_complete_response($pendingstep) && $pendingstep->has_behaviour_var('certainty');
+    }
+
+    public function process_finish(question_attempt_pending_step $pendingstep) {
+        $status = parent::process_finish($pendingstep);
+        if ($status == question_attempt::KEEP) {
+            $fraction = $pendingstep->get_fraction();
+            if ($this->qa->get_last_step()->has_behaviour_var('certainty')) {
+                $certainty = $this->qa->get_last_step()->get_behaviour_var('certainty');
+            } else {
+                $certainty = question_cbm::default_certainty();
+                $pendingstep->set_behaviour_var('_assumedcertainty', $certainty);
+            }
+            if (!is_null($fraction)) {
+                $pendingstep->set_behaviour_var('_rawfraction', $fraction);
+                $pendingstep->set_fraction(question_cbm::adjust_fraction($fraction, $certainty));
+            }
+            $pendingstep->set_new_response_summary(
+                    question_cbm::summary_with_certainty($pendingstep->get_new_response_summary(),
+                    $this->qa->get_last_step()->get_behaviour_var('certainty')));
+        }
+        return $status;
+    }
+
+    public function summarise_action(question_attempt_step $step) {
+        $summary = parent::summarise_action($step);
+        if ($step->has_behaviour_var('certainty')) {
+            $summary = question_cbm::summary_with_certainty($summary,
+                    $step->get_behaviour_var('certainty'));
+        }
+        return $summary;
+    }
+
+    public static function adjust_random_guess_score($fraction) {
+        return question_cbm::adjust_fraction($fraction, question_cbm::default_certainty());
+    }
+}
diff --git a/question/behaviour/deferredcbm/lang/en/qbehaviour_deferredcbm.php b/question/behaviour/deferredcbm/lang/en/qbehaviour_deferredcbm.php
new file mode 100644 (file)
index 0000000..3576722
--- /dev/null
@@ -0,0 +1,9 @@
+<?php
+
+$string['assumingcertainty'] = 'You did not select a certainty. Assuming: {$a}.';
+$string['certainty1'] = 'Not very (less than 67%)';
+$string['certainty2'] = 'Fairly (more than 67%)';
+$string['certainty3'] = 'Very (more than 85%)';
+$string['deferredcbm'] = 'Deferred feedback with CBM';
+$string['howcertainareyou'] = 'How certain are you? {$a}';
+$string['markadjustment'] = 'Based on the certainty you expressed, your base mark of {$a->rawmark} was adjusted to {$a->mark}.';
diff --git a/question/behaviour/deferredcbm/renderer.php b/question/behaviour/deferredcbm/renderer.php
new file mode 100644 (file)
index 0000000..eef1afc
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the deferred
+ * feedback behaviour.
+ *
+ * @package qbehaviour_deferredcbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+class qbehaviour_deferredcbm_renderer extends qbehaviour_renderer {
+    protected function certainly_choices($controlname, $selected, $readonly) {
+        $attributes = array(
+            'type' => 'radio',
+            'name' => $controlname,
+        );
+        if ($readonly) {
+            $attributes['disabled'] = 'disabled';
+        }
+
+        $choices = '';
+        foreach (question_cbm::$certainties as $certainty) {
+            $id = $controlname . $certainty;
+            $attributes['id'] = $id;
+            $attributes['value'] = $certainty;
+            if ($selected == $certainty) {
+                $attributes['checked'] = 'checked';
+            } else {
+                unset($attributes['checked']);
+            }
+            $choices .= ' ' . html_writer::empty_tag('input', $attributes) . ' ' .
+                    html_writer::tag('label', question_cbm::get_string($certainty),
+                            array('for' => $id));
+        }
+        return $choices;
+    }
+
+    public function controls(question_attempt $qa, question_display_options $options) {
+        return html_writer::tag('div', get_string('howcertainareyou', 'qbehaviour_deferredcbm',
+                $this->certainly_choices($qa->get_behaviour_field_name('certainty'),
+                $qa->get_last_behaviour_var('certainty'), $options->readonly)),
+                array('class' => 'certaintychoices'));
+    }
+
+    public function feedback(question_attempt $qa, question_display_options $options) {
+        if (!$options->feedback) {
+            return '';
+        }
+
+        if ($qa->get_state() == question_state::$gaveup || $qa->get_state() == question_state::$mangaveup) {
+            return '';
+        }
+
+        $feedback = '';
+        if (!$qa->get_last_behaviour_var('certainty') && $qa->get_last_behaviour_var('_assumedcertainty')) {
+            $feedback .= html_writer::tag('p', get_string('assumingcertainty', 'qbehaviour_deferredcbm',
+                    question_cbm::get_string($qa->get_last_behaviour_var('_assumedcertainty'))));
+        }
+
+        if ($options->marks) {
+            $a->rawmark = format_float(
+                    $qa->get_last_behaviour_var('_rawfraction') * $qa->get_max_mark(), $options->markdp);
+            $a->mark = $qa->format_mark($options->markdp);
+            $feedback .= html_writer::tag('p', get_string('markadjustment', 'qbehaviour_deferredcbm', $a));
+        }
+
+        return $feedback;
+    }
+}
\ No newline at end of file
diff --git a/question/behaviour/deferredcbm/simpletest/testwalkthrough.php b/question/behaviour/deferredcbm/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..742911d
--- /dev/null
@@ -0,0 +1,261 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the deferred feedback
+ * behaviour.
+ *
+ * @package qbehaviour_deferredcbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_deferredcbm_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_deferred_cbm_truefalse_high_certainty() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredcbm', 2);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($tf),
+                $this->get_contains_tf_true_radio_expectation(true, false),
+                $this->get_contains_tf_false_radio_expectation(true, false),
+                $this->get_contains_cbm_radio_expectation(1, true, false),
+                $this->get_contains_cbm_radio_expectation(2, true, false),
+                $this->get_contains_cbm_radio_expectation(3, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process the data extracted for this question.
+        $this->process_submission(array('answer' => 1, '-certainty' => 3));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_tf_true_radio_expectation(true, true),
+                $this->get_contains_cbm_radio_expectation(3, true, true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process the same data again, check it does not create a new step.
+        $numsteps = $this->get_step_count();
+        $this->process_submission(array('answer' => 1, '-certainty' => 3));
+        $this->check_step_count($numsteps);
+
+        // Process different data, check it creates a new step.
+        $this->process_submission(array('answer' => 1, '-certainty' => 1));
+        $this->check_step_count($numsteps + 1);
+        $this->check_current_state(question_state::$complete);
+
+        // Change back, check it creates a new step.
+        $this->process_submission(array('answer' => 1, '-certainty' => 3));
+        $this->check_step_count($numsteps + 2);
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2);
+        $this->check_current_output(
+                $this->get_contains_tf_true_radio_expectation(false, true),
+                $this->get_contains_cbm_radio_expectation(3, false, true),
+                $this->get_contains_correct_expectation());
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 1);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $tf->rightanswer = false;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), -2, 0.0000001);
+    }
+
+    public function test_deferred_cbm_truefalse_low_certainty() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredcbm', 2);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit ansewer with low certainty.
+        $this->process_submission(array('answer' => 1, '-certainty' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(null);
+        $this->check_current_output($this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, true, true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(0.6666667);
+        $this->check_current_output($this->get_contains_correct_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, false, true));
+        $this->assertEqual(get_string('true', 'qtype_truefalse') . ' [' . question_cbm::get_string(1) . ']',
+                $this->quba->get_response_summary($this->slot));
+    }
+
+    public function test_deferred_cbm_truefalse_default_certainty() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredcbm', 2);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit ansewer with low certainty and finish the attempt.
+        $this->process_submission(array('answer' => 1));
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $qa = $this->quba->get_question_attempt($this->slot);
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(0.6666667);
+        $this->check_current_output($this->get_contains_correct_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, false, false),
+                new PatternExpectation('/' . preg_quote(get_string('assumingcertainty', 'qbehaviour_deferredcbm',
+                    question_cbm::get_string($qa->get_last_behaviour_var('_assumedcertainty')))) . '/'));
+        $this->assertEqual(get_string('true', 'qtype_truefalse'),
+                $this->quba->get_response_summary($this->slot));
+    }
+
+    public function test_deferredcbm_resume_multichoice_single() {
+
+        // Create a multiple-choice question.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+
+        // Attempt it getting it wrong.
+        $this->start_attempt_at_question($mc, 'deferredcbm', 3);
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+        $this->process_submission(array('answer' => $wrongindex, '-certainty' => 2));
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedwrong);
+        $this->check_current_mark(-3.3333333);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, false, true),
+                $this->get_contains_cbm_radio_expectation(2, false, true),
+                $this->get_contains_incorrect_expectation());
+        $this->assertEqual('A [' . question_cbm::get_string(question_cbm::HIGH) . ']',
+                $this->quba->get_right_answer_summary($this->slot));
+        $this->assertPattern('/' . preg_quote($mc->questiontext) . '/',
+                $this->quba->get_question_summary($this->slot));
+        $this->assertPattern('/(B|C) \[' . preg_quote(question_cbm::get_string(2)) . '\]/',
+                $this->quba->get_response_summary($this->slot));
+
+        // Save the old attempt.
+        $oldqa = $this->quba->get_question_attempt($this->slot);
+
+        // Reinitialise.
+        $this->setUp();
+        $this->quba->set_preferred_behaviour('deferredcbm');
+        $this->slot = $this->quba->add_question($mc, 3);
+        $this->quba->start_question_based_on($this->slot, $oldqa);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_cbm_radio_expectation(2, true, true),
+                $this->get_does_not_contain_feedback_expectation(),
+                $this->get_does_not_contain_correctness_expectation());
+        $this->assertEqual('A [' . question_cbm::get_string(question_cbm::HIGH) . ']',
+                $this->quba->get_right_answer_summary($this->slot));
+        $this->assertPattern('/' . preg_quote($mc->questiontext) . '/',
+                $this->quba->get_question_summary($this->slot));
+        $this->assertNull($this->quba->get_response_summary($this->slot));
+
+        // Now get it right.
+        $this->process_submission(array('answer' => $rightindex, '-certainty' => 3));
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_cbm_radio_expectation(3, false, true),
+                $this->get_contains_correct_expectation());
+        $this->assertPattern('/(A) \[' . preg_quote(question_cbm::get_string(3)) . '\]/',
+                $this->quba->get_response_summary($this->slot));
+    }
+
+    public function test_deferred_cbm_truefalse_no_certainty_feedback_when_not_answered() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredcbm', 2);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Finish without answering.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gaveup);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                new NoPatternExpectation('/class=\"im-feedback/'));
+    }
+}
+
diff --git a/question/behaviour/deferredfeedback/behaviour.php b/question/behaviour/deferredfeedback/behaviour.php
new file mode 100644 (file)
index 0000000..937799a
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour for the case when the student's answer is just
+ * saved until they submit the whole attempt, and then it is graded.
+ *
+ * @package qbehaviour_deferredfeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+/**
+ * Question behaviour for deferred feedback.
+ *
+ * The student enters their response during the attempt, and it is saved. Later,
+ * when the whole attempt is finished, their answer is graded.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_deferredfeedback extends question_behaviour_with_save {
+    const IS_ARCHETYPAL = true;
+
+    public function required_question_definition_type() {
+        return 'question_automatically_gradable';
+    }
+
+    public static function get_unused_display_options() {
+        return array('correctness', 'marks', 'specificfeedback', 'generalfeedback',
+                'rightanswer');
+    }
+
+    public function get_min_fraction() {
+        return $this->question->get_min_fraction();
+    }
+
+    public function get_right_answer_summary() {
+        return $this->question->get_right_answer_summary();
+    }
+
+    public function process_action(question_attempt_pending_step $pendingstep) {
+        if ($pendingstep->has_behaviour_var('comment')) {
+            return $this->process_comment($pendingstep);
+        } else if ($pendingstep->has_behaviour_var('finish')) {
+            return $this->process_finish($pendingstep);
+        } else {
+            return $this->process_save($pendingstep);
+        }
+    }
+
+    public function summarise_action(question_attempt_step $step) {
+        if ($step->has_behaviour_var('comment')) {
+            return $this->summarise_manual_comment($step);
+        } else if ($step->has_behaviour_var('finish')) {
+            return $this->summarise_finish($step);
+        } else {
+            return $this->summarise_save($step);
+        }
+    }
+
+    public function process_finish(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        $response = $this->qa->get_last_step()->get_qt_data();
+        if (!$this->question->is_gradable_response($response)) {
+            $pendingstep->set_state(question_state::$gaveup);
+        } else {
+            list($fraction, $state) = $this->question->grade_response($response);
+            $pendingstep->set_fraction($fraction);
+            $pendingstep->set_state($state);
+        }
+        $pendingstep->set_new_response_summary($this->question->summarise_response($response));
+        return question_attempt::KEEP;
+    }
+}
diff --git a/question/behaviour/deferredfeedback/lang/en/qbehaviour_deferredfeedback.php b/question/behaviour/deferredfeedback/lang/en/qbehaviour_deferredfeedback.php
new file mode 100644 (file)
index 0000000..a6646f6
--- /dev/null
@@ -0,0 +1,3 @@
+<?php
+
+$string['deferredfeedback'] = 'Deferred feedback';
diff --git a/question/behaviour/deferredfeedback/renderer.php b/question/behaviour/deferredfeedback/renderer.php
new file mode 100644 (file)
index 0000000..a3a2976
--- /dev/null
@@ -0,0 +1,30 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the deferred
+ * feedback behaviour.
+ *
+ * @package qbehaviour_deferredfeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+class qbehaviour_deferredfeedback_renderer extends qbehaviour_renderer {
+}
diff --git a/question/behaviour/deferredfeedback/simpletest/testwalkthrough.php b/question/behaviour/deferredfeedback/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..8f4eee1
--- /dev/null
@@ -0,0 +1,205 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the deferred feedback
+ * behaviour.
+ *
+ * @package qbehaviour_deferredfeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_deferredfeedback_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_deferredfeedback_feedback_truefalse() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredfeedback', 2);
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output($this->get_contains_question_text_expectation($tf),
+                $this->get_does_not_contain_feedback_expectation());
+        $this->assertEqual(get_string('true', 'qtype_truefalse'),
+                $this->quba->get_right_answer_summary($this->slot));
+        $this->assertPattern('/' . preg_quote($tf->questiontext) . '/',
+                $this->quba->get_question_summary($this->slot));
+        $this->assertNull($this->quba->get_response_summary($this->slot));
+
+        // Process a true answer and check the expected result.
+        $this->process_submission(array('answer' => 1));
+
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(null);
+        $this->check_current_output($this->get_contains_tf_true_radio_expectation(true, true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process the same data again, check it does not create a new step.
+        $numsteps = $this->get_step_count();
+        $this->process_submission(array('answer' => 1));
+        $this->check_step_count($numsteps);
+
+        // Process different data, check it creates a new step.
+        $this->process_submission(array('answer' => 0));
+        $this->check_step_count($numsteps + 1);
+        $this->check_current_state(question_state::$complete);
+
+        // Change back, check it creates a new step.
+        $this->process_submission(array('answer' => 1));
+        $this->check_step_count($numsteps + 2);
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2);
+        $this->check_current_output($this->get_contains_correct_expectation(),
+                $this->get_contains_tf_true_radio_expectation(false, true),
+                new PatternExpectation('/class="r0 correct"/'));
+        $this->assertEqual(get_string('true', 'qtype_truefalse'),
+                $this->quba->get_response_summary($this->slot));
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 1);
+
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $tf->rightanswer = false;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(1);
+
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), 0, 0.0000001);
+    }
+
+    public function test_deferredfeedback_feedback_multichoice_single() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'deferredfeedback', 3);
+
+        // Start a deferred feedback attempt and add the question to it.
+        $rightindex = $this->get_mc_right_answer_index($mc);
+
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Process the data extracted for this question.
+        $this->process_submission(array('answer' => $rightindex));
+
+        // Verify.
+        $this->check_current_state(question_state::$complete);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, true, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, true, false),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_correct_expectation());
+
+        // Now change the correct answer to the question, and regrade.
+        $mc->answers[13]->fraction = -0.33333333;
+        $mc->answers[14]->fraction = 1;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedwrong);
+        $this->check_current_mark(-1);
+        $this->check_current_output(
+                $this->get_contains_incorrect_expectation());
+    }
+
+    public function test_deferredfeedback_resume_multichoice_single() {
+
+        // Create a multiple-choice question.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+
+        // Attempt it getting it wrong.
+        $this->start_attempt_at_question($mc, 'deferredfeedback', 3);
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+        $this->process_submission(array('answer' => $wrongindex));
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedwrong);
+        $this->check_current_mark(-1);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, false, true),
+                $this->get_contains_incorrect_expectation());
+
+        // Save the old attempt.
+        $oldqa = $this->quba->get_question_attempt($this->slot);
+
+        // Reinitialise.
+        $this->setUp();
+        $this->quba->set_preferred_behaviour('deferredfeedback');
+        $this->slot = $this->quba->add_question($mc, 3);
+        $this->quba->start_question_based_on($this->slot, $oldqa);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_does_not_contain_feedback_expectation(),
+                $this->get_does_not_contain_correctness_expectation());
+
+        // Now get it right.
+        $this->process_submission(array('answer' => $rightindex));
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_correct_expectation());
+    }
+}
diff --git a/question/behaviour/immediatecbm/behaviour.php b/question/behaviour/immediatecbm/behaviour.php
new file mode 100644 (file)
index 0000000..ef8ac16
--- /dev/null
@@ -0,0 +1,151 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour where the student can submit questions one at a
+ * time for immediate feedback, with certainty based marking.
+ *
+ * @package qbehaviour_immediatecbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../immediatefeedback/behaviour.php');
+
+/**
+ * Question behaviour for immediate feedback with CBM.
+ *
+ * Each question has a submit button next to it along with some radio buttons
+ * to input a certainly, that is, how sure they are that they are right.
+ * The student can submit their answer at any time for immediate feedback.
+ * Once the qustion is submitted, it is not possible for the student to change
+ * their answer any more. The student's degree of certainly affects their score.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_immediatecbm extends qbehaviour_immediatefeedback {
+    const IS_ARCHETYPAL = true;
+
+    public function get_min_fraction() {
+        return question_cbm::adjust_fraction(parent::get_min_fraction(), question_cbm::HIGH);
+    }
+
+    public function get_expected_data() {
+        if ($this->qa->get_state()->is_active()) {
+            return array(
+                'submit' => PARAM_BOOL,
+                'certainty' => PARAM_INT,
+            );
+        }
+        return parent::get_expected_data();
+    }
+
+    public function get_right_answer_summary() {
+        $summary = parent::get_right_answer_summary();
+        return question_cbm::summary_with_certainty($summary, question_cbm::HIGH);
+    }
+
+    public function get_correct_response() {
+        if ($this->qa->get_state()->is_active()) {
+            return array('certainty' => question_cbm::HIGH);
+        }
+        return array();
+    }
+
+    protected function get_our_resume_data() {
+        $lastcertainty = $this->qa->get_last_behaviour_var('certainty');
+        if ($lastcertainty) {
+            return array('-certainty' => $lastcertainty);
+        } else {
+            return array();
+        }
+    }
+
+    protected function is_same_response($pendingstep) {
+        return parent::is_same_response($pendingstep) &&
+                $this->qa->get_last_behaviour_var('certainty') == $pendingstep->get_behaviour_var('certainty');
+    }
+
+    protected function is_complete_response($pendingstep) {
+        return parent::is_complete_response($pendingstep) && $pendingstep->has_behaviour_var('certainty');
+    }
+
+    public function process_submit(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        if (!$this->qa->get_question()->is_gradable_response($pendingstep->get_qt_data()) ||
+                !$pendingstep->has_behaviour_var('certainty')) {
+            $pendingstep->set_state(question_state::$invalid);
+            return question_attempt::KEEP;
+        }
+
+        return $this->do_grading($pendingstep, $pendingstep);
+    }
+
+    public function process_finish(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        $laststep = $this->qa->get_last_step();
+        return $this->do_grading($laststep, $pendingstep);
+    }
+
+    protected function do_grading(question_attempt_step $responsesstep,
+            question_attempt_pending_step $pendingstep) {
+        if (!$this->question->is_gradable_response($responsesstep->get_qt_data())) {
+            $pendingstep->set_state(question_state::$gaveup);
+
+        } else {
+            $response = $responsesstep->get_qt_data();
+            list($fraction, $state) = $this->question->grade_response($response);
+
+            if ($responsesstep->has_behaviour_var('certainty')) {
+                $certainty = $responsesstep->get_behaviour_var('certainty');
+            } else {
+                $certainty = question_cbm::default_certainty();
+                $pendingstep->set_behaviour_var('_assumedcertainty', $certainty);
+            }
+
+            $pendingstep->set_behaviour_var('_rawfraction', $fraction);
+            $pendingstep->set_fraction(question_cbm::adjust_fraction($fraction, $certainty));
+            $pendingstep->set_state($state);
+            $pendingstep->set_new_response_summary(
+                    question_cbm::summary_with_certainty(
+                    $this->question->summarise_response($response), $responsesstep->get_behaviour_var('certainty')));
+        }
+        return question_attempt::KEEP;
+    }
+
+    public function summarise_action(question_attempt_step $step) {
+        $summary = parent::summarise_action($step);
+        if ($step->has_behaviour_var('certainty')) {
+            $summary = question_cbm::summary_with_certainty($summary,
+                    $step->get_behaviour_var('certainty'));
+        }
+        return $summary;
+    }
+
+    public static function adjust_random_guess_score($fraction) {
+        return question_cbm::adjust_fraction($fraction, question_cbm::default_certainty());
+    }
+}
diff --git a/question/behaviour/immediatecbm/lang/en/qbehaviour_immediatecbm.php b/question/behaviour/immediatecbm/lang/en/qbehaviour_immediatecbm.php
new file mode 100644 (file)
index 0000000..e754515
--- /dev/null
@@ -0,0 +1,4 @@
+<?php
+
+$string['immediatecbm'] = 'Immediate feedback with CBM';
+$string['pleaseselectacertainty'] = 'Please select a certainty.';
diff --git a/question/behaviour/immediatecbm/renderer.php b/question/behaviour/immediatecbm/renderer.php
new file mode 100644 (file)
index 0000000..c36a03e
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the immediate
+ * feedback with CBM behaviour.
+ *
+ * @package qbehaviour_immediatecbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../deferredcbm/renderer.php');
+
+
+class qbehaviour_immediatecbm_renderer extends qbehaviour_deferredcbm_renderer {
+    public function controls(question_attempt $qa, question_display_options $options) {
+        $output = parent::controls($qa, $options);
+        if ($qa->get_state() == question_state::$invalid && !$qa->get_last_step()->has_behaviour_var('certainty')) {
+            $output .= html_writer::tag('div',
+                    get_string('pleaseselectacertainty', 'qbehaviour_immediatecbm'),
+                    array('class' => 'validationerror'));
+        }
+        $output .= $this->submit_button($qa, $options);
+        return $output;
+    }
+}
diff --git a/question/behaviour/immediatecbm/simpletest/testwalkthrough.php b/question/behaviour/immediatecbm/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..425ec4e
--- /dev/null
@@ -0,0 +1,282 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the immediate cbm
+ * behaviour.
+ *
+ * @package qbehaviour_immediatecbm
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_immediatecbm_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_immediatecbm_feedback_multichoice_right() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatecbm');
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+        $this->assertEqual('A [' . question_cbm::get_string(question_cbm::HIGH) . ']',
+                $this->quba->get_right_answer_summary($this->slot));
+        $this->assertPattern('/' . preg_quote($mc->questiontext) . '/',
+                $this->quba->get_question_summary($this->slot));
+        $this->assertNull($this->quba->get_response_summary($this->slot));
+
+        // Save the wrong answer.
+        $this->process_submission(array('answer' => $wrongindex, '-certainty' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit the right answer.
+        $this->process_submission(array('answer' => $rightindex, '-certainty' => 2, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2/3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_correct_expectation());
+        $this->assertEqual('A [' . question_cbm::get_string(2) . ']',
+                $this->quba->get_response_summary($this->slot));
+
+        $numsteps = $this->get_step_count();
+
+        // Finish the attempt - should not need to add a new state.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->assertEqual($numsteps, $this->get_step_count());
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(2/3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_correct_expectation());
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 0.5);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation(),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $mc->answers[13]->fraction = -0.33333333;
+        $mc->answers[15]->fraction = 1;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation());
+
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), -10/9, 0.0000001);
+    }
+
+    public function test_immediatecbm_feedback_multichoice_try_to_submit_blank() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatecbm');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit nothing.
+        $this->process_submission(array('-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$invalid);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_validation_error_expectation());
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gaveup);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation(0, false, false),
+                $this->get_contains_mc_radio_expectation(1, false, false),
+                $this->get_contains_mc_radio_expectation(2, false, false));
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 0.5);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation(),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+    }
+
+    public function test_immediatecbm_feedback_shortanswer_try_to_submit_no_certainty() {
+
+        // Create a short answer question with correct answer true.
+        $sa = test_question_maker::make_a_shortanswer_question();
+        $this->start_attempt_at_question($sa, 'immediatecbm');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit with certainty missing.
+        $this->process_submission(array('-submit' => 1, 'answer' => 'frog'));
+
+        // Verify.
+        $this->check_current_state(question_state::$invalid);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_validation_error_expectation());
+
+        // Now get it right.
+        $this->process_submission(array('-submit' => 1, 'answer' => 'frog', '-certainty' => 3));
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_does_not_contain_validation_error_expectation());
+    }
+
+    public function test_immediatecbm_feedback_multichoice_wrong_on_finish() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatecbm');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Save the wrong answer.
+        $this->process_submission(array('answer' => $wrongindex, '-certainty' => 3));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation());
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedwrong);
+        $this->check_current_mark(-3);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, false, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, false, false),
+                $this->get_contains_incorrect_expectation());
+    }
+
+    public function test_immediatecbm_cbm_truefalse_no_certainty_feedback_when_not_answered() {
+
+        // Create a true-false question with correct answer true.
+        $tf = test_question_maker::make_a_truefalse_question();
+        $this->start_attempt_at_question($tf, 'deferredcbm', 2);
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_contains_cbm_radio_expectation(1, true, false),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Finish without answering.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gaveup);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                new NoPatternExpectation('/class=\"im-feedback/'));
+    }
+}
diff --git a/question/behaviour/immediatefeedback/behaviour.php b/question/behaviour/immediatefeedback/behaviour.php
new file mode 100644 (file)
index 0000000..cf7b4c3
--- /dev/null
@@ -0,0 +1,131 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Question behaviour where the student can submit questions one at a
+ * time for immediate feedback.
+ *
+ * @package qbehaviour_immediatefeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+/**
+ * Question behaviour for immediate feedback.
+ *
+ * Each question has a submit button next to it which the student can use to
+ * submit it. Once the qustion is submitted, it is not possible for the
+ * student to change their answer any more, but the student gets full feedback
+ * straight away.
+ *
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class qbehaviour_immediatefeedback extends question_behaviour_with_save {
+    const IS_ARCHETYPAL = true;
+
+    public function required_question_definition_type() {
+        return 'question_automatically_gradable';
+    }
+
+    public function get_min_fraction() {
+        return $this->question->get_min_fraction();
+    }
+
+    public function get_expected_data() {
+        if ($this->qa->get_state()->is_active()) {
+            return array(
+                'submit' => PARAM_BOOL,
+            );
+        }
+        return parent::get_expected_data();
+    }
+
+    public function get_right_answer_summary() {
+        return $this->question->get_right_answer_summary();
+    }
+
+    public function process_action(question_attempt_pending_step $pendingstep) {
+        if ($pendingstep->has_behaviour_var('comment')) {
+            return $this->process_comment($pendingstep);
+        } else if ($pendingstep->has_behaviour_var('submit')) {
+            return $this->process_submit($pendingstep);
+        } else if ($pendingstep->has_behaviour_var('finish')) {
+            return $this->process_finish($pendingstep);
+        } else {
+            return $this->process_save($pendingstep);
+        }
+    }
+
+    public function summarise_action(question_attempt_step $step) {
+        if ($step->has_behaviour_var('comment')) {
+            return $this->summarise_manual_comment($step);
+        } else if ($step->has_behaviour_var('finish')) {
+            return $this->summarise_finish($step);
+        } else if ($step->has_behaviour_var('submit')) {
+            return $this->summarise_submit($step);
+        } else {
+            return $this->summarise_save($step);
+        }
+    }
+
+    public function process_submit(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        if (!$this->is_complete_response($pendingstep)) {
+            $pendingstep->set_state(question_state::$invalid);
+
+        } else {
+            $response = $pendingstep->get_qt_data();
+            list($fraction, $state) = $this->question->grade_response($response);
+            $pendingstep->set_fraction($fraction);
+            $pendingstep->set_state($state);
+            $pendingstep->set_new_response_summary($this->question->summarise_response($response));
+        }
+        return question_attempt::KEEP;
+    }
+
+    public function process_finish(question_attempt_pending_step $pendingstep) {
+        if ($this->qa->get_state()->is_finished()) {
+            return question_attempt::DISCARD;
+        }
+
+        $response = $this->qa->get_last_step()->get_qt_data();
+        if (!$this->question->is_gradable_response($response)) {
+            $pendingstep->set_state(question_state::$gaveup);
+
+        } else {
+            list($fraction, $state) = $this->question->grade_response($response);
+            $pendingstep->set_fraction($fraction);
+            $pendingstep->set_state($state);
+        }
+        $pendingstep->set_new_response_summary($this->question->summarise_response($response));
+        return question_attempt::KEEP;
+    }
+
+    public function process_save(question_attempt_pending_step $pendingstep) {
+        $status = parent::process_save($pendingstep);
+        if ($status == question_attempt::KEEP && $pendingstep->get_state() == question_state::$complete) {
+            $pendingstep->set_state(question_state::$todo);
+        }
+        return $status;
+    }
+}
diff --git a/question/behaviour/immediatefeedback/lang/en/qbehaviour_immediatefeedback.php b/question/behaviour/immediatefeedback/lang/en/qbehaviour_immediatefeedback.php
new file mode 100644 (file)
index 0000000..2aed0db
--- /dev/null
@@ -0,0 +1,3 @@
+<?php
+
+$string['immediatefeedback'] = 'Immediate feedback';
diff --git a/question/behaviour/immediatefeedback/renderer.php b/question/behaviour/immediatefeedback/renderer.php
new file mode 100644 (file)
index 0000000..5189587
--- /dev/null
@@ -0,0 +1,33 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Renderer for outputting parts of a question belonging to the immediate
+ * feedback behaviour.
+ *
+ * @package qbehaviour_immediatefeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+class qbehaviour_immediatefeedback_renderer extends qbehaviour_renderer {
+    public function controls(question_attempt $qa, question_display_options $options) {
+        return $this->submit_button($qa, $options);
+    }
+}
diff --git a/question/behaviour/immediatefeedback/simpletest/testwalkthrough.php b/question/behaviour/immediatefeedback/simpletest/testwalkthrough.php
new file mode 100644 (file)
index 0000000..6811eaf
--- /dev/null
@@ -0,0 +1,237 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * This file contains tests that walks a question through the immediate feedback
+ * behaviour.
+ *
+ * @package qbehaviour_immediatefeedback
+ * @copyright 2009 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../../../engine/lib.php');
+require_once(dirname(__FILE__) . '/../../../engine/simpletest/helpers.php');
+
+class qbehaviour_immediatefeedback_walkthrough_test extends qbehaviour_walkthrough_test_base {
+    public function test_immediatefeedback_feedback_multichoice_right() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatefeedback');
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Save the wrong answer.
+        $this->process_submission(array('answer' => $wrongindex));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit the right answer.
+        $this->process_submission(array('answer' => $rightindex, '-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_correct_expectation());
+        $this->assertEqual('A',
+                $this->quba->get_response_summary($this->slot));
+
+        $numsteps = $this->get_step_count();
+
+        // Now try to save again - as if the user clicked next in the quiz.
+        $this->process_submission(array('answer' => $rightindex));
+
+        // Verify.
+        $this->assertEqual($numsteps, $this->get_step_count());
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_correct_expectation());
+
+        // Finish the attempt - should not need to add a new state.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->assertEqual($numsteps, $this->get_step_count());
+        $this->check_current_state(question_state::$gradedright);
+        $this->check_current_mark(1);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($rightindex, false, true),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($rightindex + 1) % 3, false, false),
+                $this->get_contains_correct_expectation());
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 0.5);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation(),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+
+        // Now change the correct answer to the question, and regrade.
+        $mc->answers[13]->fraction = -0.33333333;
+        $mc->answers[15]->fraction = 1;
+        $this->quba->regrade_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation());
+
+        $autogradedstep = $this->get_step($this->get_step_count() - 2);
+        $this->assertWithinMargin($autogradedstep->get_fraction(), -0.3333333, 0.0000001);
+    }
+
+    public function test_immediatefeedback_feedback_multichoice_try_to_submit_blank() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatefeedback');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Submit nothing.
+        $this->process_submission(array('-submit' => 1));
+
+        // Verify.
+        $this->check_current_state(question_state::$invalid);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation(),
+                $this->get_contains_validation_error_expectation());
+        $this->assertNull($this->quba->get_response_summary($this->slot));
+    
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gaveup);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation(0, false, false),
+                $this->get_contains_mc_radio_expectation(1, false, false),
+                $this->get_contains_mc_radio_expectation(2, false, false));
+
+        // Process a manual comment.
+        $this->manual_grade('Not good enough!', 0.5);
+
+        // Verify.
+        $this->check_current_state(question_state::$mangrpartial);
+        $this->check_current_mark(0.5);
+        $this->check_current_output(
+                $this->get_contains_partcorrect_expectation(),
+                new PatternExpectation('/' . preg_quote('Not good enough!') . '/'));
+    }
+
+    public function test_immediatefeedback_feedback_multichoice_wrong_on_finish() {
+
+        // Create a true-false question with correct answer true.
+        $mc = test_question_maker::make_a_multichoice_single_question();
+        $this->start_attempt_at_question($mc, 'immediatefeedback');
+
+        // Check the initial state.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_question_text_expectation($mc),
+                $this->get_contains_mc_radio_expectation(0, true, false),
+                $this->get_contains_mc_radio_expectation(1, true, false),
+                $this->get_contains_mc_radio_expectation(2, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_feedback_expectation());
+
+        $rightindex = $this->get_mc_right_answer_index($mc);
+        $wrongindex = ($rightindex + 1) % 3;
+
+        // Save the wrong answer.
+        $this->process_submission(array('answer' => $wrongindex));
+
+        // Verify.
+        $this->check_current_state(question_state::$todo);
+        $this->check_current_mark(null);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, true, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, true, false),
+                $this->get_contains_submit_button_expectation(true),
+                $this->get_does_not_contain_correctness_expectation(),
+                $this->get_does_not_contain_feedback_expectation());
+
+        // Finish the attempt.
+        $this->quba->finish_all_questions();
+
+        // Verify.
+        $this->check_current_state(question_state::$gradedwrong);
+        $this->check_current_mark(-0.3333333);
+        $this->check_current_output(
+                $this->get_contains_mc_radio_expectation($wrongindex, false, true),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, false, false),
+                $this->get_contains_mc_radio_expectation(($wrongindex + 1) % 3, false, false),
+                $this->get_contains_incorrect_expectation());
+        $this->assertPattern('/B|C/',
+                $this->quba->get_response_summary($this->slot));
+    }
+}
diff --git a/question/behaviour/informationitem/behaviour.php b/question/behaviour/informationitem/behaviour.php
new file mode 100644 (file)
index 0000000..a5b3c4c
--- /dev/null
@@ -0,0 +1,114 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FO