Merge remote-tracking branch 'moodle/master' into MDL-20636_master_new_question_engine
authorTim Hunt <T.J.Hunt@open.ac.uk>
Mon, 6 Jun 2011 16:14:59 +0000 (17:14 +0100)
committerTim Hunt <T.J.Hunt@open.ac.uk>
Mon, 6 Jun 2011 16:14:59 +0000 (17:14 +0100)
Conflicts:
lib/db/upgrade.php
mod/quiz/lib.php

467 files changed:
admin/generator.php
admin/qtypes.php
admin/report/questioninstances/index.php
backup/moodle2/backup_qtype_plugin.class.php
backup/moodle2/backup_stepslib.php
backup/moodle2/restore_qtype_plugin.class.php
backup/moodle2/restore_stepslib.php
lang/en/question.php
lib/adminlib.php
lib/cronlib.php
lib/db/install.xml
lib/db/upgrade.php
lib/html2text.php
lib/moodlelib.php
lib/questionlib.php
lib/simpletest/testquestionlib.php
lib/simpletest/testweblib.php
local/qeupgradehelper/README.txt [new file with mode: 0755]
local/qeupgradehelper/afterupgradelib.php [new file with mode: 0755]
local/qeupgradehelper/convertquiz.php [new file with mode: 0755]
local/qeupgradehelper/cronsetup.php [new file with mode: 0755]
local/qeupgradehelper/cronsetup_form.php [new file with mode: 0755]
local/qeupgradehelper/extracttestcase.php [new file with mode: 0755]
local/qeupgradehelper/extracttestcase_form.php [new file with mode: 0755]
local/qeupgradehelper/index.php [new file with mode: 0755]
local/qeupgradehelper/lang/en/local_qeupgradehelper.php [new file with mode: 0755]
local/qeupgradehelper/lib.php [new file with mode: 0755]
local/qeupgradehelper/listpreupgrade.php [new file with mode: 0755]
local/qeupgradehelper/listtodo.php [new file with mode: 0755]
local/qeupgradehelper/listupgraded.php [new file with mode: 0755]
local/qeupgradehelper/locallib.php [new file with mode: 0755]
local/qeupgradehelper/partialupgrade-example.php [new file with mode: 0755]
local/qeupgradehelper/renderer.php [new file with mode: 0755]
local/qeupgradehelper/resetquiz.php [new file with mode: 0755]
local/qeupgradehelper/settings.php [new file with mode: 0755]
local/qeupgradehelper/styles.css [new file with mode: 0755]
local/qeupgradehelper/version.php [new file with mode: 0755]
mod/quiz/accessrules.php
mod/quiz/addrandom.php
mod/quiz/addrandomform.php
mod/quiz/attempt.php
mod/quiz/attemptlib.php
mod/quiz/backup/moodle2/backup_quiz_activity_task.class.php
mod/quiz/backup/moodle2/backup_quiz_stepslib.php
mod/quiz/backup/moodle2/restore_quiz_activity_task.class.php
mod/quiz/backup/moodle2/restore_quiz_stepslib.php
mod/quiz/comment.php
mod/quiz/db/access.php
mod/quiz/db/install.php
mod/quiz/db/install.xml
mod/quiz/db/log.php
mod/quiz/db/messages.php
mod/quiz/db/subplugins.php
mod/quiz/db/upgrade.php
mod/quiz/db/upgradelib.php [new file with mode: 0644]
mod/quiz/edit.js
mod/quiz/edit.php
mod/quiz/editlib.php
mod/quiz/grade.php
mod/quiz/index.php
mod/quiz/lang/en/quiz.php
mod/quiz/lib.php
mod/quiz/locallib.php
mod/quiz/mod_form.php
mod/quiz/module.js
mod/quiz/override_form.php
mod/quiz/overridedelete.php
mod/quiz/overrideedit.php
mod/quiz/overrides.php
mod/quiz/pix/icon.gif [deleted file]
mod/quiz/pix/icon.png [new file with mode: 0644]
mod/quiz/pix/navflagged.png [new file with mode: 0644]
mod/quiz/processattempt.php
mod/quiz/renderer.php [new file with mode: 0644]
mod/quiz/report.php
mod/quiz/report/attemptsreport.php [new file with mode: 0644]
mod/quiz/report/default.php
mod/quiz/report/grading/db/access.php [new file with mode: 0644]
mod/quiz/report/grading/gradingsettings_form.php [new file with mode: 0644]
mod/quiz/report/grading/lang/en/quiz_grading.php
mod/quiz/report/grading/report.php
mod/quiz/report/grading/styles.css [new file with mode: 0644]
mod/quiz/report/grading/version.php [new file with mode: 0644]
mod/quiz/report/overview/db/install.xml
mod/quiz/report/overview/db/upgrade.php
mod/quiz/report/overview/lang/en/quiz_overview.php
mod/quiz/report/overview/overview_table.php
mod/quiz/report/overview/overviewgraph.php
mod/quiz/report/overview/overviewsettings_form.php
mod/quiz/report/overview/report.php
mod/quiz/report/overview/version.php
mod/quiz/report/reportlib.php
mod/quiz/report/responses/lang/en/quiz_responses.php
mod/quiz/report/responses/report.php
mod/quiz/report/responses/responses_table.php
mod/quiz/report/responses/responsessettings_form.php
mod/quiz/report/responses/styles.css [deleted file]
mod/quiz/report/responses/version.php [new file with mode: 0644]
mod/quiz/report/simpletest/testreportlib.php
mod/quiz/report/statistics/cron.php
mod/quiz/report/statistics/db/access.php
mod/quiz/report/statistics/db/install.php
mod/quiz/report/statistics/db/install.xml
mod/quiz/report/statistics/db/upgrade.php
mod/quiz/report/statistics/lang/en/quiz_statistics.php
mod/quiz/report/statistics/qstats.php
mod/quiz/report/statistics/report.php
mod/quiz/report/statistics/responseanalysis.php [new file with mode: 0644]
mod/quiz/report/statistics/simpletest/mdl_question.csv
mod/quiz/report/statistics/simpletest/mdl_question_states.csv
mod/quiz/report/statistics/simpletest/test_qstats.php
mod/quiz/report/statistics/statistics_form.php
mod/quiz/report/statistics/statistics_graph.php
mod/quiz/report/statistics/statistics_question_table.php
mod/quiz/report/statistics/statistics_table.php
mod/quiz/report/statistics/version.php
mod/quiz/review.php
mod/quiz/reviewquestion.php
mod/quiz/settings.php
mod/quiz/settingslib.php
mod/quiz/simpletest/testaccessrules.php
mod/quiz/simpletest/testeditlib.php
mod/quiz/simpletest/testlib.php
mod/quiz/simpletest/testlocallib.php
mod/quiz/simpletest/testquizdisplayoptions.php [new file with mode: 0644]
mod/quiz/startattempt.php
mod/quiz/styles.css
mod/quiz/summary.php
mod/quiz/version.php
mod/quiz/view.php
question/addquestion.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/rendererbase.php [new file with mode: 0644]
question/category.php
question/category_class.php
question/category_form.php
question/edit.php
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/questionattempt.php [new file with mode: 0644]
question/engine/questionattemptstep.php [new file with mode: 0644]
question/engine/questionusage.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/testquestionbank.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/upgrade/behaviourconverters.php [new file with mode: 0644]
question/engine/upgrade/logger.php [new file with mode: 0644]
question/engine/upgrade/simpletest/helper.php [new file with mode: 0644]
question/engine/upgrade/upgradelib.php [new file with mode: 0644]
question/export.php
question/export_form.php
question/file.php [deleted file]
question/flags.js
question/format.php
question/format/README.txt
question/format/aiken/format.php
question/format/aiken/lang/en/qformat_aiken.php
question/format/blackboard/format.php
question/format/blackboard/lang/en/qformat_blackboard.php
question/format/blackboard_six/format.php
question/format/blackboard_six/lang/en/qformat_blackboard_six.php
question/format/examview/format.php
question/format/examview/lang/en/qformat_examview.php
question/format/gift/format.php
question/format/gift/lang/en/qformat_gift.php
question/format/gift/simpletest/testgiftformat.php
question/format/learnwise/format.php
question/format/learnwise/lang/en/qformat_learnwise.php
question/format/missingword/format.php
question/format/missingword/lang/en/qformat_missingword.php
question/format/multianswer/format.php
question/format/multianswer/lang/en/qformat_multianswer.php
question/format/qti_two/custommediafilter.php
question/format/qti_two/format.php
question/format/qti_two/lang/en/qformat_qti_two.php
question/format/qti_two/qt_common.php
question/format/webct/format.php
question/format/webct/lang/en/qformat_webct.php
question/format/xhtml/format.php
question/format/xhtml/lang/en/qformat_xhtml.php
question/format/xml/format.php
question/format/xml/lang/en/qformat_xml.php
question/format/xml/simpletest/testxmlformat.php [new file with mode: 0644]
question/import.php
question/import_form.php
question/move_form.php
question/preview.js [new file with mode: 0644]
question/preview.php
question/previewlib.php
question/qbank.js
question/qengine.js
question/question.php
question/simpletest/testimportexport.php
question/toggleflag.php
question/type/calculated/backup/moodle2/backup_qtype_calculated_plugin.class.php
question/type/calculated/backup/moodle2/restore_qtype_calculated_plugin.class.php
question/type/calculated/datasetdefinitions_form.php
question/type/calculated/datasetitems_form.php
question/type/calculated/db/install.xml
question/type/calculated/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/calculated/db/upgrade.php
question/type/calculated/db/upgradelib.php [new file with mode: 0644]
question/type/calculated/edit_calculated_form.php
question/type/calculated/lang/en/qtype_calculated.php
question/type/calculated/lib.php
question/type/calculated/question.php [new file with mode: 0644]
question/type/calculated/questiontype.php
question/type/calculated/renderer.php [new file with mode: 0644]
question/type/calculated/simpletest/helper.php [new file with mode: 0644]
question/type/calculated/simpletest/testquestion.php [new file with mode: 0644]
question/type/calculated/simpletest/testvariablesubstituter.php [new file with mode: 0644]
question/type/calculated/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/calculated/styles.css [new file with mode: 0644]
question/type/calculated/version.php
question/type/calculatedmulti/backup/moodle2/backup_qtype_calculatedmulti_plugin.class.php
question/type/calculatedmulti/backup/moodle2/restore_qtype_calculatedmulti_plugin.class.php
question/type/calculatedmulti/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/calculatedmulti/db/upgradelib.php [new file with mode: 0644]
question/type/calculatedmulti/edit_calculatedmulti_form.php
question/type/calculatedmulti/lang/en/qtype_calculatedmulti.php
question/type/calculatedmulti/lib.php
question/type/calculatedmulti/question.php [new file with mode: 0644]
question/type/calculatedmulti/questiontype.php
question/type/calculatedmulti/renderer.php [new file with mode: 0644]
question/type/calculatedmulti/simpletest/helper.php [new file with mode: 0644]
question/type/calculatedmulti/simpletest/testquestion.php [new file with mode: 0644]
question/type/calculatedmulti/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/calculatedmulti/styles.css [new file with mode: 0644]
question/type/calculatedmulti/version.php [new file with mode: 0644]
question/type/calculatedsimple/backup/moodle2/backup_qtype_calculatedsimple_plugin.class.php
question/type/calculatedsimple/backup/moodle2/restore_qtype_calculatedsimple_plugin.class.php
question/type/calculatedsimple/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/calculatedsimple/db/upgradelib.php [new file with mode: 0644]
question/type/calculatedsimple/edit_calculatedsimple_form.php
question/type/calculatedsimple/lang/en/qtype_calculatedsimple.php
question/type/calculatedsimple/lib.php
question/type/calculatedsimple/question.php [new file with mode: 0644]
question/type/calculatedsimple/questiontype.php
question/type/calculatedsimple/renderer.php [new file with mode: 0644]
question/type/calculatedsimple/simpletest/helper.php [new file with mode: 0644]
question/type/calculatedsimple/simpletest/testquestion.php [new file with mode: 0644]
question/type/calculatedsimple/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/calculatedsimple/styles.css [new file with mode: 0644]
question/type/calculatedsimple/version.php [new file with mode: 0644]
question/type/description/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/description/db/upgradelib.php [new file with mode: 0644]
question/type/description/edit_description_form.php
question/type/description/lang/en/qtype_description.php
question/type/description/question.html [deleted file]
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/description/version.php [new file with mode: 0644]
question/type/edit_question_form.php
question/type/essay/backup/moodle2/backup_qtype_essay_plugin.class.php
question/type/essay/backup/moodle2/restore_qtype_essay_plugin.class.php
question/type/essay/db/install.xml [new file with mode: 0644]
question/type/essay/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/essay/db/upgrade.php [new file with mode: 0644]
question/type/essay/db/upgradelib.php [new file with mode: 0644]
question/type/essay/display.html [deleted file]
question/type/essay/edit_essay_form.php
question/type/essay/lang/en/qtype_essay.php
question/type/essay/lib.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/styles.css [new file with mode: 0644]
question/type/essay/version.php
question/type/match/backup/moodle2/backup_qtype_match_plugin.class.php
question/type/match/backup/moodle2/restore_qtype_match_plugin.class.php
question/type/match/db/install.xml
question/type/match/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/match/db/upgrade.php
question/type/match/db/upgradelib.php [new file with mode: 0644]
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/lib.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/missingtype/version.php [new file with mode: 0644]
question/type/multianswer/backup/moodle2/backup_qtype_multianswer_plugin.class.php
question/type/multianswer/backup/moodle2/restore_qtype_multianswer_plugin.class.php
question/type/multianswer/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/multianswer/db/upgrade.php
question/type/multianswer/db/upgradelib.php [new file with mode: 0644]
question/type/multianswer/edit_multianswer_form.php
question/type/multianswer/lang/en/qtype_multianswer.php
question/type/multianswer/module.js [new file with mode: 0644]
question/type/multianswer/question.php [new file with mode: 0644]
question/type/multianswer/questiontype.php
question/type/multianswer/renderer.php [new file with mode: 0644]
question/type/multianswer/simpletest/helper.php [new file with mode: 0644]
question/type/multianswer/simpletest/testquestion.php [new file with mode: 0644]
question/type/multianswer/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/multianswer/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/multianswer/styles.css [new file with mode: 0644]
question/type/multianswer/version.php
question/type/multichoice/backup/moodle2/backup_qtype_multichoice_plugin.class.php
question/type/multichoice/backup/moodle2/restore_qtype_multichoice_plugin.class.php
question/type/multichoice/db/install.xml
question/type/multichoice/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/multichoice/db/upgrade.php
question/type/multichoice/db/upgradelib.php [new file with mode: 0644]
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/lib.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/backup/moodle2/backup_qtype_numerical_plugin.class.php
question/type/numerical/backup/moodle2/restore_qtype_numerical_plugin.class.php
question/type/numerical/db/install.xml
question/type/numerical/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/numerical/db/upgrade.php
question/type/numerical/db/upgradelib.php [new file with mode: 0644]
question/type/numerical/display.html [deleted file]
question/type/numerical/edit_numerical_form.php
question/type/numerical/lang/en/qtype_numerical.php
question/type/numerical/lib.php
question/type/numerical/question.php [new file with mode: 0644]
question/type/numerical/questiontype.php
question/type/numerical/renderer.php [new file with mode: 0644]
question/type/numerical/simpletest/helper.php [new file with mode: 0644]
question/type/numerical/simpletest/testanswer.php [new file with mode: 0644]
question/type/numerical/simpletest/testanswerprocessor.php [new file with mode: 0644]
question/type/numerical/simpletest/testquestion.php [new file with mode: 0644]
question/type/numerical/simpletest/testquestiontype.php
question/type/numerical/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/numerical/styles.css [new file with mode: 0644]
question/type/numerical/version.php
question/type/question.html [deleted file]
question/type/questionbase.php [new file with mode: 0644]
question/type/questiontype.php [deleted file]
question/type/questiontypebase.php [new file with mode: 0644]
question/type/random/backup/moodle2/restore_qtype_random_plugin.class.php
question/type/random/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/random/edit_random_form.php
question/type/random/lang/en/qtype_random.php
question/type/random/questiontype.php
question/type/random/simpletest/testquestiontype.php [new file with mode: 0644]
question/type/random/version.php [new file with mode: 0644]
question/type/randomsamatch/backup/moodle2/backup_qtype_randomsamatch_plugin.class.php
question/type/randomsamatch/backup/moodle2/restore_qtype_randomsamatch_plugin.class.php
question/type/randomsamatch/edit_randomsamatch_form.php
question/type/randomsamatch/lang/en/qtype_randomsamatch.php
question/type/randomsamatch/questiontype.php
question/type/randomsamatch/version.php
question/type/rendererbase.php [new file with mode: 0644]
question/type/shortanswer/backup/moodle2/backup_qtype_shortanswer_plugin.class.php
question/type/shortanswer/backup/moodle2/restore_qtype_shortanswer_plugin.class.php
question/type/shortanswer/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/shortanswer/db/upgradelib.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/lib.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/styles.css [new file with mode: 0644]
question/type/shortanswer/version.php
question/type/simpletest/testquestionbase.php [new file with mode: 0644]
question/type/simpletest/testquestiontype.php
question/type/truefalse/backup/moodle2/backup_qtype_truefalse_plugin.class.php
question/type/truefalse/backup/moodle2/restore_qtype_truefalse_plugin.class.php
question/type/truefalse/db/simpletest/testupgradelibnewqe.php [new file with mode: 0644]
question/type/truefalse/db/upgradelib.php [new file with mode: 0644]
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/lib.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/helper.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]
question/type/truefalse/simpletest/testwalkthrough.php [new file with mode: 0644]
question/type/truefalse/styles.css [new file with mode: 0644]
question/type/truefalse/version.php
question/upgrade.php
theme/base/style/question.css
theme/canvas/style/question.css
theme/standard/style/question.css

index 0e0c11e..5d642af 100644 (file)
@@ -622,7 +622,7 @@ class generator {
             require_once($CFG->libdir .'/questionlib.php');
             require_once($CFG->dirroot .'/mod/quiz/editlib.php');
             $questions = array();
-            $questionsmenu = question_type_menu();
+            $questionsmenu = question_bank::get_creatable_qtypes();
             $questiontypes = array();
             foreach ($questionsmenu as $qtype => $qname) {
                 $questiontypes[] = $qtype;
index 33a70d8..b02e6b1 100644 (file)
 <?php
-// Allows the admin to manage question types.
-
-    require_once(dirname(__FILE__) . '/../config.php');
-    require_once($CFG->libdir . '/questionlib.php');
-    require_once($CFG->libdir . '/adminlib.php');
-    require_once($CFG->libdir . '/tablelib.php');
-
-/// Check permissions.
-    require_login();
-    $systemcontext = get_context_instance(CONTEXT_SYSTEM);
-    require_capability('moodle/question:config', $systemcontext);
-    $canviewreports = has_capability('report/questioninstances:view', $systemcontext);
-
-    admin_externalpage_setup('manageqtypes');
-
-/// 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) {
-        if (!isset($counts[$qtypename])) {
-            $counts[$qtypename] = new stdClass;
-            $counts[$qtypename]->numquestions = 0;
-            $counts[$qtypename]->numhidden = 0;
-        }
-        $needed[$qtypename] = $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 ($qtype->requires_qtypes() as $reqtype) {
-            $needed[$reqtype] = true;
-        }
+
+// 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/>.
+
+/**
+ * Allows the admin to manage question types.
+ *
+ * @package    moodlecore
+ * @subpackage questionbank
+ * @copyright  2008 Tim Hunt
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+require_once(dirname(__FILE__) . '/../config.php');
+require_once($CFG->libdir . '/questionlib.php');
+require_once($CFG->libdir . '/adminlib.php');
+require_once($CFG->libdir . '/tablelib.php');
+
+// Check permissions.
+require_login();
+$systemcontext = get_context_instance(CONTEXT_SYSTEM);
+require_capability('moodle/question:config', $systemcontext);
+$canviewreports = has_capability('report/questioninstances:view', $systemcontext);
+
+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) {
+    if (!isset($counts[$qtypename])) {
+        $counts[$qtypename] = new stdClass;
+        $counts[$qtypename]->numquestions = 0;
+        $counts[$qtypename]->numhidden = 0;
     }
-    foreach ($counts as $qtypename => $count) {
-        if (!isset($QTYPES[$qtypename])) {
-            $counts['missingtype']->numquestions += $count->numquestions - $count->numhidden;
-            $counts['missingtype']->numhidden += $count->numhidden;
-        }
+    $needed[$qtypename] = $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 ($qtype->requires_qtypes() as $reqtype) {
+        $needed[$reqtype] = true;
     }
-
-/// Work of the correct sort order.
-    $config = get_config('question');
-    $sortedqtypes = array();
-    foreach ($QTYPES as $qtypename => $qtype) {
-        $sortedqtypes[$qtypename] = $qtype->local_name();
+}
+foreach ($counts as $qtypename => $count) {
+    if (!isset($qtypes[$qtypename])) {
+        $counts['missingtype']->numquestions += $count->numquestions - $count->numhidden;
+        $counts['missingtype']->numhidden += $count->numhidden;
     }
-    $sortedqtypes = question_sort_qtype_array($sortedqtypes, $config);
+}
 
-/// Process actions ============================================================
+// Work of the correct sort order.
+$config = get_config('question');
+$sortedqtypes = array();
+foreach ($qtypes as $qtypename => $qtype) {
+    $sortedqtypes[$qtypename] = $qtype->local_name();
+}
+$sortedqtypes = question_bank::sort_qtype_array($sortedqtypes, $config);
 
-    // Disable.
-    if (($disable = optional_param('disable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$disable])) {
-            print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $disable);
-        }
+// Process actions ============================================================
 
-        set_config($disable . '_disabled', 1, 'question');
-        redirect(admin_url('qtypes.php'));
+// Disable.
+if (($disable = optional_param('disable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
+    if (!isset($qtypes[$disable])) {
+        print_error('unknownquestiontype', 'question', new moodle_url('/admin/qtypes.php'), $disable);
     }
 
-    // Enable.
-    if (($enable = optional_param('enable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$enable])) {
-            print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $enable);
-        }
+    set_config($disable . '_disabled', 1, 'question');
+    redirect(admin_url('qtypes.php'));
+}
 
-        if (!$QTYPES[$enable]->menu_name()) {
-            print_error('cannotenable', 'question', admin_url('qtypes.php'), $enable);
-        }
+// Enable.
+if (($enable = optional_param('enable', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
+    if (!isset($qtypes[$enable])) {
+        print_error('unknownquestiontype', 'question', new moodle_url('/admin/qtypes.php'), $enable);
+    }
 
-        unset_config($enable . '_disabled', 'question');
-        redirect(admin_url('qtypes.php'));
+    if (!$qtypes[$enable]->menu_name()) {
+        print_error('cannotenable', 'question', new moodle_url('/admin/qtypes.php'), $enable);
     }
 
-    // Move up in order.
-    if (($up = optional_param('up', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$up])) {
-            print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $up);
-        }
+    unset_config($enable . '_disabled', 'question');
+    redirect(new moodle_url('/admin/qtypes.php'));
+}
 
-        $neworder = question_reorder_qtypes($sortedqtypes, $up, -1);
-        question_save_qtype_order($neworder, $config);
-        redirect(admin_url('qtypes.php'));
+// Move up in order.
+if (($up = optional_param('up', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
+    if (!isset($qtypes[$up])) {
+        print_error('unknownquestiontype', 'question', new moodle_url('/admin/qtypes.php'), $up);
     }
 
-    // Move down in order.
-    if (($down = optional_param('down', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        if (!isset($QTYPES[$down])) {
-            print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $down);
-        }
+    $neworder = question_reorder_qtypes($sortedqtypes, $up, -1);
+    question_save_qtype_order($neworder, $config);
+    redirect(new moodle_url('/admin/qtypes.php'));
+}
 
-        $neworder = question_reorder_qtypes($sortedqtypes, $down, +1);
-        question_save_qtype_order($neworder, $config);
-        redirect(admin_url('qtypes.php'));
+// Move down in order.
+if (($down = optional_param('down', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
+    if (!isset($qtypes[$down])) {
+        print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $down);
     }
 
-    // Delete.
-    if (($delete = optional_param('delete', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
-        // Check it is OK to delete this question type.
-        if ($delete == 'missingtype') {
-            print_error('cannotdeletemissingqtype', 'admin', admin_url('qtypes.php'));
-        }
+    $neworder = question_reorder_qtypes($sortedqtypes, $down, +1);
+    question_save_qtype_order($neworder, $config);
+    redirect(new moodle_url('/admin/qtypes.php'));
+}
 
-        if (!isset($QTYPES[$delete])) {
-            print_error('unknownquestiontype', 'question', admin_url('qtypes.php'), $delete);
-        }
+// Delete.
+if (($delete = optional_param('delete', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
+    // Check it is OK to delete this question type.
+    if ($delete == 'missingtype') {
+        print_error('cannotdeletemissingqtype', 'admin', new moodle_url('/admin/qtypes.php'));
+    }
 
-        $qtypename = $QTYPES[$delete]->local_name();
-        if ($counts[$delete]->numquestions + $counts[$delete]->numhidden > 0) {
-            print_error('cannotdeleteqtypeinuse', 'admin', admin_url('qtypes.php'), $qtypename);
-        }
+    if (!isset($qtypes[$delete])) {
+        print_error('unknownquestiontype', 'question', new moodle_url('/admin/qtypes.php'), $delete);
+    }
 
-        if ($needed[$delete] > 0) {
-            print_error('cannotdeleteqtypeneeded', 'admin', admin_url('qtypes.php'), $qtypename);
-        }
+    $qtypename = $qtypes[$delete]->local_name();
+    if ($counts[$delete]->numquestions + $counts[$delete]->numhidden > 0) {
+        print_error('cannotdeleteqtypeinuse', 'admin', new moodle_url('/admin/qtypes.php'), $qtypename);
+    }
 
-        // If not yet confirmed, display a confirmation message.
-        if (!optional_param('confirm', '', PARAM_BOOL)) {
-            $qtypename = $QTYPES[$delete]->local_name();
-            echo $OUTPUT->header();
-            echo $OUTPUT->heading(get_string('deleteqtypeareyousure', 'admin', $qtypename));
-            echo $OUTPUT->confirm(get_string('deleteqtypeareyousuremessage', 'admin', $qtypename),
-                    admin_url('qtypes.php?delete=' . $delete . '&confirm=1'),
-                    admin_url('qtypes.php'));
-            echo $OUTPUT->footer();
-            exit;
-        }
+    if ($needed[$delete] > 0) {
+        print_error('cannotdeleteqtypeneeded', 'admin', new moodle_url('/admin/qtypes.php'), $qtypename);
+    }
 
-        // Do the deletion.
+    // If not yet confirmed, display a confirmation message.
+    if (!optional_param('confirm', '', PARAM_BOOL)) {
+        $qtypename = $qtypes[$delete]->local_name();
         echo $OUTPUT->header();
-        echo $OUTPUT->heading(get_string('deletingqtype', 'admin', $qtypename));
-
-        // Delete any configuration records.
-        if (!unset_all_config_for_plugin('qtype_' . $delete)) {
-            echo $OUTPUT->notification(get_string('errordeletingconfig', 'admin', 'qtype_' . $delete));
-        }
-        unset_config($delete . '_disabled', 'question');
-        unset_config($delete . '_sortorder', 'question');
-
-        // Then the tables themselves
-        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();
-        echo $OUTPUT->box(get_string('qtypedeletefiles', 'admin', $a), 'generalbox', 'notice');
-        echo $OUTPUT->continue_button(admin_url('qtypes.php'));
+        echo $OUTPUT->heading(get_string('deleteqtypeareyousure', 'admin', $qtypename));
+        echo $OUTPUT->confirm(get_string('deleteqtypeareyousuremessage', 'admin', $qtypename),
+                new moodle_url('/admin/qtypes.php', array('delete' => $delete, 'confirm' => 1)),
+                new moodle_url('/admin/qtypes.php'));
         echo $OUTPUT->footer();
         exit;
     }
 
-    // End of process actions ==================================================
-
-/// Print the page heading.
+    // Do the deletion.
     echo $OUTPUT->header();
-    echo $OUTPUT->heading(get_string('manageqtypes', 'admin'));
-
-/// Set up the table.
-    $table = new flexible_table('qtypeadmintable');
-    $table->define_columns(array('questiontype', 'numquestions', 'version', 'requires',
-            'availableto', 'delete', 'settings'));
-    $table->define_headers(array(get_string('questiontype', 'admin'), get_string('numquestions', 'admin'),
-            get_string('version'), get_string('requires', 'admin'), get_string('availableq', 'question'),
-            get_string('delete'), get_string('settings')));
-    $table->set_attribute('id', 'qtypes');
-    $table->set_attribute('class', 'generaltable generalbox boxaligncenter boxwidthwide');
-    $table->setup();
-
-/// Add a row for each question type.
-    $createabletypes = question_type_menu();
-    foreach ($sortedqtypes as $qtypename => $localname) {
-        $qtype = $QTYPES[$qtypename];
-        $row = array();
-
-        // Question icon and name.
-        $fakequestion = new stdClass;
-        $fakequestion->qtype = $qtypename;
-        $icon = print_question_icon($fakequestion, true);
-        $row[] = $icon . ' ' . $localname;
-
-        // Number of questions of this type.
-        if ($counts[$qtypename]->numquestions + $counts[$qtypename]->numhidden > 0) {
-            if ($counts[$qtypename]->numhidden > 0) {
-                $strcount = get_string('numquestionsandhidden', 'admin', $counts[$qtypename]);
-            } else {
-                $strcount = $counts[$qtypename]->numquestions;
-            }
-            if ($canviewreports) {
-                $row[] = '<a href="' . admin_url('/report/questioninstances/index.php?qtype=' . $qtypename) .
-                        '" title="' . get_string('showdetails', 'admin') . '">' . $strcount . '</a>';
-            } else {
-                $strcount;
-            }
-        } else {
-            $row[] = 0;
-        }
+    echo $OUTPUT->heading(get_string('deletingqtype', 'admin', $qtypename));
 
-        // Question version number.
-        $version = get_config('qtype_' . $qtypename, 'version');
-        if ($version) {
-            $row[] = $version;
-        } else {
-            $row[] = '<span class="disabled">' . get_string('nodatabase', 'admin') . '</span>';
-        }
+    // Delete any configuration records.
+    if (!unset_all_config_for_plugin('qtype_' . $delete)) {
+        echo $OUTPUT->notification(get_string('errordeletingconfig', 'admin', 'qtype_' . $delete));
+    }
+    unset_config($delete . '_disabled', 'question');
+    unset_config($delete . '_sortorder', 'question');
 
-        // Other question types required by this one.
-        $requiredtypes = $qtype->requires_qtypes();
-        $strtypes = array();
-        if (!empty($requiredtypes)) {
-            foreach ($requiredtypes as $required) {
-                $strtypes[] = $QTYPES[$required]->local_name();
-            }
-            $row[] = implode(', ', $strtypes);
+    // Then the tables themselves
+    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();
+    echo $OUTPUT->box(get_string('qtypedeletefiles', 'admin', $a), 'generalbox', 'notice');
+    echo $OUTPUT->continue_button(new moodle_url('/admin/qtypes.php'));
+    echo $OUTPUT->footer();
+    exit;
+}
+
+// End of process actions ==================================================
+
+// Print the page heading.
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('manageqtypes', 'admin'));
+
+// Set up the table.
+$table = new flexible_table('qtypeadmintable');
+$table->define_columns(array('questiontype', 'numquestions', 'version', 'requires',
+        'availableto', 'delete', 'settings'));
+$table->define_headers(array(get_string('questiontype', 'admin'), get_string('numquestions', 'admin'),
+        get_string('version'), get_string('requires', 'admin'), get_string('availableq', 'question'),
+        get_string('delete'), get_string('settings')));
+$table->set_attribute('id', 'qtypes');
+$table->set_attribute('class', 'generaltable generalbox boxaligncenter boxwidthwide');
+$table->setup();
+
+// Add a row for each question type.
+$createabletypes = question_bank::get_creatable_qtypes();
+foreach ($sortedqtypes as $qtypename => $localname) {
+    $qtype = $qtypes[$qtypename];
+    $row = array();
+
+    // Question icon and name.
+    $fakequestion = new stdClass;
+    $fakequestion->qtype = $qtypename;
+    $icon = print_question_icon($fakequestion, true);
+    $row[] = $icon . ' ' . $localname;
+
+    // Number of questions of this type.
+    if ($counts[$qtypename]->numquestions + $counts[$qtypename]->numhidden > 0) {
+        if ($counts[$qtypename]->numhidden > 0) {
+            $strcount = get_string('numquestionsandhidden', 'admin', $counts[$qtypename]);
         } else {
-            $row[] = '';
+            $strcount = $counts[$qtypename]->numquestions;
         }
-
-        // Are people allowed to create new questions of this type?
-        $rowclass = '';
-        if ($qtype->menu_name()) {
-            $createable = isset($createabletypes[$qtypename]);
-            $icons = enable_disable_button($qtypename, $createable);
-            if (!$createable) {
-                $rowclass = 'dimmed_text';
-            }
+        if ($canviewreports) {
+            $row[] = '<a href="' . new moodle_url('/admin/report/questioninstances/index.php', array('qtype' => $qtypename)) .
+                    '" title="' . get_string('showdetails', 'admin') . '">' . $strcount . '</a>';
         } else {
-            $icons = '<img src="' . $OUTPUT->pix_url('spacer') . '" alt="" class="spacer" />';
+            $strcount;
         }
+    } else {
+        $row[] = 0;
+    }
 
-        // Move icons.
-        $icons .= icon_html('up', $qtypename, 't/up', get_string('up'), '');
-        $icons .= icon_html('down', $qtypename, 't/down', get_string('down'), '');
-        $row[] = $icons;
+    // Question version number.
+    $version = get_config('qtype_' . $qtypename, 'version');
+    if ($version) {
+        $row[] = $version;
+    } else {
+        $row[] = '<span class="disabled">' . get_string('nodatabase', 'admin') . '</span>';
+    }
 
-        // Delete link, if available.
-        if ($needed[$qtypename]) {
-            $row[] = '';
-        } else {
-            $row[] = '<a href="' . admin_url('qtypes.php?delete=' . $qtypename .
-                    '&amp;sesskey=' . sesskey()) . '" title="' .
-                    get_string('uninstallqtype', 'admin') . '">' . get_string('delete') . '</a>';
+    // Other question types required by this one.
+    $requiredtypes = $qtype->requires_qtypes();
+    $strtypes = array();
+    if (!empty($requiredtypes)) {
+        foreach ($requiredtypes as $required) {
+            $strtypes[] = $qtypes[$required]->local_name();
         }
+        $row[] = implode(', ', $strtypes);
+    } else {
+        $row[] = '';
+    }
 
-        // Settings link, if available.
-        $settings = admin_get_root()->locate('qtypesetting' . $qtypename);
-        if ($settings instanceof admin_externalpage) {
-            $row[] = '<a href="' . $settings->url .
-                    '">' . get_string('settings') . '</a>';
-        } else if ($settings instanceof admin_settingpage) {
-            $row[] = '<a href="' . admin_url('settings.php?section=qtypesetting' . $qtypename) .
-                    '">' . get_string('settings') . '</a>';
-        } else {
-            $row[] = '';
+    // Are people allowed to create new questions of this type?
+    $rowclass = '';
+    if ($qtype->menu_name()) {
+        $createable = isset($createabletypes[$qtypename]);
+        $icons = enable_disable_button($qtypename, $createable);
+        if (!$createable) {
+            $rowclass = 'dimmed_text';
         }
-
-        $table->add_data($row, $rowclass);
+    } else {
+        $icons = '<img src="' . $OUTPUT->pix_url('spacer') . '" alt="" class="spacer" />';
     }
 
-    $table->finish_output();
+    // Move icons.
+    $icons .= icon_html('up', $qtypename, 't/up', get_string('up'), '');
+    $icons .= icon_html('down', $qtypename, 't/down', get_string('down'), '');
+    $row[] = $icons;
 
-    echo $OUTPUT->footer();
+    // Delete link, if available.
+    if ($needed[$qtypename]) {
+        $row[] = '';
+    } else {
+        $row[] = '<a href="' . new moodle_url('/admin/qtypes.php', array('delete' => $qtypename,
+                'sesskey' => sesskey())) . '" title="' .
+                get_string('uninstallqtype', 'admin') . '">' . get_string('delete') . '</a>';
+    }
+
+    // Settings link, if available.
+    $settings = admin_get_root()->locate('qtypesetting' . $qtypename);
+    if ($settings instanceof admin_externalpage) {
+        $row[] = '<a href="' . $settings->url .
+                '">' . get_string('settings') . '</a>';
+    } else if ($settings instanceof admin_settingpage) {
+        $row[] = '<a href="' . new moodle_url('/admin/settings.php', array('section' => 'qtypesetting' . $qtypename)) .
+                '">' . get_string('settings') . '</a>';
+    } else {
+        $row[] = '';
+    }
 
-function admin_url($endbit) {
-    global $CFG;
-    return $CFG->wwwroot . '/' . $CFG->admin . '/' . $endbit;
+    $table->add_data($row, $rowclass);
 }
 
+$table->finish_output();
+
+echo $OUTPUT->footer();
+
 function enable_disable_button($qtypename, $createable) {
     if ($createable) {
         return icon_html('disable', $qtypename, 'i/hide', get_string('enabled', 'question'), get_string('disable'));
@@ -283,7 +304,7 @@ function icon_html($action, $qtypename, $icon, $alt, $tip) {
     if ($tip) {
         $tip = 'title="' . $tip . '" ';
     }
-    $html = ' <form action="' . admin_url('qtypes.php') . '" method="post"><div>';
+    $html = ' <form action="' . new moodle_url('/admin/qtypes.php') . '" method="post"><div>';
     $html .= '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
     $html .= '<input type="image" name="' . $action . '" value="' . $qtypename .
             '" src="' . $OUTPUT->pix_url($icon) . '" alt="' . $alt . '" ' . $tip . '/>';
index d690982..24299d3 100644 (file)
@@ -22,8 +22,9 @@ echo $OUTPUT->header();
 add_to_log(SITEID, "admin", "report questioninstances", "report/questioninstances/index.php?qtype=$requestedqtype", $requestedqtype);
 
 // Prepare the list of capabilities to choose from
+$qtypes = question_bank::get_all_qtypes();
 $qtypechoices = array();
-foreach ($QTYPES as $qtype) {
+foreach ($qtypes as $qtype) {
     $qtypechoices[$qtype->name()] = $qtype->local_name();
 }
 
@@ -45,7 +46,7 @@ if ($requestedqtype) {
 
     // Work out the bits needed for the SQL WHERE clauses.
     if ($requestedqtype == 'missingtype') {
-        $othertypes = array_keys($QTYPES);
+        $othertypes = array_keys($qtypes);
         $key = array_search('missingtype', $othertypes);
         unset($othertypes[$key]);
         list($sqlqtypetest, $params) = $DB->get_in_or_equal($othertypes, SQL_PARAMS_QM, '', false);
@@ -58,7 +59,8 @@ if ($requestedqtype) {
     } else {
         $sqlqtypetest = 'WHERE qtype = ?';
         $params = array($requestedqtype);
-        $title = get_string('reportforqtype', 'report_questioninstances', $QTYPES[$requestedqtype]->local_name());
+        $title = get_string('reportforqtype', 'report_questioninstances',
+                question_bank::get_qtype($requestedqtype)->local_name());
     }
 
     // Get the question counts, and all the context information, for each
index 603ac9d..5d940c5 100644 (file)
@@ -111,8 +111,7 @@ abstract class backup_qtype_plugin extends backup_plugin {
         // Define the elements
         $options = new backup_nested_element('numerical_options');
         $option = new backup_nested_element('numerical_option', array('id'), array(
-            'instructions', 'instructionsformat', 'showunits', 'unitsleft',
-            'unitgradingtype', 'unitpenalty'));
+            'showunits', 'unitsleft', 'unitgradingtype', 'unitpenalty'));
 
         // Build the tree
         $element->add_child($options);
index 4ba9120..a0acb19 100644 (file)
@@ -174,78 +174,76 @@ abstract class backup_questions_activity_structure_step extends backup_activity_
 
     /**
      * Attach to $element (usually attempts) the needed backup structures
-     * for question_states for a given question_attempt
+     * for question_usages and all the associated data.
      */
-    protected function add_question_attempts_states($element, $questionattemptname) {
+    protected function add_question_usages($element, $usageidname) {
+        global $CFG;
+        require_once($CFG->dirroot . '/question/engine/lib.php');
+
         // Check $element is one nested_backup_element
         if (! $element instanceof backup_nested_element) {
             throw new backup_step_exception('question_states_bad_parent_element', $element);
         }
-        // Check that the $questionattemptname is final element in $element
-        if (! $element->get_final_element($questionattemptname)) {
-            throw new backup_step_exception('question_states_bad_question_attempt_element', $questionattemptname);
+        if (! $element->get_final_element($usageidname)) {
+            throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
         }
 
-        // TODO: Some day we should stop these "encrypted" state->answers and
-        // TODO: delegate to qtypes plugin to proper XML writting the needed info on each question
-
-        // TODO: Should be doing here some introspection in the "answer" element, based on qtype,
-        // TODO: to know which real questions are being used (for randoms and other qtypes...)
-        // TODO: Not needed if consistency is guaranteed, but it isn't right now :-(
+        $quba = new backup_nested_element('question_usage', array('id'),
+                array('component', 'preferredbehaviour'));
 
-        // Define the elements
-        $states = new backup_nested_element('states');
-        $state = new backup_nested_element('state', array('id'), array(
-            'question', 'seq_number', 'answer', 'timestamp',
-            'event', 'grade', 'raw_grade', 'penalty'));
+        $qas = new backup_nested_element('question_attempts');
+        $qa = new backup_nested_element('question_attempt', array('id'), array(
+                'slot', 'behaviour', 'questionid', 'maxmark', 'minfraction',
+                'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
+                'timemodified'));
 
-        // Build the tree
-        $element->add_child($states);
-        $states->add_child($state);
-
-        // Set the sources
-        $state->set_source_table('question_states', array('attempt' => '../../' . $questionattemptname));
+        $steps = new backup_nested_element('steps');
+        $step = new backup_nested_element('step', array('id'), array(
+                'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
 
-        // Annotate ids
-        $state->annotate_ids('question', 'question');
-    }
-
-    /**
-     * Attach to $element (usually attempts) the needed backup structures
-     * for question_sessions for a given question_attempt
-     */
-    protected function add_question_attempts_sessions($element, $questionattemptname) {
-        // Check $element is one nested_backup_element
-        if (! $element instanceof backup_nested_element) {
-            throw new backup_step_exception('question_sessions_bad_parent_element', $element);
-        }
-        // Check that the $questionattemptname is final element in $element
-        if (! $element->get_final_element($questionattemptname)) {
-            throw new backup_step_exception('question_sessions_bad_question_attempt_element', $questionattemptname);
-        }
-
-        // Define the elements
-        $sessions = new backup_nested_element('sessions');
-        $session = new backup_nested_element('session', array('id'), array(
-            'questionid', 'newest', 'newgraded', 'sumpenalty',
-            'manualcomment', 'manualcommentformat', 'flagged'));
+        $response = new backup_nested_element('response');
+        $variable = new backup_nested_element('variable', null,  array('name', 'value'));
 
         // Build the tree
-        $element->add_child($sessions);
-        $sessions->add_child($session);
+        $element->add_child($quba);
+        $quba->add_child($qas);
+        $qas->add_child($qa);
+        $qa->add_child($steps);
+        $steps->add_child($step);
+        $step->add_child($response);
+        $response->add_child($variable);
 
         // Set the sources
-        $session->set_source_table('question_sessions', array('attemptid' => '../../' . $questionattemptname));
+        $quba->set_source_table('question_usages',
+                array('id'                => '../' . $usageidname));
+        $qa->set_source_sql('
+                SELECT *
+                FROM {question_attempts}
+                WHERE questionusageid = :questionusageid
+                ORDER BY slot',
+                array('questionusageid'   => backup::VAR_PARENTID));
+        $step->set_source_sql('
+                SELECT *
+                FROM {question_attempt_steps}
+                WHERE questionattemptid = :questionattemptid
+                ORDER BY sequencenumber',
+                array('questionattemptid' => backup::VAR_PARENTID));
+        $variable->set_source_table('question_attempt_step_data',
+                array('attemptstepid'     => backup::VAR_PARENTID));
 
         // Annotate ids
-        $session->annotate_ids('question', 'questionid');
+        $qa->annotate_ids('question', 'questionid');
+        $step->annotate_ids('user', 'userid');
 
         // Annotate files
-        // Note: question_sessions haven't files associated. On purpose manualcomment is lacking
-        // support for them, so we don't need to annotated them here.
+        $fileareas = question_engine::get_all_response_file_areas();
+        foreach ($fileareas as $filearea) {
+            $step->annotate_files('question', $filearea, 'id');
+        }
     }
 }
 
+
 /**
  * backup structure step in charge of calculating the categories to be
  * included in backup, based in the context being backuped (module/course)
@@ -1670,19 +1668,25 @@ class backup_questions_structure_step extends backup_structure_step {
 
         $question = new backup_nested_element('question', array('id'), array(
             'parent', 'name', 'questiontext', 'questiontextformat',
-            'generalfeedback', 'generalfeedbackformat', 'defaultgrade', 'penalty',
+            'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
             'qtype', 'length', 'stamp', 'version',
             'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
 
         // attach qtype plugin structure to $question element, only one allowed
         $this->add_plugin_structure('qtype', $question, false);
 
+        $qhints = new backup_nested_element('question_hints');
+
+        $qhint = new backup_nested_element('question_hint', array('id'), array(
+            'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
+
         // Build the tree
 
         $qcategories->add_child($qcategory);
         $qcategory->add_child($questions);
-
         $questions->add_child($question);
+        $question->add_child($qhints);
+        $qhints->add_child($qhint);
 
         // Define the sources
 
@@ -1696,6 +1700,13 @@ class backup_questions_structure_step extends backup_structure_step {
 
         $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
 
+        $qhint->set_source_sql('
+                SELECT *
+                FROM {question_hints}
+                WHERE questionid = :questionid
+                ORDER BY id',
+                array('questionid' => backup::VAR_PARENTID));
+
         // don't need to annotate ids nor files
         // (already done by {@link backup_annotate_all_question_files}
 
index fb97beb..97d8b85 100644 (file)
@@ -115,6 +115,23 @@ abstract class restore_qtype_plugin extends restore_plugin {
         $newquestionid   = $this->get_new_parentid('question');
         $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
 
+        // In the past, there were some sloppily rounded fractions around. Fix them up.
+        $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',
+        );
+        if (array_key_exists($data->fraction, $changes)) {
+            $data->fraction = $changes[$data->fraction];
+        }
+
         // If the question has been created by restore, we need to create its question_answers too
         if ($questioncreated) {
             // Adjust some columns
@@ -298,11 +315,14 @@ abstract class restore_qtype_plugin extends restore_plugin {
     }
 
     /**
-     * Decode one question_states for this qtype (default impl)
+     * Do any re-coding necessary in the student response.
+     * @param int $questionid the new id of the question
+     * @param int $sequencenumber of the step within the qusetion attempt.
+     * @param array the response data from the backup.
+     * @return array the recoded response.
      */
-    public function recode_state_answer($state) {
-        // By default, return answer unmodified, qtypes needing recode will override this
-        return $state->answer;
+    public function recode_response($questionid, $sequencenumber, array $response) {
+        return $response;
     }
 
     /**
index 7c66910..d37030b 100644 (file)
@@ -2310,6 +2310,17 @@ class restore_create_categories_and_questions extends restore_structure_step {
         // we have loaded qcatids there for all parsed questions
         $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
 
+        // In the past, there were some very sloppy values of penalty. Fix them.
+        if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
+            $data->penalty = 0.3333333;
+        }
+        if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
+            $data->penalty = 0.6666667;
+        }
+        if ($data->penalty >= 1) {
+            $data->penalty = 1;
+        }
+
         $data->timecreated  = $this->apply_date_offset($data->timecreated);
         $data->timemodified = $this->apply_date_offset($data->timemodified);
 
@@ -2339,6 +2350,47 @@ class restore_create_categories_and_questions extends restore_structure_step {
         // step will be in charge of restoring all the question files
     }
 
+        protected function process_question_hint($data) {
+        global $DB;
+
+        $data = (object)$data;
+        $oldid = $data->id;
+
+        // Detect if the question is created or mapped
+        $oldquestionid   = $this->get_old_parentid('question');
+        $newquestionid   = $this->get_new_parentid('question');
+        $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
+
+        // If the question has been created by restore, we need to create its question_answers too
+        if ($questioncreated) {
+            // Adjust some columns
+            $data->questionid = $newquestionid;
+            // Insert record
+            $newitemid = $DB->insert_record('question_answers', $data);
+
+        // The question existed, we need to map the existing question_answers
+        } else {
+            // Look in question_answers by answertext matching
+            $sql = 'SELECT id
+                      FROM {question_hints}
+                     WHERE questionid = ?
+                       AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
+            $params = array($newquestionid, $data->hint);
+            $newitemid = $DB->get_field_sql($sql, $params);
+            // If we haven't found the newitemid, something has gone really wrong, question in DB
+            // is missing answers, exception
+            if (!$newitemid) {
+                $info = new stdClass();
+                $info->filequestionid = $oldquestionid;
+                $info->dbquestionid   = $newquestionid;
+                $info->hint           = $data->hint;
+                throw new restore_step_exception('error_question_hint_missing_in_db', $info);
+            }
+        }
+        // Create mapping (we'll use this intensively when restoring question_states. And also answerfeedback files)
+        $this->set_mapping('question_hint', $oldid, $newitemid);
+    }
+
     protected function after_execute() {
         global $DB;
 
@@ -2461,6 +2513,8 @@ class restore_create_question_files extends restore_execution_step {
                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
                                               $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
+            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
+                                              $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
             // Add qtype dependent files
             $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
             foreach ($components as $component => $fileareas) {
@@ -2481,12 +2535,16 @@ class restore_create_question_files extends restore_execution_step {
  * (like the quiz module), to support qtype plugins, states and sessions
  */
 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
+    /** @var array question_attempt->id to qtype. */
+    protected $qtypes = array();
+    /** @var array question_attempt->id to questionid. */
+    protected $newquestionids = array();
 
     /**
      * Attach below $element (usually attempts) the needed restore_path_elements
-     * to restore question_states
+     * to restore question_usages and all they contain.
      */
-    protected function add_question_attempts_states($element, &$paths) {
+    protected function add_question_usages($element, &$paths) {
         // Check $element is restore_path_element
         if (! $element instanceof restore_path_element) {
             throw new restore_step_exception('element_must_be_restore_path_element', $element);
@@ -2495,70 +2553,114 @@ abstract class restore_questions_activity_structure_step extends restore_activit
         if (!is_array($paths)) {
             throw new restore_step_exception('paths_must_be_array', $paths);
         }
-        $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state');
+        $paths[] = new restore_path_element('question_usage',
+                $element->get_path() . '/question_usage');
+        $paths[] = new restore_path_element('question_attempt',
+                $element->get_path() . '/question_usage/question_attempts/question_attempt');
+        $paths[] = new restore_path_element('question_attempt_step',
+                $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step',
+                true);
+        $paths[] = new restore_path_element('question_attempt_step_data',
+                $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step/response/variable');
+
+        // TODO Put back code for restoring legacy 2.0 backups.
+        // $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state');
+        // $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session');
     }
 
     /**
-     * Attach below $element (usually attempts) the needed restore_path_elements
-     * to restore question_sessions
+     * Process question_usages
      */
-    protected function add_question_attempts_sessions($element, &$paths) {
-        // Check $element is restore_path_element
-        if (! $element instanceof restore_path_element) {
-            throw new restore_step_exception('element_must_be_restore_path_element', $element);
-        }
-        // Check $paths is one array
-        if (!is_array($paths)) {
-            throw new restore_step_exception('paths_must_be_array', $paths);
-        }
-        $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session');
+    protected function process_question_usage($data) {
+        global $DB;
+
+        // Clear our caches.
+        $this->qtypes = array();
+        $this->newquestionids = array();
+
+        $data = (object)$data;
+        $oldid = $data->id;
+
+        $oldcontextid = $this->get_task()->get_old_contextid();
+        $data->contextid  = $this->get_mappingid('context', $this->task->get_old_contextid());
+
+        // Everything ready, insert (no mapping needed)
+        $newitemid = $DB->insert_record('question_usages', $data);
+
+        $this->inform_new_usage_id($newitemid);
+
+        $this->set_mapping('question_usage', $oldid, $newitemid, false);
     }
 
     /**
-     * Process question_states
+     * When process_question_usage creates the new usage, it calls this method
+     * to let the activity link to the new usage. For example, the quiz uses
+     * this method to set quiz_attempts.uniqueid to the new usage id.
+     * @param integer $newusageid
+     */
+    abstract protected function inform_new_usage_id($newusageid);
+
+    /**
+     * Process question_attempts
      */
-    protected function process_question_state($data) {
+    protected function process_question_attempt($data) {
         global $DB;
 
         $data = (object)$data;
         $oldid = $data->id;
+        $question = $this->get_mapping('question', $data->questionid);
 
-        // Get complete question mapping, we'll need info
-        $question = $this->get_mapping('question', $data->question);
+        $data->questionusageid = $this->get_new_parentid('question_usage');
+        $data->questionid      = $question->newitemid;
+        $data->timemodified    = $this->apply_date_offset($data->timemodified);
 
-        // In the quiz_attempt mapping we are storing uniqueid
-        // and not id, so this gets the correct question_attempt to point to
-        $data->attempt  = $this->get_new_parentid('quiz_attempt');
-        $data->question = $question->newitemid;
-        $data->answer   = $this->restore_recode_answer($data, $question->info->qtype); // Delegate recoding of answer
-        $data->timestamp= $this->apply_date_offset($data->timestamp);
+        $newitemid = $DB->insert_record('question_attempts', $data);
 
-        // Everything ready, insert and create mapping (needed by question_sessions)
-        $newitemid = $DB->insert_record('question_states', $data);
-        $this->set_mapping('question_state', $oldid, $newitemid);
+        $this->set_mapping('question_attempt', $oldid, $newitemid);
+        $this->qtypes[$newitemid] = $question->info->qtype;
+        $this->newquestionids[$newitemid] = $data->questionid;
     }
 
     /**
-     * Process question_sessions
+     * Process question_attempt_steps
      */
-    protected function process_question_session($data) {
+    protected function process_question_attempt_step($data) {
         global $DB;
 
         $data = (object)$data;
         $oldid = $data->id;
 
-        // In the quiz_attempt mapping we are storing uniqueid
-        // and not id, so this gets the correct question_attempt to point to
-        $data->attemptid  = $this->get_new_parentid('quiz_attempt');
-        $data->questionid = $this->get_mappingid('question', $data->questionid);
-        $data->newest     = $this->get_mappingid('question_state', $data->newest);
-        $data->newgraded  = $this->get_mappingid('question_state', $data->newgraded);
+        // Pull out the response data.
+        $response = array();
+        if (!empty($data->response['variable'])) {
+            foreach ($data->response['variable'] as $variable) {
+                $response[$variable['name']] = $variable['value'];
+            }
+        }
+        unset($data->response);
 
-        // Everything ready, insert (no mapping needed)
-        $newitemid = $DB->insert_record('question_sessions', $data);
+        $data->questionattemptid = $this->get_new_parentid('question_attempt');
+        $data->timecreated = $this->apply_date_offset($data->timecreated);
+        $data->userid      = $this->get_mappingid('user', $data->userid);
 
-        // Note: question_sessions haven't files associated. On purpose manualcomment is lacking
-        // support for them, so we don't need to handle them here.
+        // Everything ready, insert and create mapping (needed by question_sessions)
+        $newitemid = $DB->insert_record('question_attempt_steps', $data);
+        $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
+
+        // Now process the response data.
+        $qtyperestorer = $this->get_qtype_restorer($this->qtypes[$data->questionattemptid]);
+        if ($qtyperestorer) {
+            $response = $qtyperestorer->recode_response(
+                    $this->newquestionids[$data->questionattemptid],
+                    $data->sequencenumber, $response);
+        }
+        foreach ($response as $name => $value) {
+            $row = new stdClass();
+            $row->attemptstepid = $newitemid;
+            $row->name = $name;
+            $row->value = $value;
+            $DB->insert_record('question_attempt_step_data', $row, false);
+        }
     }
 
     /**
@@ -2581,25 +2683,33 @@ abstract class restore_questions_activity_structure_step extends restore_activit
     }
 
     /**
-     * Given one question_states record, return the answer
-     * recoded pointing to all the restored stuff
+     * Get the restore_qtype_plugin subclass for a specific question type.
+     * @param string $qtype e.g. multichoice.
+     * @return restore_qtype_plugin instance.
      */
-    public function restore_recode_answer($state, $qtype) {
+    public function get_qtype_restorer($qtype) {
         // Build one static cache to store {@link restore_qtype_plugin}
         // while we are needing them, just to save zillions of instantiations
         // or using static stuff that will break our nice API
         static $qtypeplugins = array();
 
-        // If we haven't the corresponding restore_qtype_plugin for current qtype
-        // instantiate it and add to cache
         if (!isset($qtypeplugins[$qtype])) {
             $classname = 'restore_qtype_' . $qtype . '_plugin';
             if (class_exists($classname)) {
                 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
             } else {
-                $qtypeplugins[$qtype] = false;
+                $qtypeplugins[$qtype] = null;
             }
         }
-        return !empty($qtypeplugins[$qtype]) ? $qtypeplugins[$qtype]->recode_state_answer($state) : $state->answer;
+        return $qtypeplugins[$qtype];
+    }
+
+    protected function after_execute() {
+        parent::after_execute();
+
+        // Restore any files belonging to responses.
+        foreach (question_engine::get_all_response_file_areas() as $filearea) {
+            $this->add_related_files('question', $filearea, 'question_attempt_step');
+        }
     }
 }
index e262ae3..71c3460 100644 (file)
@@ -23,6 +23,7 @@
  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
+$string['addcategory'] = 'Add category';
 $string['adminreport'] = 'Report on possible problems in your question database.';
 $string['availableq'] = 'Available?';
 $string['badbase'] = 'Bad base before **: {$a}**';
@@ -52,7 +53,9 @@ $string['cannotwriteto'] = 'Cannot write exported questions to {$a}';
 $string['categorycurrent'] = 'Current category';
 $string['categorycurrentuse'] = 'Use this category';
 $string['categorydoesnotexist'] = 'This category does not exist';
+$string['categoryinfo'] = 'Category info';
 $string['categorymoveto'] = 'Save in category';
+$string['categorynamecantbeblank'] = 'The category name cannot be blank.';
 $string['clicktoflag'] = 'Click to flag this question';
 $string['clicktounflag'] = 'Click to un-flag this question';
 $string['contexterror'] = 'You shouldn\'t have got here if you\'re not moving a category to another context.';
@@ -76,6 +79,8 @@ $string['cwrqpfsnoprob'] = 'No question categories in your site are affected by
 $string['defaultfor'] = 'Default for {$a}';
 $string['defaultinfofor'] = 'The default category for questions shared in context \'{$a}\'.';
 $string['deletecoursecategorywithquestions'] = 'There are questions in the question bank associated with this course category. If you proceed, they will be deleted. You may wish to move them first, using the question bank interface.';
+$string['deletequestioncheck'] = 'Are you absolutely sure you want to delete \'{$a}\'?';
+$string['deletequestionscheck'] = 'Are you absolutely sure you want to delete the following questions?<br /><br />{$a}';
 $string['disabled'] = 'Disabled';
 $string['disterror'] = 'The distribution {$a} caused problems';
 $string['donothing'] = 'Don\'t copy or move files or change links.';
@@ -91,6 +96,7 @@ Each category has a context which determines where the questions in the category
 
 Categories are also used for random questions, as questions are selected from a particular category.';
 $string['editcategories_link'] = 'question/category';
+$string['editcategory'] = 'Edit category';
 $string['editingcategory'] = 'Editing a category';
 $string['editingquestion'] = 'Editing a question';
 $string['editthiscategory'] = 'Edit this category';
@@ -125,6 +131,7 @@ $string['exportquestions_help'] = 'This function enables the export of a complet
 $string['exportquestions_link'] = 'question/export';
 $string['filecantmovefrom'] = 'The questions files cannot be moved because you do not have permission to remove files from the place you are trying to move questions from.';
 $string['filecantmoveto'] = 'The question files cannot be moved or copied becuase you do not have permission to add files to the place you are trying to move the questions to.';
+$string['fileformat'] = 'File format';
 $string['filesareacourse'] = 'the course files area';
 $string['filesareasite'] = 'the site files area';
 $string['filestomove'] = 'Move / copy files to {$a}?';
@@ -136,26 +143,36 @@ $string['getcategoryfromfile'] = 'Get category from file';
 $string['getcontextfromfile'] = 'Get context from file';
 $string['changepublishstatuscat'] = '<a href="{$a->caturl}">Category "{$a->name}"</a> in course "{$a->coursename}" will have it\'s sharing status changed from <strong>{$a->changefrom} to {$a->changeto}</strong>.';
 $string['chooseqtypetoadd'] = 'Choose a question type to add';
+$string['editquestions'] = 'Edit questions';
 $string['ignorebroken'] = 'Ignore broken links';
 $string['impossiblechar'] = 'Impossible character {$a} detected as parenthesis character';
 $string['importcategory'] = 'Import category';
 $string['importcategory_help'] = 'This setting determines the category into which the imported questions will go.
 
 Certain import formats, such as GIFT and Moodle XML, may include category and context data in the import file. To make use of this data, rather than the selected category, the appropriate checkboxes should be ticked. If categories specified in the import file do not exist, they will be created.';
+$string['importerror'] = 'An error occurred during import processing';
+$string['importerrorquestion'] = 'Error importing question';
+$string['importingquestions'] = 'Importing {$a} questions from file';
+$string['importparseerror'] = 'Error(s) found parsing the import file. No questions have been imported. To import any good questions try again setting \'Stop on error\' to \'No\'';
 $string['importquestions'] = 'Import questions from file';
 $string['importquestions_help'] = 'This function enables questions in a variety of formats to be imported via text file. Note that the file must use UTF-8 encoding.';
 $string['importquestions_link'] = 'question/import';
+$string['importwrongfiletype'] = 'The type of the file you selected ({$a->actualtype}) does not match the type expected by this import format ({$a->expectedtype}).';
 $string['invalidarg'] = 'No valid arguments supplied or incorrect server configuration';
 $string['invalidcategoryidforparent'] = 'Invalid category id for parent!';
 $string['invalidcategoryidtomove'] = 'Invalid category id to move!';
 $string['invalidconfirm'] = 'Confirmation string was incorrect';
 $string['invalidcontextinhasanyquestions'] = 'Invalid context passed to question_context_has_any_questions.';
+$string['invalidpenalty'] = 'Invalid penalty';
 $string['invalidwizardpage'] = 'Incorrect or no wizard page specified!';
 $string['lastmodifiedby'] = 'Last modified by';
 $string['linkedfiledoesntexist'] = 'Linked file {$a} doesn\'t exist';
 $string['makechildof'] = 'Make child of \'{$a}\'';
 $string['maketoplevelitem'] = 'Move to top level';
+$string['matcherror'] = 'Grades do not match grade options - question skipped';
 $string['matchgrades'] = 'Match grades';
+$string['matchgradeserror'] = 'Error if grade not listed';
+$string['matchgradesnearest'] = 'Nearest grade if not listed';
 $string['matchgrades_help'] = 'Imported grades must match one of the fixed list of valid grades - 100, 90, 80, 75, 70, 66.666, 60, 50, 40, 33.333, 30, 25, 20, 16.666, 14.2857, 12.5, 11.111, 10, 5, 0 (also negative values). If not, there are two options:
 
 *  Error if grade not listed - If a question contains any grades not found in the list an error is displayed and that question will not be imported
@@ -171,6 +188,7 @@ $string['movedquestionsandcategories'] = 'Moved questions and question categorie
 $string['movelinksonly'] = 'Just change where links point to, do not move or copy files.';
 $string['moveq'] = 'Move question(s)';
 $string['moveqtoanothercontext'] = 'Move question to another context.';
+$string['moveto'] = 'Move to >>';
 $string['movingcategory'] = 'Moving category';
 $string['movingcategoryandfiles'] = 'Are you sure you want to move category {$a->name} and all child categories to context for "{$a->contextto}"?<br /> We have detected {$a->urlcount} files linked from questions in {$a->fromareaname}, would you like to copy or move these to {$a->toareaname}?';
 $string['movingcategorynofiles'] = 'Are you sure you want to move category "{$a->name}" and all child categories to context for "{$a->contextto}"?';
@@ -182,6 +200,7 @@ $string['nocate'] = 'No such category {$a}!';
 $string['nopermissionadd'] = 'You don\'t have permission to add questions here.';
 $string['nopermissionmove'] = 'You don\'t have permission to move questions from here. You must save the question in this category or save it as a new question.';
 $string['noprobs'] = 'No problems found in your question database.';
+$string['notenoughanswers'] = 'This type of question requires at least {$a} answers';
 $string['notenoughdatatoeditaquestion'] = 'Neither a question id, nor a category id and question type, was specified.';
 $string['notenoughdatatomovequestions'] = 'You need to provide the question ids of questions you want to move.';
 $string['notflagged'] = 'Not flagged';
@@ -191,6 +210,7 @@ $string['parentcategory_help'] = 'The parent category is the one in which the ne
 $string['parentcategory_link'] = 'question/category';
 $string['parenthesisinproperclose'] = 'Parenthesis before ** is not properly closed in {$a}**';
 $string['parenthesisinproperstart'] = 'Parenthesis before ** is not properly started in {$a}**';
+$string['parsingquestions'] = 'Parsing questions from import file.';
 $string['penaltyfactor'] = 'Penalty factor';
 $string['penaltyfactor_help'] = 'This setting determines what fraction of the achieved score is subtracted for each wrong response. It is only applicable if the quiz is run in adaptive mode.
 
@@ -207,12 +227,16 @@ $string['questioncategory'] = 'Question category';
 $string['questioncatsfor'] = 'Question categories for \'{$a}\'';
 $string['questiondoesnotexist'] = 'This question does not exist';
 $string['questionname'] = 'Question name';
+$string['questionno'] = 'Question {$a}';
 $string['questionsaveerror'] = 'Errors occur during saving question - ({$a})';
+$string['questionsinuse'] = '(* Questions marked by an asterisk are already in use in some quizzes. These question will not be deleted from these quizzes but only from the category list.)';
 $string['questionsmovedto'] = 'Questions still in use moved to "{$a}" in the parent course category.';
 $string['questionsrescuedfrom'] = 'Questions saved from context {$a}.';
 $string['questionsrescuedfrominfo'] = 'These questions (some of which may be hidden) were saved when context {$a} was deleted because they are still used by some quizzes or other activities.';
 $string['questiontype'] = 'Question type';
 $string['questionuse'] = 'Use question in this activity';
+$string['questionvariant'] = 'Question variant';
+$string['reviewresponse'] = 'Review response';
 $string['saveflags'] = 'Save the state of the flags';
 $string['selectacategory'] = 'Select a category:';
 $string['selectaqtypefordescription'] = 'Select a question type to see its description.';
@@ -232,3 +256,116 @@ $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['errorsavingflags'] = 'Error saving the flag state.';
+$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['includesubcategories'] = 'Also show questions from sub-categories';
+$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['parent'] = 'Parent';
+$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['questions'] = 'Questions';
+$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['showhidden'] = 'Also show old questions';
+$string['showmarkandmax'] = 'Show mark and max';
+$string['showmaxmarkonly'] = 'Show max mark only';
+$string['showquestiontext'] = 'Show question text in the question list';
+$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['withselected'] = 'With selected';
+$string['xoutofmax'] = '{$a->mark} out of {$a->max}';
+$string['yougotnright'] = 'You have correctly selected {$a->num}.';
index 49289dd..76088f6 100644 (file)
@@ -3762,6 +3762,35 @@ class admin_setting_special_calendar_weekend extends admin_setting {
 }
 
 
+/**
+ * Admin setting that allows a user to pick a behaviour.
+ *
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class admin_setting_question_behaviour extends admin_setting_configselect {
+    /**
+     * @param string $name name of config variable
+     * @param string $visiblename display name
+     * @param string $description description
+     * @param string $default default.
+     */
+    public function __construct($name, $visiblename, $description, $default) {
+        parent::__construct($name, $visiblename, $description, $default, NULL);
+    }
+
+    /**
+     * Load list of behaviours as choices
+     * @return bool true => success, false => error.
+     */
+    public function load_choices() {
+        global $CFG;
+        require_once($CFG->dirroot . '/question/engine/lib.php');
+        $this->choices = question_engine::get_archetypal_behaviours();
+        return true;
+    }
+}
+
+
 /**
  * Admin setting that allows a user to pick appropriate roles for something.
  *
@@ -4938,9 +4967,8 @@ class admin_page_manageqtypes extends admin_externalpage {
 
         $found = false;
         $textlib = textlib_get_instance();
-        require_once($CFG->libdir . '/questionlib.php');
-        global $QTYPES;
-        foreach ($QTYPES as $qtype) {
+        require_once($CFG->dirroot . '/question/engine/bank.php');
+        foreach (question_bank::get_all_qtypes() as $qtype) {
             if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
                 $found = true;
                 break;
index ea7c115..9ccfc30 100644 (file)
@@ -131,7 +131,7 @@ function cron_run() {
     plagiarism_cron();
 
     mtrace("Starting quiz reports");
-    if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
+    if ($reports = $DB->get_records_select('quiz_reports', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
         foreach ($reports as $report) {
             $cronfile = "$CFG->dirroot/mod/quiz/report/$report->name/cron.php";
             if (file_exists($cronfile)) {
@@ -143,7 +143,7 @@ function cron_run() {
                     $pre_dbqueries = $DB->perf_get_queries();
                     $pre_time      = microtime(1);
                     if ($cron_function()) {
-                        $DB->set_field('quiz_report', "lastcron", $timenow, array("id"=>$report->id));
+                        $DB->set_field('quiz_reports', "lastcron", $timenow, array("id"=>$report->id));
                     }
                     if (isset($pre_dbqueries)) {
                         mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
index 5c1397d..110e24b 100644 (file)
         <FIELD NAME="questiontext" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" PREVIOUS="name" NEXT="questiontextformat"/>
         <FIELD NAME="questiontextformat" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="false" DEFAULT="0" SEQUENCE="false" PREVIOUS="questiontext" NEXT="generalfeedback"/>
         <FIELD NAME="generalfeedback" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" COMMENT="to store the question feedback" PREVIOUS="questiontextformat" NEXT="generalfeedbackformat"/>
-        <FIELD NAME="generalfeedbackformat" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="false" DEFAULT="0" SEQUENCE="false" PREVIOUS="generalfeedback" NEXT="defaultgrade"/>
-        <FIELD NAME="defaultgrade" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="true" DEFAULT="1" SEQUENCE="false" DECIMALS="7" PREVIOUS="generalfeedbackformat" NEXT="penalty"/>
-        <FIELD NAME="penalty" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="false" DEFAULT="0.1" SEQUENCE="false" DECIMALS="7" PREVIOUS="defaultgrade" NEXT="qtype"/>
+        <FIELD NAME="generalfeedbackformat" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="false" DEFAULT="0" SEQUENCE="false" PREVIOUS="generalfeedback" NEXT="defaultmark"/>
+        <FIELD NAME="defaultmark" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="true" DEFAULT="1" SEQUENCE="false" DECIMALS="7" PREVIOUS="generalfeedbackformat" NEXT="penalty"/>
+        <FIELD NAME="penalty" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="false" DEFAULT="0.1" SEQUENCE="false" DECIMALS="7" PREVIOUS="defaultmark" NEXT="qtype"/>
         <FIELD NAME="qtype" TYPE="char" LENGTH="20" NOTNULL="true" SEQUENCE="false" PREVIOUS="penalty" NEXT="length"/>
         <FIELD NAME="length" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="1" SEQUENCE="false" PREVIOUS="qtype" NEXT="stamp"/>
         <FIELD NAME="stamp" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" PREVIOUS="length" NEXT="version"/>
         <KEY NAME="modifiedby" TYPE="foreign" FIELDS="modifiedby" REFTABLE="user" REFFIELDS="id" COMMENT="foreign (modifiedby) references user (id)" PREVIOUS="createdby"/>
       </KEYS>
     </TABLE>
-    <TABLE NAME="question_answers" COMMENT="Answers, with a fractional grade (0-1) and feedback" PREVIOUS="question" NEXT="question_attempts">
+    <TABLE NAME="question_answers" COMMENT="Answers, with a fractional grade (0-1) and feedback" PREVIOUS="question" NEXT="question_hints">
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="question"/>
         <FIELD NAME="question" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="id" NEXT="answer"/>
         <KEY NAME="question" TYPE="foreign" FIELDS="question" REFTABLE="question" REFFIELDS="id" PREVIOUS="primary"/>
       </KEYS>
     </TABLE>
-    <TABLE NAME="question_attempts" COMMENT="Student attempts. This table gets extended by the modules" PREVIOUS="question_answers" NEXT="question_states">
+    <TABLE NAME="question_hints" COMMENT="Stores the the part of the question definition that gives different feedback after each try in interactive and similar behaviours." PREVIOUS="question_answers" NEXT="question_usages">
       <FIELDS>
-        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="modulename"/>
-        <FIELD NAME="modulename" TYPE="char" LENGTH="20" NOTNULL="true" DEFAULT="quiz" SEQUENCE="false" PREVIOUS="id"/>
+        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="questionid"/>
+        <FIELD NAME="questionid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" PREVIOUS="id" NEXT="hint"/>
+        <FIELD NAME="hint" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" COMMENT="The text of the feedback to be given." PREVIOUS="questionid" NEXT="shownumcorrect"/>
+        <FIELD NAME="shownumcorrect" TYPE="int" LENGTH="1" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="Whether the feedback should include a message about how many things the student got right. This is only applicable to certain question types (for example matching or multiple choice multiple-response)." PREVIOUS="hint" NEXT="clearwrong"/>
+        <FIELD NAME="clearwrong" TYPE="int" LENGTH="1" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="Whether any wrong choices should be cleared before the next try. Whether this is applicable, and what it means, depends on the question type, as with the shownumright option." PREVIOUS="shownumcorrect" NEXT="options"/>
+        <FIELD NAME="options" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false" COMMENT="A space for any other question-type specific options." PREVIOUS="clearwrong"/>
       </FIELDS>
       <KEYS>
-        <KEY NAME="primary" TYPE="primary" FIELDS="id"/>
+        <KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="questionid"/>
+        <KEY NAME="questionid" TYPE="foreign" FIELDS="questionid" REFTABLE="question" REFFIELDS="id" PREVIOUS="primary"/>
+      </KEYS>
+    </TABLE>
+    <TABLE NAME="question_usages" COMMENT="This table's main purpose it to assign a unique id to each attempt at a set of questions by some part of Moodle. A question usage is made up of a number of question_attempts." PREVIOUS="question_hints" NEXT="question_attempts">
+      <FIELDS>
+        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="contextid"/>
+        <FIELD NAME="contextid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Every question usage must be associated with some context." PREVIOUS="id" NEXT="component"/>
+        <FIELD NAME="component" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" COMMENT="The plugin this attempt belongs to, e.g. 'mod_quiz', 'block_questionoftheday', 'filter_embedquestion'." PREVIOUS="contextid" NEXT="preferredbehaviour"/>
+        <FIELD NAME="preferredbehaviour" TYPE="char" LENGTH="32" NOTNULL="true" SEQUENCE="false" COMMENT="The archetypal behaviour that should be used for question attempts in this usage." PREVIOUS="component"/>
+      </FIELDS>
+      <KEYS>
+        <KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="contextid"/>
+        <KEY NAME="contextid" TYPE="foreign" FIELDS="contextid" REFTABLE="context" REFFIELDS="id" PREVIOUS="primary"/>
+      </KEYS>
+    </TABLE>
+    <TABLE NAME="question_attempts" COMMENT="Each row here corresponds to an attempt at one question, as part of a question_usage. A question_attempt will have some question_attempt_steps" PREVIOUS="question_usages" NEXT="question_attempt_steps">
+      <FIELDS>
+        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="questionusageid"/>
+        <FIELD NAME="questionusageid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Foreign key, references question_usages.id" PREVIOUS="id" NEXT="slot"/>
+        <FIELD NAME="slot" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Used to number the questions in one attempt sequentially." PREVIOUS="questionusageid" NEXT="behaviour"/>
+        <FIELD NAME="behaviour" TYPE="char" LENGTH="32" NOTNULL="true" SEQUENCE="false" COMMENT="The name of the question behaviour that is managing this question attempt." PREVIOUS="slot" NEXT="questionid"/>
+        <FIELD NAME="questionid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="The id of the question being attempted. Foreign key references question.id." PREVIOUS="behaviour" NEXT="variant"/>
+        <FIELD NAME="variant" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="The variant of the qusetion being used." PREVIOUS="questionid" NEXT="maxmark"/>
+        <FIELD NAME="maxmark" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" DECIMALS="7" COMMENT="The grade this question is marked out of in this attempt." PREVIOUS="variant" NEXT="minfraction"/>
+        <FIELD NAME="minfraction" TYPE="number" LENGTH="12" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" DECIMALS="7" COMMENT="Some questions can award negative marks. This indicates the most negative mark that can be awarded, on the faction scale where the maximum positive mark is 1." PREVIOUS="maxmark" NEXT="flagged"/>
+        <FIELD NAME="flagged" TYPE="int" LENGTH="1" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" COMMENT="Whether this question has been flagged within the attempt." PREVIOUS="minfraction" NEXT="questionsummary"/>
+        <FIELD NAME="questionsummary" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" COMMENT="If this question uses randomisation, it should set this field to summarise what random version the student actually saw. This is a human-readable textual summary of the student's response which might, for example, be used in a report." PREVIOUS="flagged" NEXT="rightanswer"/>
+        <FIELD NAME="rightanswer" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" COMMENT="This is a human-readable textual summary of the right answer to this question. Might be used, for example on the quiz preview, to help people who are testing the question. Or might be used in reports." PREVIOUS="questionsummary" NEXT="responsesummary"/>
+        <FIELD NAME="responsesummary" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" COMMENT="This is a textual summary of the student's response (basically what you would expect to in the Quiz responses report)." PREVIOUS="rightanswer" NEXT="timemodified"/>
+        <FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="The time this record was last changed." PREVIOUS="responsesummary"/>
+      </FIELDS>
+      <KEYS>
+        <KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="questionid"/>
+        <KEY NAME="questionid" TYPE="foreign" FIELDS="questionid" REFTABLE="question" REFFIELDS="id" PREVIOUS="primary" NEXT="questionusageid"/>
+        <KEY NAME="questionusageid" TYPE="foreign" FIELDS="questionusageid" REFTABLE="question_usages" REFFIELDS="id" PREVIOUS="questionid"/>
+      </KEYS>
+      <INDEXES>
+        <INDEX NAME="questionusageid-slot" UNIQUE="true" FIELDS="questionusageid, slot"/>
+      </INDEXES>
+    </TABLE>
+    <TABLE NAME="question_attempt_steps" COMMENT="Stores one step in in a question attempt. As well as the data here, the step will have some data in the question_attempt_step_data table." PREVIOUS="question_attempts" NEXT="question_attempt_step_data">
+      <FIELDS>
+        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="questionattemptid"/>
+        <FIELD NAME="questionattemptid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Foreign key, references question_attempt.id" PREVIOUS="id" NEXT="sequencenumber"/>
+        <FIELD NAME="sequencenumber" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Numbers the steps in a question attempt sequentially." PREVIOUS="questionattemptid" NEXT="state"/>
+        <FIELD NAME="state" TYPE="char" LENGTH="13" NOTNULL="true" SEQUENCE="false" COMMENT="One of the constants defined by the question_state class, giving the state of the question at the end of this step." PREVIOUS="sequencenumber" NEXT="fraction"/>
+        <FIELD NAME="fraction" TYPE="number" LENGTH="12" NOTNULL="false" UNSIGNED="false" SEQUENCE="false" DECIMALS="7" COMMENT="The grade for this question, when graded out of 1. Needs to be multiplied by question_attempt.maxmark to get the actual mark for the question." PREVIOUS="state" NEXT="timecreated"/>
+        <FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Time-stamp of the action that lead to this state being created." PREVIOUS="fraction" NEXT="userid"/>
+        <FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="The user whose action lead to this state being created." PREVIOUS="timecreated"/>
+      </FIELDS>
+      <KEYS>
+        <KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="questionattemptid"/>
+        <KEY NAME="questionattemptid" TYPE="foreign" FIELDS="questionattemptid" REFTABLE="question_attempts" REFFIELDS="id" PREVIOUS="primary" NEXT="userid"/>
+        <KEY NAME="userid" TYPE="foreign" FIELDS="userid" REFTABLE="user" REFFIELDS="id" PREVIOUS="questionattemptid"/>
       </KEYS>
+      <INDEXES>
+        <INDEX NAME="questionattemptid-sequencenumber" UNIQUE="true" FIELDS="questionattemptid, sequencenumber"/>
+      </INDEXES>
+    </TABLE>
+    <TABLE NAME="question_attempt_step_data" COMMENT="Each question_attempt_step has an associative array of the data that was submitted by the user in the POST request. It can also contain extra data from the question type or behaviour to avoid re-computation. The convention is that names belonging to the behaviour start with -, and cached values added to the submitted data start with _, or _-" PREVIOUS="question_attempt_steps" NEXT="question_states">
+      <FIELDS>
+        <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="attemptstepid"/>
+        <FIELD NAME="attemptstepid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="Foreign key, references question_attempt_steps.id" PREVIOUS="id" NEXT="name"/>
+        <FIELD NAME="name" TYPE="char" LENGTH="32" NOTNULL="true" SEQUENCE="false" COMMENT="The name of this bit of data." PREVIOUS="attemptstepid" NEXT="value"/>
+        <FIELD NAME="value" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" COMMENT="The corresponding value" PREVIOUS="name"/>
+      </FIELDS>
+      <KEYS>
+        <KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="attemptstepid"/>
+        <KEY NAME="attemptstepid" TYPE="foreign" FIELDS="attemptstepid" REFTABLE="question_attempt_steps" REFFIELDS="id" PREVIOUS="primary"/>
+      </KEYS>
+      <INDEXES>
+        <INDEX NAME="attemptstepid-name" UNIQUE="true" FIELDS="attemptstepid, name"/>
+      </INDEXES>
     </TABLE>
-    <TABLE NAME="question_states" COMMENT="Stores user responses to an attempt, and percentage grades" PREVIOUS="question_attempts" NEXT="question_sessions">
+    <TABLE NAME="question_states" COMMENT="Stores user responses to an attempt, and percentage grades" PREVIOUS="question_attempt_step_data" NEXT="question_sessions">
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="attempt"/>
         <FIELD NAME="attempt" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="id" NEXT="question"/>
       </KEYS>
     </TABLE>
   </TABLES>
-</XMLDB>
\ No newline at end of file
+</XMLDB>
index 2918eb1..7397a66 100644 (file)
@@ -6112,6 +6112,374 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
         upgrade_main_savepoint(true, 2011052300.02);
     }
 
+    // Question engine 2 changes (14) start here
+    if ($oldversion < 2011051200) {
+        // 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');
+
+        // Launch change of default for field penalty
+        $dbman->change_field_default($table, $field);
+
+        // quiz savepoint reached
+        upgrade_main_savepoint(true, 2011051200);
+    }
+
+    if ($oldversion < 2011051201) {
+
+        // 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');
+
+        // Launch rename field defaultmark
+        if ($dbman->field_exists($table, $field)) {
+            $dbman->rename_field($table, $field, 'defaultmark');
+        }
+
+        // quiz savepoint reached
+        upgrade_main_savepoint(true, 2011051201);
+    }
+
+    if ($oldversion < 2011051202) {
+
+        // Rename the question_attempts table to question_usages.
+        $table = new xmldb_table('question_attempts');
+        if (!$dbman->table_exists('question_usages')) {
+            $dbman->rename_table($table, 'question_usages');
+        }
+
+        // quiz savepoint reached
+        upgrade_main_savepoint(true, 2011051202);
+    }
+
+    if ($oldversion < 2011051203) {
+
+        // 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');
+
+        if ($dbman->field_exists($table, $field)) {
+            $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');
+        if (!$dbman->field_exists($table, $field)) {
+            $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');
+        if (!$dbman->field_exists($table, $field)) {
+            $field->set_attributes(XMLDB_TYPE_CHAR, '32', null,
+                    XMLDB_NOTNULL, 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_main_savepoint(true, 2011051203);
+    }
+
+    if ($oldversion < 2011051204) {
+
+        // 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_main_savepoint(true, 2011051204);
+    }
+
+    if ($oldversion < 2011051205) {
+
+        // 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_main_savepoint(true, 2011051205);
+    }
+
+    if ($oldversion < 2011051206) {
+
+        // 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_main_savepoint(true, 2011051206);
+    }
+
+    if ($oldversion < 2011051207) {
+
+        // 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_main_savepoint(true, 2011051207);
+    }
+
+    if ($oldversion < 2011051208) {
+
+        // 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_main_savepoint(true, 2011051208);
+    }
+
+    if ($oldversion < 2011051209) {
+
+        // 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_main_savepoint(true, 2011051209);
+    }
+
+    if ($oldversion < 2011051210) {
+
+        // 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_main_savepoint(true, 2011051210);
+    }
+
+    if ($oldversion < 2011051211) {
+
+        // 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_main_savepoint(true, 2011051211);
+    }
+
+    if ($oldversion < 2011051212) {
+
+        // 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_main_savepoint(true, 2011051212);
+    }
+
+    if ($oldversion < 2011051213) {
+        // Define field variant to be added to question_attempts
+        $table = new xmldb_table('question_attempts');
+        $field = new xmldb_field('variant', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED,
+                XMLDB_NOTNULL, null, 1, 'questionid');
+
+        // Launch add field component
+        if (!$dbman->field_exists($table, $field)) {
+            $dbman->add_field($table, $field);
+        }
+
+        // Main savepoint reached
+        upgrade_main_savepoint(true, 2011051213);
+    }
+    // Question engine 2 changes (14) end here
 
     return true;
 }
index 8d143bf..e2d0dff 100644 (file)
@@ -169,6 +169,7 @@ class html2text
         '/&(bull|#149|#8226);/i',                // Bullet
         '/&(pound|#163);/i',                     // Pound sign
         '/&(euro|#8364);/i',                     // Euro sign
+        '/[ ]+([\n\t])/',                        // Trailing spaces before newline or tab
         '/[ ]{2,}/'                              // Runs of spaces, post-handling
     );
 
@@ -212,6 +213,7 @@ class html2text
         '*',
         '£',
         'EUR',                                  // Euro sign. € ?
+        '\\1',                                  // Trailing spaces before newline or tab
         ' '                                     // Runs of spaces, post-handling
     );
 
index 3dee9f9..d8a0873 100644 (file)
@@ -7067,7 +7067,8 @@ function get_plugin_types($fullpaths=true) {
     static $fullinfo = null;
 
     if (!$info) {
-        $info = array('mod'           => 'mod',
+        $info = array('qtype'         => 'question/type',
+                      'mod'           => 'mod',
                       'auth'          => 'auth',
                       'enrol'         => 'enrol',
                       'message'       => 'message/output',
@@ -7085,7 +7086,7 @@ function get_plugin_types($fullpaths=true) {
                       'webservice'    => 'webservice',
                       'repository'    => 'repository',
                       'portfolio'     => 'portfolio',
-                      'qtype'         => 'question/type',
+                      'qbehaviour'    => 'question/behaviour',
                       'qformat'       => 'question/format',
                       'plagiarism'    => 'plagiarism',
                       'theme'         => 'theme'); // this is a bit hacky, themes may be in $CFG->themedir too
index dc3805f..9b47a4b 100644 (file)
@@ -1,5 +1,4 @@
 <?php
-
 // This file is part of Moodle - http://moodle.org/
 //
 // Moodle is free software: you can redistribute it and/or modify
  * 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
+ * @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
  */
 
-defined('MOODLE_INTERNAL') || die();
-
-/// CONSTANTS ///////////////////////////////////
 
-/**#@+
- * The different types of events that can create question states
- */
-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);
+defined('MOODLE_INTERNAL') || die();
 
+require_once($CFG->dirroot . '/question/engine/lib.php');
+require_once($CFG->dirroot . '/question/type/questiontypebase.php');
 
-define('QUESTION_EVENTS_CLOSED', QUESTION_EVENTCLOSE.','.
-                    QUESTION_EVENTCLOSEANDGRADE.','.
-                    QUESTION_EVENTMANUALGRADE);
 
-define('QUESTION_EVENTS_CLOSED_OR_GRADED', QUESTION_EVENTGRADE.','.
-                    QUESTION_EVENTS_CLOSED);
 
-/**#@-*/
+/// 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
@@ -103,134 +77,6 @@ define("QUESTION_NUMANS_START", 3);
  */
 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');
-
-/**#@+
- * 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 $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;
-}
-
-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);
-    }
-}
-
-/**
- * An array of question type names translated to the user's language, suitable for use when
- * creating a drop-down menu of options.
- *
- * Long-time Moodle programmers will realise that this replaces the old $QTYPE_MENU array.
- * 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.
-            $menuname = $qtype->menu_name();
-            $enabledvar = $name . '_disabled';
-            if ($menuname && !isset($config->$enabledvar)) {
-                $menuoptions[$name] = $menuname;
-            }
-        }
-
-        $menuoptions = question_sort_qtype_array($menuoptions, $config);
-    }
-    return $menuoptions;
-}
-
-/**
- * Sort an array of question type names according to the question type sort order stored in
- * config_plugins. Entries for which there is no xxx_sortorder defined will go
- * at the end, sorted according to textlib_get_instance()->asort($inarray).
- * @param $inarray an array $qtype => $QTYPES[$qtype]->local_name().
- * @param $config get_config('question'), if you happen to have it around, to save one DB query.
- * @return array the sorted version of $inarray.
- */
-function question_sort_qtype_array($inarray, $config = null) {
-    if (is_null($config)) {
-        $config = get_config('question');
-    }
-
-    $sortorder = array();
-    foreach ($inarray as $name => $notused) {
-        $sortvar = $name . '_sortorder';
-        if (isset($config->$sortvar)) {
-            $sortorder[$config->$sortvar] = $name;
-        }
-    }
-
-    ksort($sortorder);
-    $outarray = array();
-    foreach ($sortorder as $name) {
-        $outarray[$name] = $inarray[$name];
-        unset($inarray[$name]);
-    }
-    textlib_get_instance()->asort($inarray);
-    return array_merge($outarray, $inarray);
-}
-
 /**
  * Move one question type in a list of question types. If you try to move one element
  * off of the end, nothing will change.
@@ -282,93 +128,59 @@ 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 +188,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,19 +246,18 @@ 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);
     arsort($gradeoptionsfull, SORT_NUMERIC);
 
     // construct return object
-    $grades = new stdClass;
+    $grades = new stdClass();
     $grades->gradeoptions = $gradeoptions;
     $grades->gradeoptionsfull = $gradeoptionsfull;
 
@@ -463,21 +273,20 @@ function get_grade_options() {
  * @return mixed either 'fixed' value or false if erro
  */
 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
-    // if we just need an error...
-    if ($matchgrades=='error') {
-        foreach($gradeoptionsfull as $value => $option) {
+    if ($matchgrades == 'error') {
+        // if we just need an error...
+        foreach ($gradeoptionsfull as $value => $option) {
             // slightly fuzzy test, never check floats for equality :-)
-            if (abs($grade-$value)<0.00001) {
+            if (abs($grade - $value) < 0.00001) {
                 return $grade;
             }
         }
         // didn't find a match so that's an error
         return false;
-    }
-    // work out nearest value
-    else if ($matchgrades=='nearest') {
+    } else if ($matchgrades == 'nearest') {
+        // work out nearest value
         $hownear = array();
-        foreach($gradeoptionsfull as $value => $option) {
+        foreach ($gradeoptionsfull as $value => $option) {
             if ($grade==$value) {
                 return $grade;
             }
@@ -487,39 +296,49 @@ function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
         asort( $hownear, SORT_NUMERIC );
         reset( $hownear );
         return key( $hownear );
-    }
-    else {
+    } else {
         return false;
     }
 }
 
 /**
- * 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,44 +346,14 @@ 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) {
-    global $QTYPES, $DB;
+function question_delete_question($questionid) {
+    global $DB;
 
     $question = $DB->get_record_sql('
             SELECT q.*, qc.contextid
@@ -579,48 +368,37 @@ 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')) {
+    if ($children = $DB->get_records('question',
+            array('parent' => $questionid), '', 'id, qtype')) {
         foreach ($children as $child) {
             if ($child->id != $questionid) {
-                delete_question($child->id);
+                question_delete_question($child->id);
             }
         }
     }
 
     // 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
@@ -634,7 +412,8 @@ function question_delete_course($course, $feedback=true) {
     //Cache some strings
     $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-    $categoriescourse = $DB->get_records('question_categories', array('contextid'=>$coursecontext->id), 'parent', 'id, parent, name, contextid');
+    $categoriescourse = $DB->get_records('question_categories',
+            array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
 
     if ($categoriescourse) {
 
@@ -646,14 +425,15 @@ function question_delete_course($course, $feedback=true) {
 
             //Delete it completely (questions and category itself)
             //deleting questions
-            if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
+            if ($questions = $DB->get_records('question',
+                    array('category' => $category->id), '', 'id,qtype')) {
                 foreach ($questions as $question) {
-                    delete_question($question->id);
+                    question_delete_question($question->id);
                 }
-                $DB->delete_records("question", array("category"=>$category->id));
+                $DB->delete_records("question", array("category" => $category->id));
             }
             //delete the category
-            $DB->delete_records('question_categories', array('id'=>$category->id));
+            $DB->delete_records('question_categories', array('id' => $category->id));
 
             //Fill feedback
             $feedbackdata[] = array($category->name, $strcatdeleted);
@@ -661,7 +441,7 @@ function question_delete_course($course, $feedback=true) {
         //Inform about changes performed if feedback is enabled
         if ($feedback) {
             $table = new html_table();
-            $table->head = array(get_string('category','quiz'), get_string('action'));
+            $table->head = array(get_string('category', 'quiz'), get_string('action'));
             $table->data = $feedbackdata;
             echo html_writer::table($table);
         }
@@ -674,9 +454,9 @@ 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 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
  * @return boolean
  */
@@ -690,28 +470,34 @@ function question_delete_course_category($category, $newcategory, $feedback=true
         $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
 
         // Loop over question categories.
-        if ($categories = $DB->get_records('question_categories', array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
+        if ($categories = $DB->get_records('question_categories',
+                array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
             foreach ($categories as $category) {
 
                 // Deal with any questions in the category.
-                if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
+                if ($questions = $DB->get_records('question',
+                        array('category' => $category->id), '', 'id,qtype')) {
 
                     // Try to delete each question.
                     foreach ($questions as $question) {
-                        delete_question($question->id);
+                        question_delete_question($question->id);
                     }
 
-                    // Check to see if there were any questions that were kept because they are
-                    // still in use somehow, even though quizzes in courses in this category will
-                    // already have been deteted. This could happen, for example, if questions are
-                    // added to a course, and then that course is moved to another category (MDL-14802).
-                    $questionids = $DB->get_records_menu('question', array('category'=>$category->id), '', 'id,1');
+                    // Check to see if there were any questions that were kept because
+                    // they are still in use somehow, even though quizzes in courses
+                    // in this category will already have been deteted. This could
+                    // happen, for example, if questions are added to a course,
+                    // and then that course is moved to another category (MDL-14802).
+                    $questionids = $DB->get_records_menu('question',
+                            array('category'=>$category->id), '', 'id, 1');
                     if (!empty($questionids)) {
-                        if (!$rescueqcategory = question_save_from_deletion(array_keys($questionids),
-                                get_parent_contextid($context), print_context_name($context), $rescueqcategory)) {
+                        if (!$rescueqcategory = question_save_from_deletion(
+                                array_keys($questionids), get_parent_contextid($context),
+                                print_context_name($context), $rescueqcategory)) {
                             return false;
-                       }
-                       $feedbackdata[] = array($category->name, get_string('questionsmovedto', 'question', $rescueqcategory->name));
+                        }
+                        $feedbackdata[] = array($category->name,
+                            get_string('questionsmovedto', 'question', $rescueqcategory->name));
                     }
                 }
 
@@ -727,7 +513,7 @@ function question_delete_course_category($category, $newcategory, $feedback=true
         // Output feedback if requested.
         if ($feedback and $feedbackdata) {
             $table = new html_table();
-            $table->head = array(get_string('questioncategory','question'), get_string('action'));
+            $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
             $table->data = $feedbackdata;
             echo html_writer::table($table);
         }
@@ -737,12 +523,14 @@ function question_delete_course_category($category, $newcategory, $feedback=true
         if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
             return false;
         }
-        $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid'=>$context->id));
+        $DB->set_field('question_categories', 'contextid', $newcontext->id,
+                array('contextid'=>$context->id));
         if ($feedback) {
-            $a = new stdClass;
+            $a = new stdClass();
             $a->oldplace = print_context_name($context);
             $a->newplace = print_context_name($newcontext);
-            echo $OUTPUT->notification(get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
+            echo $OUTPUT->notification(
+                    get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
         }
     }
 
@@ -752,14 +540,15 @@ 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
+ * @param string $oldplace a textual description of the think being deleted,
+ *      e.g. from get_context_name
  * @param object $newcategory
  * @return mixed false on
  */
-function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
+function question_save_from_deletion($questionids, $newcontextid, $oldplace,
+        $newcategory = null) {
     global $DB;
 
     // Make a category in the parent context to move the questions to.
@@ -784,7 +573,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
@@ -798,7 +586,8 @@ function question_delete_activity($cm, $feedback=true) {
     //Cache some strings
     $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
     $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-    if ($categoriesmods = $DB->get_records('question_categories', array('contextid'=>$modcontext->id), 'parent', 'id, parent, name, contextid')){
+    if ($categoriesmods = $DB->get_records('question_categories',
+            array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
         //Sort categories following their tree (parent-child) relationships
         //this will make the feedback more readable
         $categoriesmods = sort_categories_by_tree($categoriesmods);
@@ -807,9 +596,10 @@ function question_delete_activity($cm, $feedback=true) {
 
             //Delete it completely (questions and category itself)
             //deleting questions
-            if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
+            if ($questions = $DB->get_records('question',
+                    array('category' => $category->id), '', 'id,qtype')) {
                 foreach ($questions as $question) {
-                    delete_question($question->id);
+                    question_delete_question($question->id);
                 }
                 $DB->delete_records("question", array("category"=>$category->id));
             }
@@ -822,7 +612,7 @@ function question_delete_activity($cm, $feedback=true) {
         //Inform about changes performed if feedback is enabled
         if ($feedback) {
             $table = new html_table();
-            $table->head = array(get_string('category','quiz'), get_string('action'));
+            $table->head = array(get_string('category', 'quiz'), get_string('action'));
             $table->data = $feedbackdata;
             echo html_writer::table($table);
         }
@@ -832,16 +622,16 @@ function question_delete_activity($cm, $feedback=true) {
 
 /**
  * This function should be considered private to the question bank, it is called from
- * question/editlib.php question/contextmoveq.php and a few similar places to to the work of
- * 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.
+ * question/editlib.php question/contextmoveq.php and a few similar places to to the
+ * work of 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.
  */
 function question_move_questions_to_category($questionids, $newcategoryid) {
-    global $DB, $QTYPES;
+    global $DB;
 
     $newcontextid = $DB->get_field('question_categories', 'contextid',
             array('id' => $newcategoryid));
@@ -853,16 +643,18 @@ function question_move_questions_to_category($questionids, $newcategoryid) {
              WHERE  q.id $questionidcondition", $params);
     foreach ($questions as $question) {
         if ($newcontextid != $question->contextid) {
-            $QTYPES[$question->qtype]->move_files($question->id,
-                    $question->contextid, $newcontextid);
+            question_bank::get_qtype($question->qtype)->move_files(
+                    $question->id, $question->contextid, $newcontextid);
         }
     }
 
     // Move the questions themselves.
-    $DB->set_field_select('question', 'category', $newcategoryid, "id $questionidcondition", $params);
+    $DB->set_field_select('question', 'category', $newcategoryid,
+            "id $questionidcondition", $params);
 
     // Move any subquestions belonging to them.
-    $DB->set_field_select('question', 'category', $newcategoryid, "parent $questionidcondition", $params);
+    $DB->set_field_select('question', 'category', $newcategoryid,
+            "parent $questionidcondition", $params);
 
     // TODO Deal with datasets.
 
@@ -878,26 +670,78 @@ function question_move_questions_to_category($questionids, $newcategoryid) {
  * @param integer $newcontextid the new context id.
  */
 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
-    global $DB, $QTYPES;
+    global $DB;
 
     $questionids = $DB->get_records_menu('question',
             array('category' => $categoryid), '', 'id,qtype');
     foreach ($questionids as $questionid => $qtype) {
-        $QTYPES[$qtype]->move_files($questionid, $oldcontextid, $newcontextid);
+        question_bank::get_qtype($qtype)->move_files(
+                $questionid, $oldcontextid, $newcontextid);
     }
 
     $subcatids = $DB->get_records_menu('question_categories',
             array('parent' => $categoryid), '', 'id,1');
     foreach ($subcatids as $subcatid => $notused) {
-        $DB->set_field('question_categories', 'contextid', $newcontextid, array('id' => $subcatid));
+        $DB->set_field('question_categories', 'contextid', $newcontextid,
+                array('id' => $subcatid));
         question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
     }
 }
 
 /**
- * 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.
- * See, for example, the usage in mod/quiz/attemptlib.php, and
+ * 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.
+ * @param int $variant the variant of the question to preview. If null, one will
+ *      be picked randomly.
+ * @return string the URL.
+ */
+function question_preview_url($questionid, $preferredbehaviour = null,
+        $maxmark = null, $displayoptions = null, $variant = null) {
+
+    $params = array('id' => $questionid);
+
+    if (!is_null($preferredbehaviour)) {
+        $params['behaviour'] = $preferredbehaviour;
+    }
+
+    if (!is_null($maxmark)) {
+        $params['maxmark'] = $maxmark;
+    }
+
+    if (!is_null($displayoptions)) {
+        $params['correctness']     = $displayoptions->correctness;
+        $params['marks']           = $displayoptions->marks;
+        $params['markdp']          = $displayoptions->markdp;
+        $params['feedback']        = (bool) $displayoptions->feedback;
+        $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
+        $params['rightanswer']     = (bool) $displayoptions->rightanswer;
+        $params['history']         = (bool) $displayoptions->history;
+    }
+
+    if ($variant) {
+        $params['variant'] = $variant;
+    }
+
+    return new moodle_url('/question/preview.php', $params);
+}
+
+/**
+ * @return array that can be passed as $params to the {@link popup_action} constructor.
+ */
+function question_preview_popup_params() {
+    return array(
+        'height' => 600,
+        'width' => 800,
+    );
+}
+
+/**
+ * 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. See, for example, the usage in mod/quiz/attemptlib.php, and
  * read the code below to see how the SQL is assembled. Throws exceptions on error.
  *
  * @global object
@@ -911,8 +755,9 @@ function question_move_category_to_context($categoryid, $oldcontextid, $newconte
  * @return array partially complete question objects. You need to call get_question_options
  * on them before they can be properly used.
  */
-function question_preload_questions($questionids, $extrafields = '', $join = '', $extraparams = array()) {
-    global $CFG, $DB;
+function question_preload_questions($questionids, $extrafields = '', $join = '',
+        $extraparams = array()) {
+    global $DB;
     if (empty($questionids)) {
         return array();
     }
@@ -924,12 +769,14 @@ function question_preload_questions($questionids, $extrafields = '', $join = '',
     }
     list($questionidcondition, $params) = $DB->get_in_or_equal(
             $questionids, SQL_PARAMS_NAMED, 'qid0000');
-    $sql = 'SELECT q.*' . $extrafields . ' FROM {question} q' . $join .
-            ' WHERE q.id ' . $questionidcondition;
+    $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
+            JOIN {question_categories} qc ON q.category = qc.id' .
+            $join .
+          ' WHERE q.id ' . $questionidcondition;
 
     // Load the questions
     if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
-        return 'Could not load questions.';
+        return array();
     }
 
     foreach ($questions as $question) {
@@ -963,1082 +810,75 @@ function question_load_questions($questionids, $extrafields = '', $join = '') {
 
     // Load the question type specific information
     if (!get_question_options($questions)) {
-        return 'Could not load the question options';
-    }
-
-    return $questions;
-}
-
-/**
- * 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) {
-    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 'Could not load the question options';
     }
 
-    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 . '_';
+    return $questions;
 }
 
 /**
- * Extract question id from the prefix of form element names
+ * Private function to factor common code out of get_question_options().
  *
- * @return integer      The question id
- * @param string $name  The name that contains a prefix that was
- *                      constructed with {@link question_make_name_prefix()}
+ * @param object $question the question to tidy.
+ * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
  */
-function question_get_id_from_name_prefix($name) {
-    if (!preg_match('/^resp([0-9]+)_/', $name, $matches)) {
-        return false;
+function _tidy_question($question, $loadtags = false) {
+    global $CFG;
+    if (!question_bank::is_qtype_installed($question->qtype)) {
+        $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
+                'qtype_missingtype')) . $question->questiontext;
+    }
+    question_bank::get_qtype($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 (integer) $matches[1];
 }
 
 /**
- * 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) {
+            _tidy_question($questions[$i], $loadtags);
+        }
+    } else { // deal with single question
+        _tidy_question($questions, $loadtags);
     }
-    return array((integer) $matches[1], $matches[2]);
+    return true;
 }
 
 /**
- * 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.
+ * Print the icon for the question type
  *
- * @global object
+ * @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 question_new_attempt_uniqueid($modulename='quiz') {
-    global $DB;
+function print_question_icon($question) {
+    global $OUTPUT;
+
+    $qtype = question_bank::get_qtype($question->qtype, false);
+    $namestr = $qtype->menu_name();
 
-    $attempt = new stdClass;
-    $attempt->modulename = $modulename;
-    $id = $DB->insert_record('question_attempts', $attempt);
-    return $id;
+    // 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 . '" />';
+
+    return $html;
 }
 
 /**
@@ -2054,191 +894,33 @@ 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;
-
-    $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;
+    question_bank::get_qtype($question->qtype)->save_question_options($question);
 }
 
-/**
-* 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;
@@ -2250,18 +932,23 @@ function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
         if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
             $children[$key] = $categories[$key];
             $categories[$key]->processed = true;
-            $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
+            $children = $children + sort_categories_by_tree(
+                    $categories, $children[$key]->id, $level+1);
         }
     }
-    //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
+    //If level = 1, we have finished, try to look for non processed categories
+    // (bad parent) and sort them too
     if ($level == 1) {
         foreach ($keys as $key) {
-            // If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
-            if (!isset($categories[$key]->processed) && !$DB->record_exists(
-                    'question_categories', array('contextid'=>$categories[$key]->contextid, 'id'=>$categories[$key]->parent))) {
+            // If not processed and it's a good candidate to start (because its
+            // parent doesn't exist in the course)
+            if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
+                    array('contextid' => $categories[$key]->contextid,
+                            'id' => $categories[$key]->parent))) {
                 $children[$key] = $categories[$key];
                 $categories[$key]->processed = true;
-                $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
+                $children = $children + sort_categories_by_tree(
+                        $categories, $children[$key]->id, $level + 1);
             }
         }
     }
@@ -2287,12 +974,14 @@ function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1
     // Indent the name of this category.
     $newcategories = array();
     $newcategories[$id] = $categories[$id];
-    $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) . $categories[$id]->name;
+    $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
+            $categories[$id]->name;
 
     // Recursively indent the children.
     foreach ($categories[$id]->childids as $childid) {
-        if ($childid != $nochildrenof){
-            $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1, $nochildrenof);
+        if ($childid != $nochildrenof) {
+            $newcategories = $newcategories + flatten_category_tree(
+                    $categories, $childid, $depth + 1, $nochildrenof);
         }
     }
 
@@ -2310,8 +999,9 @@ function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1
  */
 function add_indented_names($categories, $nochildrenof = -1) {
 
-    // Add an array to each category to hold the child category ids. This array will be removed
-    // again by flatten_category_tree(). It should not be used outside these two functions.
+    // Add an array to each category to hold the child category ids. This array
+    // will be removed again by flatten_category_tree(). It should not be used
+    // outside these two functions.
     foreach (array_keys($categories) as $id) {
         $categories[$id]->childids = array();
     }
@@ -2321,7 +1011,8 @@ function add_indented_names($categories, $nochildrenof = -1) {
     // categories from other courses, but not their parents.
     $toplevelcategoryids = array();
     foreach (array_keys($categories) as $id) {
-        if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) {
+        if (!empty($categories[$id]->parent) &&
+                array_key_exists($categories[$id]->parent, $categories)) {
             $categories[$categories[$id]->parent]->childids[] = $id;
         } else {
             $toplevelcategoryids[] = $id;
@@ -2331,7 +1022,8 @@ function add_indented_names($categories, $nochildrenof = -1) {
     // Flatten the tree to and add the indents.
     $newcategories = array();
     foreach ($toplevelcategoryids as $id) {
-        $newcategories = $newcategories + flatten_category_tree($categories, $id, 0, $nochildrenof);
+        $newcategories = $newcategories + flatten_category_tree(
+                $categories, $id, 0, $nochildrenof);
     }
 
     return $newcategories;
@@ -2346,32 +1038,35 @@ function add_indented_names($categories, $nochildrenof = -1) {
  * @param integer $courseid the id of the course to get the categories for.
  * @param integer $published if true, include publised categories from other courses.
  * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
- * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
+ * @param integer $selected optionally, the id of a category to be selected by
+ *      default in the dropdown.
  */
-function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "", $nochildrenof = -1) {
+function question_category_select_menu($contexts, $top = false, $currentcat = 0,
+        $selected = "", $nochildrenof = -1) {
     global $OUTPUT;
-    $categoriesarray = question_category_options($contexts, $top, $currentcat, false, $nochildrenof);
+    $categoriesarray = question_category_options($contexts, $top, $currentcat,
+            false, $nochildrenof);
     if ($selected) {
         $choose = '';
     } else {
         $choose = 'choosedots';
     }
     $options = array();
-    foreach($categoriesarray as $group=>$opts) {
-        $options[] = array($group=>$opts);
+    foreach ($categoriesarray as $group => $opts) {
+        $options[] = array($group => $opts);
     }
 
     echo html_writer::select($options, 'category', $selected, $choose);
 }
 
 /**
- * @global object
  * @param integer $contextid a context id.
  * @return object the default question category for that context, or false if none.
  */
 function question_get_default_category($contextid) {
     global $DB;
-    $category = $DB->get_records('question_categories', array('contextid' => $contextid),'id','*',0,1);
+    $category = $DB->get_records('question_categories',
+            array('contextid' => $contextid), 'id', '*', 0, 1);
     if (!empty($category)) {
         return reset($category);
     } else {
@@ -2380,44 +1075,12 @@ 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.
+ * Gets the default category in the most specific context.
+ * If no categories exist yet then default ones are created in all contexts.
+ *
+ * @param array $contexts  The context objects for this context and all parent contexts.
+ * @return object The default category - the category in the course 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
-*/
 function question_make_default_categories($contexts) {
     global $DB;
     static $preferredlevels = array(
@@ -2431,22 +1094,24 @@ function question_make_default_categories($contexts) {
     $preferredness = 0;
     // If it already exists, just return it.
     foreach ($contexts as $key => $context) {
-        if (!$exists = $DB->record_exists("question_categories", array('contextid'=>$context->id))) {
+        if (!$exists = $DB->record_exists("question_categories",
+                array('contextid' => $context->id))) {
             // Otherwise, we need to make one
-            $category = new stdClass;
+            $category = new stdClass();
             $contextname = print_context_name($context, false, true);
             $category->name = get_string('defaultfor', 'question', $contextname);
             $category->info = get_string('defaultinfofor', 'question', $contextname);
             $category->contextid = $context->id;
             $category->parent = 0;
-            $category->sortorder = 999; // By default, all categories get this number, and are sorted alphabetically.
+            // By default, all categories get this number, and are sorted alphabetically.
+            $category->sortorder = 999;
             $category->stamp = make_unique_id_code();
             $category->id = $DB->insert_record('question_categories', $category);
         } else {
             $category = question_get_default_category($context->id);
         }
-        if ($preferredlevels[$context->contextlevel] > $preferredness &&
-                has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
+        if ($preferredlevels[$context->contextlevel] > $preferredness && has_any_capability(
+                array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
             $toreturn = $category;
             $preferredness = $preferredlevels[$context->contextlevel];
         }
@@ -2462,7 +1127,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,12 +1143,12 @@ 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) {
+function question_category_options($contexts, $top = false, $currentcat = 0,
+        $popupform = false, $nochildrenof = -1) {
     global $CFG;
     $pcontexts = array();
-    foreach($contexts as $context){
+    foreach ($contexts as $context) {
         $pcontexts[] = $context->id;
     }
     $contextslist = join($pcontexts, ', ');
@@ -2493,34 +1157,36 @@ function question_category_options($contexts, $top = false, $currentcat = 0, $po
 
     $categories = question_add_context_in_key($categories);
 
-    if ($top){
+    if ($top) {
         $categories = question_add_tops($categories, $pcontexts);
     }
     $categories = add_indented_names($categories, $nochildrenof);
 
-    //sort cats out into different contexts
+    // sort cats out into different contexts
     $categoriesarray = array();
-    foreach ($pcontexts as $pcontext){
-        $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
+    foreach ($pcontexts as $pcontext) {
+        $contextstring = print_context_name(
+                get_context_instance_by_id($pcontext), true, true);
         foreach ($categories as $category) {
-            if ($category->contextid == $pcontext){
+            if ($category->contextid == $pcontext) {
                 $cid = $category->id;
-                if ($currentcat!= $cid || $currentcat==0) {
-                    $countstring = (!empty($category->questioncount))?" ($category->questioncount)":'';
+                if ($currentcat != $cid || $currentcat == 0) {
+                    $countstring = !empty($category->questioncount) ?
+                            " ($category->questioncount)" : '';
                     $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
                 }
             }
         }
     }
-    if ($popupform){
+    if ($popupform) {
         $popupcats = array();
-        foreach ($categoriesarray as $contextstring => $optgroup){
+        foreach ($categoriesarray as $contextstring => $optgroup) {
             $group = array();
-            foreach ($optgroup as $key=>$value) {
+            foreach ($optgroup as $key => $value) {
                 $key = str_replace($CFG->wwwroot, '', $key);
                 $group[$key] = $value;
             }
-            $popupcats[] = array($contextstring=>$group);
+            $popupcats[] = array($contextstring => $group);
         }
         return $popupcats;
     } else {
@@ -2528,7 +1194,7 @@ function question_category_options($contexts, $top = false, $currentcat = 0, $po
     }
 }
 
-function question_add_context_in_key($categories){
+function question_add_context_in_key($categories) {
     $newcatarray = array();
     foreach ($categories as $id => $category) {
         $category->parent = "$category->parent,$category->contextid";
@@ -2537,9 +1203,10 @@ function question_add_context_in_key($categories){
     }
     return $newcatarray;
 }
-function question_add_tops($categories, $pcontexts){
+
+function question_add_tops($categories, $pcontexts) {
     $topcats = array();
-    foreach ($pcontexts as $context){
+    foreach ($pcontexts as $context) {
         $newcat = new stdClass();
         $newcat->id = "0,$context";
         $newcat->name = get_string('top');
@@ -2552,86 +1219,74 @@ function question_add_tops($categories, $pcontexts){
 }
 
 /**
- * Returns a comma separated list of ids of the category and all subcategories
- * @global object
+ * @return array of question category ids of the category and all subcategories.
  */
 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')) {
-        foreach ($subcategories as $subcategory) {
-            $categorylist .= ','. question_categorylist($subcategory->id);
-        }
+    $subcategories = $DB->get_records('question_categories',
+            array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
+
+    $categorylist = array($categoryid);
+    foreach ($subcategories as $subcategory) {
+        $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
     }
+
     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");
-
-    $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 {
+
+    $fileformats = get_plugin_list('qformat');
+
+    $fileformatname = array();
+    require_once($CFG->dirroot . '/question/format.php');
+    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') {
-            $provided = $format_class->provide_import();
-        }
-        else {
-            $provided = $format_class->provide_export();
+
+        $classname = 'qformat_' . $fileformat;
+        $formatclass = new $classname();
+        if ($type == 'import') {
+            $provided = $formatclass->provide_import();
+        else {
+            $provided = $formatclass->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);
 
+    textlib_get_instance()->asort($fileformatnames);
     return $fileformatnames;
 }
 
 
 /**
-* Create a reasonable default file name for exporting questions from a particular
-* category.
-* @param object $course the course the questions are in.
-* @param object $category the question category.
-* @return string the filename.
-*/
+ * Create a reasonable default file name for exporting questions from a particular
+ * category.
+ * @param object $course the course the questions are in.
+ * @param object $category the question category.
+ * @return string the filename.
+ */
 function question_default_export_filename($course, $category) {
     // We build a string that is an appropriate name (questions) from the lang pack,
-    // then the corse shortname, then the question category name, then a timestamp. 
+    // then the corse shortname, then the question category name, then a timestamp.
 
     $base = clean_filename(get_string('exportfilename', 'question'));
 
@@ -2651,8 +1306,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 +1316,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){
-        if (!$this->contexttostringarray){
+    protected function generate_context_to_string_array($contexts) {
+        if (!$this->contexttostringarray) {
             $catno = 1;
-            foreach ($contexts as $context){
-                switch  ($context->contextlevel){
+            foreach ($contexts as $context) {
+                switch ($context->contextlevel) {
                     case CONTEXT_MODULE :
                         $contextstring = 'module';
                         break;
@@ -2701,51 +1357,17 @@ 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
  * @return boolean this user has the capability $cap for this question $question?
  */
-function question_has_capability_on($question, $cap, $cachecat = -1){
+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');
@@ -2756,26 +1378,28 @@ function question_has_capability_on($question, $cap, $cachecat = -1){
         $questions += $DB->get_records('question', array('category' => $cachecat));
         $cachedcat[] = $cachecat;
     }
-    if (!is_object($question)){
-        if (!isset($questions[$question])){
-            if (!$questions[$question] = $DB->get_record('question', array('id' => $question), 'id,category,createdby')) {
+    if (!is_object($question)) {
+        if (!isset($questions[$question])) {
+            if (!$questions[$question] = $DB->get_record('question',
+                    array('id' => $question), 'id,category,createdby')) {
                 print_error('questiondoesnotexist', 'question');
             }
         }
         $question = $questions[$question];
     }
-    if (!isset($categories[$question->category])){
-        if (!$categories[$question->category] = $DB->get_record('question_categories', array('id'=>$question->category))) {
+    if (!isset($categories[$question->category])) {
+        if (!$categories[$question->category] = $DB->get_record('question_categories',
+                array('id'=>$question->category))) {
             print_error('invalidcategory', 'quiz');
         }
     }
     $category = $categories[$question->category];
     $context = get_context_instance_by_id($category->contextid);
 
-    if (array_search($cap, $question_questioncaps)!== FALSE){
-        if (!has_capability('moodle/question:'.$cap.'all', $context)){
-            if ($question->createdby == $USER->id){
-                return has_capability('moodle/question:'.$cap.'