2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for exporting questions as Moodle XML.
20 * @package qformat_xml
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->libdir . '/xmlize.php');
29 if (!class_exists('qformat_default')) {
30 // This is ugly, but this class is also (ab)used by mod/lesson, which defines
31 // a different base class in mod/lesson/format.php. Thefore, we can only
32 // include the proper base class conditionally like this. (We have to include
33 // the base class like this, otherwise it breaks third-party question types.)
34 // This may be reviewd, and a better fix found one day.
35 require_once($CFG->dirroot . '/question/format.php');
40 * Importer for Moodle XML question format.
42 * See http://docs.moodle.org/en/Moodle_XML_format for a description of the format.
44 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class qformat_xml extends qformat_default {
49 public function provide_import() {
53 public function provide_export() {
57 public function mime_type() {
58 return 'application/xml';
61 // IMPORT FUNCTIONS START HERE.
64 * Translate human readable format name
65 * into internal Moodle code number
66 * @param string name format name from xml file
67 * @return int Moodle format code
69 public function trans_format($name) {
72 if ($name == 'moodle_auto_format') {
74 } else if ($name == 'html') {
76 } else if ($name == 'plain_text') {
78 } else if ($name == 'wiki_like') {
80 } else if ($name == 'markdown') {
81 return FORMAT_MARKDOWN;
83 debugging("Unrecognised text format '{$name}' in the import file. Assuming 'html'.");
89 * Translate human readable single answer option
90 * to internal code number
91 * @param string name true/false
92 * @return int internal code number
94 public function trans_single($name) {
96 if ($name == "false" || !$name) {
104 * process text string from xml file
105 * @param array $text bit of xml tree after ['text']
106 * @return string processed text.
108 public function import_text($text) {
109 // Quick sanity check.
113 $data = $text[0]['#'];
118 * return the value of a node, given a path to the node
119 * if it doesn't exist return the default value
120 * @param array xml data to read
121 * @param array path path to node expressed as array
122 * @param mixed default
123 * @param bool istext process as text
124 * @param string error if set value must exist, return false and issue message if not
125 * @return mixed value
127 public function getpath($xml, $path, $default, $istext=false, $error='') {
128 foreach ($path as $index) {
129 if (!isset($xml[$index])) {
130 if (!empty($error)) {
131 $this->error($error);
142 if (!is_string($xml)) {
143 $this->error(get_string('invalidxml', 'qformat_xml'));
151 public function import_text_with_files($data, $path, $defaultvalue = '', $defaultformat = 'html') {
153 $field['text'] = $this->getpath($data,
154 array_merge($path, array('#', 'text', 0, '#')), $defaultvalue, true);
155 $field['format'] = $this->trans_format($this->getpath($data,
156 array_merge($path, array('@', 'format')), $defaultformat));
157 $itemid = $this->import_files_as_draft($this->getpath($data,
158 array_merge($path, array('#', 'file')), array(), false));
159 if (!empty($itemid)) {
160 $field['itemid'] = $itemid;
165 public function import_files_as_draft($xml) {
170 $fs = get_file_storage();
171 $itemid = file_get_unused_draft_itemid();
172 $filepaths = array();
173 foreach ($xml as $file) {
174 $filename = $this->getpath($file, array('@', 'name'), '', true);
175 $filepath = $this->getpath($file, array('@', 'path'), '/', true);
176 $fullpath = $filepath . $filename;
177 if (in_array($fullpath, $filepaths)) {
178 debugging('Duplicate file in XML: ' . $fullpath, DEBUG_DEVELOPER);
182 'contextid' => context_user::instance($USER->id)->id,
183 'component' => 'user',
184 'filearea' => 'draft',
186 'filepath' => $filepath,
187 'filename' => $filename,
189 $fs->create_file_from_string($filerecord, base64_decode($file['#']));
190 $filepaths[] = $fullpath;
196 * import parts of question common to all types
197 * @param $question array question question array from xml tree
198 * @return object question object
200 public function import_headers($question) {
203 // This routine initialises the question object.
204 $qo = $this->defaultquestion();
207 $qo->name = $this->clean_question_name($this->getpath($question,
208 array('#', 'name', 0, '#', 'text', 0, '#'), '', true,
209 get_string('xmlimportnoname', 'qformat_xml')));
210 $questiontext = $this->import_text_with_files($question,
211 array('#', 'questiontext', 0));
212 $qo->questiontext = $questiontext['text'];
213 $qo->questiontextformat = $questiontext['format'];
214 if (!empty($questiontext['itemid'])) {
215 $qo->questiontextitemid = $questiontext['itemid'];
217 // Backwards compatibility, deal with the old image tag.
218 $filedata = $this->getpath($question, array('#', 'image_base64', '0', '#'), null, false);
219 $filename = $this->getpath($question, array('#', 'image', '0', '#'), null, false);
220 if ($filedata && $filename) {
221 $fs = get_file_storage();
222 if (empty($qo->questiontextitemid)) {
223 $qo->questiontextitemid = file_get_unused_draft_itemid();
225 $filename = clean_param(str_replace('/', '_', $filename), PARAM_FILE);
227 'contextid' => context_user::instance($USER->id)->id,
228 'component' => 'user',
229 'filearea' => 'draft',
230 'itemid' => $qo->questiontextitemid,
232 'filename' => $filename,
234 $fs->create_file_from_string($filerecord, base64_decode($filedata));
235 $qo->questiontext .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />';
238 // Restore files in generalfeedback.
239 $generalfeedback = $this->import_text_with_files($question,
240 array('#', 'generalfeedback', 0), $qo->generalfeedback, $this->get_format($qo->questiontextformat));
241 $qo->generalfeedback = $generalfeedback['text'];
242 $qo->generalfeedbackformat = $generalfeedback['format'];
243 if (!empty($generalfeedback['itemid'])) {
244 $qo->generalfeedbackitemid = $generalfeedback['itemid'];
247 $qo->defaultmark = $this->getpath($question,
248 array('#', 'defaultgrade', 0, '#'), $qo->defaultmark);
249 $qo->penalty = $this->getpath($question,
250 array('#', 'penalty', 0, '#'), $qo->penalty);
252 // Fix problematic rounding from old files.
253 if (abs($qo->penalty - 0.3333333) < 0.005) {
254 $qo->penalty = 0.3333333;
257 // Read the question tags.
258 if (!empty($CFG->usetags) && array_key_exists('tags', $question['#'])
259 && !empty($question['#']['tags'][0]['#']['tag'])) {
260 require_once($CFG->dirroot.'/tag/lib.php');
262 foreach ($question['#']['tags'][0]['#']['tag'] as $tagdata) {
263 $qo->tags[] = $this->getpath($tagdata, array('#', 'text', 0, '#'), '', true);
271 * Import the common parts of a single answer
272 * @param array answer xml tree for single answer
273 * @param bool $withanswerfiles if true, the answers are HTML (or $defaultformat)
274 * and so may contain files, otherwise the answers are plain text.
275 * @param array Default text format for the feedback, and the answers if $withanswerfiles
277 * @return object answer object
279 public function import_answer($answer, $withanswerfiles = false, $defaultformat = 'html') {
280 $ans = new stdClass();
282 if ($withanswerfiles) {
283 $ans->answer = $this->import_text_with_files($answer, array(), '', $defaultformat);
285 $ans->answer = array();
286 $ans->answer['text'] = $this->getpath($answer, array('#', 'text', 0, '#'), '', true);
287 $ans->answer['format'] = FORMAT_PLAIN;
290 $ans->feedback = $this->import_text_with_files($answer, array('#', 'feedback', 0), '', $defaultformat);
292 $ans->fraction = $this->getpath($answer, array('@', 'fraction'), 0) / 100;
298 * Import the common overall feedback fields.
299 * @param object $question the part of the XML relating to this question.
300 * @param object $qo the question data to add the fields to.
301 * @param bool $withshownumpartscorrect include the shownumcorrect field.
303 public function import_combined_feedback($qo, $questionxml, $withshownumpartscorrect = false) {
304 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
305 foreach ($fields as $field) {
306 $qo->$field = $this->import_text_with_files($questionxml,
307 array('#', $field, 0), '', $this->get_format($qo->questiontextformat));
310 if ($withshownumpartscorrect) {
311 $qo->shownumcorrect = array_key_exists('shownumcorrect', $questionxml['#']);
313 // Backwards compatibility.
314 if (array_key_exists('correctresponsesfeedback', $questionxml['#'])) {
315 $qo->shownumcorrect = $this->trans_single($this->getpath($questionxml,
316 array('#', 'correctresponsesfeedback', 0, '#'), 1));
322 * Import a question hint
323 * @param array $hintxml hint xml fragment.
324 * @param string $defaultformat the text format to assume for hints that do not specify.
325 * @return object hint for storing in the database.
327 public function import_hint($hintxml, $defaultformat) {
328 $hint = new stdClass();
329 if (array_key_exists('hintcontent', $hintxml['#'])) {
330 // Backwards compatibility.
332 $hint->hint = $this->import_text_with_files($hintxml,
333 array('#', 'hintcontent', 0), '', $defaultformat);
335 $hint->shownumcorrect = $this->getpath($hintxml,
336 array('#', 'statenumberofcorrectresponses', 0, '#'), 0);
337 $hint->clearwrong = $this->getpath($hintxml,
338 array('#', 'clearincorrectresponses', 0, '#'), 0);
339 $hint->options = $this->getpath($hintxml,
340 array('#', 'showfeedbacktoresponses', 0, '#'), 0);
344 $hint->hint = $this->import_text_with_files($hintxml, array(), '', $defaultformat);
345 $hint->shownumcorrect = array_key_exists('shownumcorrect', $hintxml['#']);
346 $hint->clearwrong = array_key_exists('clearwrong', $hintxml['#']);
347 $hint->options = $this->getpath($hintxml, array('#', 'options', 0, '#'), '', true);
353 * Import all the question hints
355 * @param object $qo the question data that is being constructed.
356 * @param array $questionxml The xml representing the question.
357 * @param bool $withparts whether the extra fields relating to parts should be imported.
358 * @param bool $withoptions whether the extra options field should be imported.
359 * @param string $defaultformat the text format to assume for hints that do not specify.
360 * @return array of objects representing the hints in the file.
362 public function import_hints($qo, $questionxml, $withparts = false,
363 $withoptions = false, $defaultformat = 'html') {
364 if (!isset($questionxml['#']['hint'])) {
368 foreach ($questionxml['#']['hint'] as $hintxml) {
369 $hint = $this->import_hint($hintxml, $defaultformat);
370 $qo->hint[] = $hint->hint;
373 $qo->hintshownumcorrect[] = $hint->shownumcorrect;
374 $qo->hintclearwrong[] = $hint->clearwrong;
378 $qo->hintoptions[] = $hint->options;
384 * Import files from a node in the XML.
385 * @param array $xml an array of <file> nodes from the the parsed XML.
386 * @return array of things representing files - in the form that save_question expects.
388 public function import_files($xml) {
390 foreach ($xml as $file) {
391 $data = new stdClass();
392 $data->content = $file['#'];
393 $data->encoding = $file['@']['encoding'];
394 $data->name = $file['@']['name'];
401 * import multiple choice question
402 * @param array question question array from xml tree
403 * @return object question object
405 public function import_multichoice($question) {
407 $qo = $this->import_headers($question);
409 // Header parts particular to multichoice.
410 $qo->qtype = 'multichoice';
411 $single = $this->getpath($question, array('#', 'single', 0, '#'), 'true');
412 $qo->single = $this->trans_single($single);
413 $shuffleanswers = $this->getpath($question,
414 array('#', 'shuffleanswers', 0, '#'), 'false');
415 $qo->answernumbering = $this->getpath($question,
416 array('#', 'answernumbering', 0, '#'), 'abc');
417 $qo->shuffleanswers = $this->trans_single($shuffleanswers);
419 // There was a time on the 1.8 branch when it could output an empty
420 // answernumbering tag, so fix up any found.
421 if (empty($qo->answernumbering)) {
422 $qo->answernumbering = 'abc';
425 // Run through the answers.
426 $answers = $question['#']['answer'];
428 foreach ($answers as $answer) {
429 $ans = $this->import_answer($answer, true, $this->get_format($qo->questiontextformat));
430 $qo->answer[$acount] = $ans->answer;
431 $qo->fraction[$acount] = $ans->fraction;
432 $qo->feedback[$acount] = $ans->feedback;
436 $this->import_combined_feedback($qo, $question, true);
437 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat));
443 * Import cloze type question
444 * @param array question question array from xml tree
445 * @return object question object
447 public function import_multianswer($question) {
449 question_bank::get_qtype('multianswer');
451 $questiontext = $this->import_text_with_files($question,
452 array('#', 'questiontext', 0));
453 $qo = qtype_multianswer_extract_question($questiontext);
455 // Header parts particular to multianswer.
456 $qo->qtype = 'multianswer';
458 // Only set the course if the data is available.
459 if (isset($this->course)) {
460 $qo->course = $this->course;
463 $qo->name = $this->clean_question_name($this->import_text($question['#']['name'][0]['#']['text']));
464 $qo->questiontextformat = $questiontext['format'];
465 $qo->questiontext = $qo->questiontext['text'];
466 if (!empty($questiontext['itemid'])) {
467 $qo->questiontextitemid = $questiontext['itemid'];
470 // Backwards compatibility, deal with the old image tag.
471 $filedata = $this->getpath($question, array('#', 'image_base64', '0', '#'), null, false);
472 $filename = $this->getpath($question, array('#', 'image', '0', '#'), null, false);
473 if ($filedata && $filename) {
474 $fs = get_file_storage();
475 if (empty($qo->questiontextitemid)) {
476 $qo->questiontextitemid = file_get_unused_draft_itemid();
478 $filename = clean_param(str_replace('/', '_', $filename), PARAM_FILE);
480 'contextid' => context_user::instance($USER->id)->id,
481 'component' => 'user',
482 'filearea' => 'draft',
483 'itemid' => $qo->questiontextitemid,
485 'filename' => $filename,
487 $fs->create_file_from_string($filerecord, base64_decode($filedata));
488 $qo->questiontext .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />';
491 // Restore files in generalfeedback.
492 $generalfeedback = $this->import_text_with_files($question,
493 array('#', 'generalfeedback', 0), $qo->generalfeedback, $this->get_format($qo->questiontextformat));
494 $qo->generalfeedback = $generalfeedback['text'];
495 $qo->generalfeedbackformat = $generalfeedback['format'];
496 if (!empty($generalfeedback['itemid'])) {
497 $qo->generalfeedbackitemid = $generalfeedback['itemid'];
500 $qo->penalty = $this->getpath($question,
501 array('#', 'penalty', 0, '#'), $this->defaultquestion()->penalty);
502 // Fix problematic rounding from old files.
503 if (abs($qo->penalty - 0.3333333) < 0.005) {
504 $qo->penalty = 0.3333333;
507 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat));
513 * Import true/false type question
514 * @param array question question array from xml tree
515 * @return object question object
517 public function import_truefalse($question) {
520 $qo = $this->import_headers($question);
522 // Header parts particular to true/false.
523 $qo->qtype = 'truefalse';
525 // In the past, it used to be assumed that the two answers were in the file
526 // true first, then false. Howevever that was not always true. Now, we
527 // try to match on the answer text, but in old exports, this will be a localised
528 // string, so if we don't find true or false, we fall back to the old system.
531 foreach ($question['#']['answer'] as $answer) {
532 $answertext = $this->getpath($answer,
533 array('#', 'text', 0, '#'), '', true);
534 $feedback = $this->import_text_with_files($answer,
535 array('#', 'feedback', 0), '', $this->get_format($qo->questiontextformat));
537 if ($answertext != 'true' && $answertext != 'false') {
538 // Old style file, assume order is true/false.
541 $answertext = 'true';
543 $answertext = 'false';
547 if ($answertext == 'true') {
548 $qo->answer = ($answer['@']['fraction'] == 100);
549 $qo->correctanswer = $qo->answer;
550 $qo->feedbacktrue = $feedback;
552 $qo->answer = ($answer['@']['fraction'] != 100);
553 $qo->correctanswer = $qo->answer;
554 $qo->feedbackfalse = $feedback;
561 $a->questiontext = $qo->questiontext;
562 $a->answer = get_string($qo->correctanswer ? 'true' : 'false', 'qtype_truefalse');
563 echo $OUTPUT->notification(get_string('truefalseimporterror', 'qformat_xml', $a));
566 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat));
572 * Import short answer type question
573 * @param array question question array from xml tree
574 * @return object question object
576 public function import_shortanswer($question) {
578 $qo = $this->import_headers($question);
580 // Header parts particular to shortanswer.
581 $qo->qtype = 'shortanswer';
584 $qo->usecase = $this->getpath($question, array('#', 'usecase', 0, '#'), $qo->usecase);
586 // Run through the answers.
587 $answers = $question['#']['answer'];
589 foreach ($answers as $answer) {
590 $ans = $this->import_answer($answer, false, $this->get_format($qo->questiontextformat));
591 $qo->answer[$acount] = $ans->answer['text'];
592 $qo->fraction[$acount] = $ans->fraction;
593 $qo->feedback[$acount] = $ans->feedback;
597 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat));
603 * Import description type question
604 * @param array question question array from xml tree
605 * @return object question object
607 public function import_description($question) {
609 $qo = $this->import_headers($question);
610 // Header parts particular to shortanswer.
611 $qo->qtype = 'description';
612 $qo->defaultmark = 0;
618 * Import numerical type question
619 * @param array question question array from xml tree
620 * @return object question object
622 public function import_numerical($question) {
624 $qo = $this->import_headers($question);
626 // Header parts particular to numerical.
627 $qo->qtype = 'numerical';
629 // Get answers array.
630 $answers = $question['#']['answer'];
631 $qo->answer = array();
632 $qo->feedback = array();
633 $qo->fraction = array();
634 $qo->tolerance = array();
635 foreach ($answers as $answer) {
636 // Answer outside of <text> is deprecated.
637 $obj = $this->import_answer($answer, false, $this->get_format($qo->questiontextformat));
638 $qo->answer[] = $obj->answer['text'];
639 if (empty($qo->answer)) {
642 $qo->feedback[] = $obj->feedback;
643 $qo->tolerance[] = $this->getpath($answer, array('#', 'tolerance', 0, '#'), 0);
645 // Fraction as a tag is deprecated.
646 $fraction = $this->getpath($answer, array('@', 'fraction'), 0) / 100;
647 $qo->fraction[] = $this->getpath($answer,
648 array('#', 'fraction', 0, '#'), $fraction); // Deprecated.
651 // Get the units array.
653 $units = $this->getpath($question, array('#', 'units', 0, '#', 'unit'), array());
654 if (!empty($units)) {
655 $qo->multiplier = array();
656 foreach ($units as $unit) {
657 $qo->multiplier[] = $this->getpath($unit, array('#', 'multiplier', 0, '#'), 1);
658 $qo->unit[] = $this->getpath($unit, array('#', 'unit_name', 0, '#'), '', true);
661 $qo->unitgradingtype = $this->getpath($question, array('#', 'unitgradingtype', 0, '#'), 0);
662 $qo->unitpenalty = $this->getpath($question, array('#', 'unitpenalty', 0, '#'), 0.1);
663 $qo->showunits = $this->getpath($question, array('#', 'showunits', 0, '#'), null);
664 $qo->unitsleft = $this->getpath($question, array('#', 'unitsleft', 0, '#'), 0);
665 $qo->instructions['text'] = '';
666 $qo->instructions['format'] = FORMAT_HTML;
667 $instructions = $this->getpath($question, array('#', 'instructions'), array());
668 if (!empty($instructions)) {
669 $qo->instructions = $this->import_text_with_files($instructions,
670 array('0'), '', $this->get_format($qo->questiontextformat));
673 if (is_null($qo->showunits)) {
674 // Set a good default, depending on whether there are any units defined.
675 if (empty($qo->unit)) {
676 $qo->showunits = 3; // This is qtype_numerical::UNITNONE, but we cannot refer to that constant here.
678 $qo->showunits = 0; // This is qtype_numerical::UNITOPTIONAL, but we cannot refer to that constant here.
682 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat));
688 * Import matching type question
689 * @param array question question array from xml tree
690 * @return object question object
692 public function import_match($question) {
694 $qo = $this->import_headers($question);
696 // Header parts particular to matching.
697 $qo->qtype = 'match';
698 $qo->shuffleanswers = $this->trans_single($this->getpath($question,
699 array('#', 'shuffleanswers', 0, '#'), 1));
701 // Run through subquestions.
702 $qo->subquestions = array();
703 $qo->subanswers = array();
704 foreach ($question['#']['subquestion'] as $subqxml) {
705 $qo->subquestions[] = $this->import_text_with_files($subqxml,
706 array(), '', $this->get_format($qo->questiontextformat));
708 $answers = $this->getpath($subqxml, array('#', 'answer'), array());
709 $qo->subanswers[] = $this->getpath($subqxml,
710 array('#', 'answer', 0, '#', 'text', 0, '#'), '', true);
713 $this->import_combined_feedback($qo, $question, true);
714 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat));
720 * Import essay type question
721 * @param array question question array from xml tree
722 * @return object question object
724 public function import_essay($question) {
726 $qo = $this->import_headers($question);
728 // Header parts particular to essay.
729 $qo->qtype = 'essay';
731 $qo->responseformat = $this->getpath($question,
732 array('#', 'responseformat', 0, '#'), 'editor');
733 $qo->responsefieldlines = $this->getpath($question,
734 array('#', 'responsefieldlines', 0, '#'), 15);
735 $qo->responserequired = $this->getpath($question,
736 array('#', 'responserequired', 0, '#'), 1);
737 $qo->attachments = $this->getpath($question,
738 array('#', 'attachments', 0, '#'), 0);
739 $qo->attachmentsrequired = $this->getpath($question,
740 array('#', 'attachmentsrequired', 0, '#'), 0);
741 $qo->graderinfo = $this->import_text_with_files($question,
742 array('#', 'graderinfo', 0), '', $this->get_format($qo->questiontextformat));
743 $qo->responsetemplate['text'] = $this->getpath($question,
744 array('#', 'responsetemplate', 0, '#', 'text', 0, '#'), '', true);
745 $qo->responsetemplate['format'] = $this->trans_format($this->getpath($question,
746 array('#', 'responsetemplate', 0, '@', 'format'), $this->get_format($qo->questiontextformat)));
752 * Import a calculated question
753 * @param object $question the imported XML data.
755 public function import_calculated($question) {
758 $qo = $this->import_headers($question);
760 // Header parts particular to calculated.
761 $qo->qtype = 'calculated';
762 $qo->synchronize = $this->getpath($question, array('#', 'synchronize', 0, '#'), 0);
763 $single = $this->getpath($question, array('#', 'single', 0, '#'), 'true');
764 $qo->single = $this->trans_single($single);
765 $shuffleanswers = $this->getpath($question, array('#', 'shuffleanswers', 0, '#'), 'false');
766 $qo->answernumbering = $this->getpath($question,
767 array('#', 'answernumbering', 0, '#'), 'abc');
768 $qo->shuffleanswers = $this->trans_single($shuffleanswers);
770 $this->import_combined_feedback($qo, $question);
772 $qo->unitgradingtype = $this->getpath($question,
773 array('#', 'unitgradingtype', 0, '#'), 0);
774 $qo->unitpenalty = $this->getpath($question, array('#', 'unitpenalty', 0, '#'), null);
775 $qo->showunits = $this->getpath($question, array('#', 'showunits', 0, '#'), 0);
776 $qo->unitsleft = $this->getpath($question, array('#', 'unitsleft', 0, '#'), 0);
777 $qo->instructions = $this->getpath($question,
778 array('#', 'instructions', 0, '#', 'text', 0, '#'), '', true);
779 if (!empty($instructions)) {
780 $qo->instructions = $this->import_text_with_files($instructions,
781 array('0'), '', $this->get_format($qo->questiontextformat));
784 // Get answers array.
785 $answers = $question['#']['answer'];
786 $qo->answer = array();
787 $qo->feedback = array();
788 $qo->fraction = array();
789 $qo->tolerance = array();
790 $qo->tolerancetype = array();
791 $qo->correctanswerformat = array();
792 $qo->correctanswerlength = array();
793 $qo->feedback = array();
794 foreach ($answers as $answer) {
795 $ans = $this->import_answer($answer, true, $this->get_format($qo->questiontextformat));
796 // Answer outside of <text> is deprecated.
797 if (empty($ans->answer['text'])) {
798 $ans->answer['text'] = '*';
800 $qo->answer[] = $ans->answer['text'];
801 $qo->feedback[] = $ans->feedback;
802 $qo->tolerance[] = $answer['#']['tolerance'][0]['#'];
803 // Fraction as a tag is deprecated.
804 if (!empty($answer['#']['fraction'][0]['#'])) {
805 $qo->fraction[] = $answer['#']['fraction'][0]['#'];
807 $qo->fraction[] = $answer['@']['fraction'] / 100;
809 $qo->tolerancetype[] = $answer['#']['tolerancetype'][0]['#'];
810 $qo->correctanswerformat[] = $answer['#']['correctanswerformat'][0]['#'];
811 $qo->correctanswerlength[] = $answer['#']['correctanswerlength'][0]['#'];
815 if (isset($question['#']['units'][0]['#']['unit'])) {
816 $units = $question['#']['units'][0]['#']['unit'];
817 $qo->multiplier = array();
818 foreach ($units as $unit) {
819 $qo->multiplier[] = $unit['#']['multiplier'][0]['#'];
820 $qo->unit[] = $unit['#']['unit_name'][0]['#'];
823 $instructions = $this->getpath($question, array('#', 'instructions'), array());
824 if (!empty($instructions)) {
825 $qo->instructions = $this->import_text_with_files($instructions,
826 array('0'), '', $this->get_format($qo->questiontextformat));
829 if (is_null($qo->unitpenalty)) {
830 // Set a good default, depending on whether there are any units defined.
831 if (empty($qo->unit)) {
832 $qo->showunits = 3; // This is qtype_numerical::UNITNONE, but we cannot refer to that constant here.
834 $qo->showunits = 0; // This is qtype_numerical::UNITOPTIONAL, but we cannot refer to that constant here.
838 $datasets = $question['#']['dataset_definitions'][0]['#']['dataset_definition'];
839 $qo->dataset = array();
840 $qo->datasetindex= 0;
841 foreach ($datasets as $dataset) {
843 $qo->dataset[$qo->datasetindex] = new stdClass();
844 $qo->dataset[$qo->datasetindex]->status =
845 $this->import_text($dataset['#']['status'][0]['#']['text']);
846 $qo->dataset[$qo->datasetindex]->name =
847 $this->import_text($dataset['#']['name'][0]['#']['text']);
848 $qo->dataset[$qo->datasetindex]->type =
849 $dataset['#']['type'][0]['#'];
850 $qo->dataset[$qo->datasetindex]->distribution =
851 $this->import_text($dataset['#']['distribution'][0]['#']['text']);
852 $qo->dataset[$qo->datasetindex]->max =
853 $this->import_text($dataset['#']['maximum'][0]['#']['text']);
854 $qo->dataset[$qo->datasetindex]->min =
855 $this->import_text($dataset['#']['minimum'][0]['#']['text']);
856 $qo->dataset[$qo->datasetindex]->length =
857 $this->import_text($dataset['#']['decimals'][0]['#']['text']);
858 $qo->dataset[$qo->datasetindex]->distribution =
859 $this->import_text($dataset['#']['distribution'][0]['#']['text']);
860 $qo->dataset[$qo->datasetindex]->itemcount = $dataset['#']['itemcount'][0]['#'];
861 $qo->dataset[$qo->datasetindex]->datasetitem = array();
862 $qo->dataset[$qo->datasetindex]->itemindex = 0;
863 $qo->dataset[$qo->datasetindex]->number_of_items = $this->getpath($dataset,
864 array('#', 'number_of_items', 0, '#'), 0);
865 $datasetitems = $this->getpath($dataset,
866 array('#', 'dataset_items', 0, '#', 'dataset_item'), array());
867 foreach ($datasetitems as $datasetitem) {
868 $qo->dataset[$qo->datasetindex]->itemindex++;
869 $qo->dataset[$qo->datasetindex]->datasetitem[
870 $qo->dataset[$qo->datasetindex]->itemindex] = new stdClass();
871 $qo->dataset[$qo->datasetindex]->datasetitem[
872 $qo->dataset[$qo->datasetindex]->itemindex]->itemnumber =
873 $datasetitem['#']['number'][0]['#'];
874 $qo->dataset[$qo->datasetindex]->datasetitem[
875 $qo->dataset[$qo->datasetindex]->itemindex]->value =
876 $datasetitem['#']['value'][0]['#'];
880 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat));
886 * This is not a real question type. It's a dummy type used to specify the
887 * import category. The format is:
888 * <question type="category">
889 * <category>tom/dick/harry</category>
892 protected function import_category($question) {
893 $qo = new stdClass();
894 $qo->qtype = 'category';
895 $qo->category = $this->import_text($question['#']['category'][0]['#']['text']);
900 * Parse the array of lines into an array of questions
901 * this *could* burn memory - but it won't happen that much
902 * so fingers crossed!
903 * @param array of lines from the input file.
904 * @param stdClass $context
905 * @return array (of objects) question objects.
907 protected function readquestions($lines) {
908 // We just need it as one big string.
909 $lines = implode('', $lines);
911 // This converts xml to big nasty data structure
912 // the 0 means keep white space as it is (important for markdown format).
914 $xml = xmlize($lines, 0, 'UTF-8', true);
915 } catch (xml_format_exception $e) {
916 $this->error($e->getMessage(), '');
919 unset($lines); // No need to keep this in memory.
920 return $this->import_questions($xml['quiz']['#']['question']);
924 * @param array $xml the xmlized xml
925 * @return stdClass[] question objects to pass to question type save_question_options
927 public function import_questions($xml) {
928 $questions = array();
930 // Iterate through questions.
931 foreach ($xml as $questionxml) {
932 $qo = $this->import_question($questionxml);
934 // Stick the result in the $questions array.
943 * @param array $questionxml xml describing the question
944 * @return null|stdClass an object with data to be fed to question type save_question_options
946 protected function import_question($questionxml) {
947 $questiontype = $questionxml['@']['type'];
949 if ($questiontype == 'multichoice') {
950 return $this->import_multichoice($questionxml);
951 } else if ($questiontype == 'truefalse') {
952 return $this->import_truefalse($questionxml);
953 } else if ($questiontype == 'shortanswer') {
954 return $this->import_shortanswer($questionxml);
955 } else if ($questiontype == 'numerical') {
956 return $this->import_numerical($questionxml);
957 } else if ($questiontype == 'description') {
958 return $this->import_description($questionxml);
959 } else if ($questiontype == 'matching' || $questiontype == 'match') {
960 return $this->import_match($questionxml);
961 } else if ($questiontype == 'cloze' || $questiontype == 'multianswer') {
962 return $this->import_multianswer($questionxml);
963 } else if ($questiontype == 'essay') {
964 return $this->import_essay($questionxml);
965 } else if ($questiontype == 'calculated') {
966 return $this->import_calculated($questionxml);
967 } else if ($questiontype == 'calculatedsimple') {
968 $qo = $this->import_calculated($questionxml);
969 $qo->qtype = 'calculatedsimple';
971 } else if ($questiontype == 'calculatedmulti') {
972 $qo = $this->import_calculated($questionxml);
973 $qo->qtype = 'calculatedmulti';
975 } else if ($questiontype == 'category') {
976 return $this->import_category($questionxml);
979 // Not a type we handle ourselves. See if the question type wants
981 if (!$qo = $this->try_importing_using_qtypes($questionxml, null, null, $questiontype)) {
982 $this->error(get_string('xmltypeunsupported', 'qformat_xml', $questiontype));
989 // EXPORT FUNCTIONS START HERE.
991 public function export_file_extension() {
996 * Turn the internal question type name into a human readable form.
997 * (In the past, the code used to use integers internally. Now, it uses
998 * strings, so there is less need for this, but to maintain
999 * backwards-compatibility we change two of the type names.)
1000 * @param string $qtype question type plugin name.
1001 * @return string $qtype string to use in the file.
1003 protected function get_qtype($qtype) {
1015 * Convert internal Moodle text format code into
1016 * human readable form
1017 * @param int id internal code
1018 * @return string format text
1020 public function get_format($id) {
1023 return 'moodle_auto_format';
1027 return 'plain_text';
1030 case FORMAT_MARKDOWN:
1038 * Convert internal single question code into
1039 * human readable form
1040 * @param int id single question code
1041 * @return string single question string
1043 public function get_single($id) {
1055 * Take a string, and wrap it in a CDATA secion, if that is required to make
1056 * the output XML valid.
1057 * @param string $string a string
1058 * @return string the string, wrapped in CDATA if necessary.
1060 public function xml_escape($string) {
1061 if (!empty($string) && htmlspecialchars($string) != $string) {
1062 // If the string contains something that looks like the end
1063 // of a CDATA section, then we need to avoid errors by splitting
1064 // the string between two CDATA sections.
1065 $string = str_replace(']]>', ']]]]><![CDATA[>', $string);
1066 return "<![CDATA[{$string}]]>";
1073 * Generates <text></text> tags, processing raw text therein
1074 * @param string $raw the content to output.
1075 * @param int $indent the current indent level.
1076 * @param bool $short stick it on one line.
1077 * @return string formatted text.
1079 public function writetext($raw, $indent = 0, $short = true) {
1080 $indent = str_repeat(' ', $indent);
1081 $raw = $this->xml_escape($raw);
1084 $xml = "{$indent}<text>{$raw}</text>\n";
1086 $xml = "{$indent}<text>\n{$raw}\n{$indent}</text>\n";
1093 * Generte the XML to represent some files.
1094 * @param array of store array of stored_file objects.
1095 * @return string $string the XML.
1097 public function write_files($files) {
1098 if (empty($files)) {
1102 foreach ($files as $file) {
1103 if ($file->is_directory()) {
1106 $string .= '<file name="' . $file->get_filename() . '" path="' . $file->get_filepath() . '" encoding="base64">';
1107 $string .= base64_encode($file->get_content());
1108 $string .= "</file>\n";
1113 protected function presave_process($content) {
1114 // Override to allow us to add xml headers and footers.
1115 return '<?xml version="1.0" encoding="UTF-8"?>
1117 ' . $content . '</quiz>';
1121 * Turns question into an xml segment
1122 * @param object $question the question data.
1123 * @return string xml segment
1125 public function writequestion($question) {
1126 global $CFG, $OUTPUT;
1128 $invalidquestion = false;
1129 $fs = get_file_storage();
1130 $contextid = $question->contextid;
1131 // Get files used by the questiontext.
1132 $question->questiontextfiles = $fs->get_area_files(
1133 $contextid, 'question', 'questiontext', $question->id);
1134 // Get files used by the generalfeedback.
1135 $question->generalfeedbackfiles = $fs->get_area_files(
1136 $contextid, 'question', 'generalfeedback', $question->id);
1137 if (!empty($question->options->answers)) {
1138 foreach ($question->options->answers as $answer) {
1139 $answer->answerfiles = $fs->get_area_files(
1140 $contextid, 'question', 'answer', $answer->id);
1141 $answer->feedbackfiles = $fs->get_area_files(
1142 $contextid, 'question', 'answerfeedback', $answer->id);
1148 // Add a comment linking this to the original question id.
1149 $expout .= "<!-- question: {$question->id} -->\n";
1151 // Check question type.
1152 $questiontype = $this->get_qtype($question->qtype);
1154 // Categories are a special case.
1155 if ($question->qtype == 'category') {
1156 $categorypath = $this->writetext($question->category);
1157 $expout .= " <question type=\"category\">\n";
1158 $expout .= " <category>\n";
1159 $expout .= " {$categorypath}\n";
1160 $expout .= " </category>\n";
1161 $expout .= " </question>\n";
1165 // Now we know we are are handing a real question.
1166 // Output the generic information.
1167 $expout .= " <question type=\"{$questiontype}\">\n";
1168 $expout .= " <name>\n";
1169 $expout .= $this->writetext($question->name, 3);
1170 $expout .= " </name>\n";
1171 $expout .= " <questiontext {$this->format($question->questiontextformat)}>\n";
1172 $expout .= $this->writetext($question->questiontext, 3);
1173 $expout .= $this->write_files($question->questiontextfiles);
1174 $expout .= " </questiontext>\n";
1175 $expout .= " <generalfeedback {$this->format($question->generalfeedbackformat)}>\n";
1176 $expout .= $this->writetext($question->generalfeedback, 3);
1177 $expout .= $this->write_files($question->generalfeedbackfiles);
1178 $expout .= " </generalfeedback>\n";
1179 if ($question->qtype != 'multianswer') {
1180 $expout .= " <defaultgrade>{$question->defaultmark}</defaultgrade>\n";
1182 $expout .= " <penalty>{$question->penalty}</penalty>\n";
1183 $expout .= " <hidden>{$question->hidden}</hidden>\n";
1185 // The rest of the output depends on question type.
1186 switch($question->qtype) {
1188 // Not a qtype really - dummy used for category switching.
1192 $trueanswer = $question->options->answers[$question->options->trueanswer];
1193 $trueanswer->answer = 'true';
1194 $expout .= $this->write_answer($trueanswer);
1196 $falseanswer = $question->options->answers[$question->options->falseanswer];
1197 $falseanswer->answer = 'false';
1198 $expout .= $this->write_answer($falseanswer);
1202 $expout .= " <single>" . $this->get_single($question->options->single) .
1204 $expout .= " <shuffleanswers>" .
1205 $this->get_single($question->options->shuffleanswers) .
1206 "</shuffleanswers>\n";
1207 $expout .= " <answernumbering>" . $question->options->answernumbering .
1208 "</answernumbering>\n";
1209 $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
1210 $expout .= $this->write_answers($question->options->answers);
1214 $expout .= " <usecase>{$question->options->usecase}</usecase>\n";
1215 $expout .= $this->write_answers($question->options->answers);
1219 foreach ($question->options->answers as $answer) {
1220 $expout .= $this->write_answer($answer,
1221 " <tolerance>{$answer->tolerance}</tolerance>\n");
1224 $units = $question->options->units;
1225 if (count($units)) {
1226 $expout .= "<units>\n";
1227 foreach ($units as $unit) {
1228 $expout .= " <unit>\n";
1229 $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n";
1230 $expout .= " <unit_name>{$unit->unit}</unit_name>\n";
1231 $expout .= " </unit>\n";
1233 $expout .= "</units>\n";
1235 if (isset($question->options->unitgradingtype)) {
1236 $expout .= " <unitgradingtype>" . $question->options->unitgradingtype .
1237 "</unitgradingtype>\n";
1239 if (isset($question->options->unitpenalty)) {
1240 $expout .= " <unitpenalty>{$question->options->unitpenalty}</unitpenalty>\n";
1242 if (isset($question->options->showunits)) {
1243 $expout .= " <showunits>{$question->options->showunits}</showunits>\n";
1245 if (isset($question->options->unitsleft)) {
1246 $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
1248 if (!empty($question->options->instructionsformat)) {
1249 $files = $fs->get_area_files($contextid, 'qtype_numerical',
1250 'instruction', $question->id);
1251 $expout .= " <instructions " .
1252 $this->format($question->options->instructionsformat) . ">\n";
1253 $expout .= $this->writetext($question->options->instructions, 3);
1254 $expout .= $this->write_files($files);
1255 $expout .= " </instructions>\n";
1260 $expout .= " <shuffleanswers>" .
1261 $this->get_single($question->options->shuffleanswers) .
1262 "</shuffleanswers>\n";
1263 $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
1264 foreach ($question->options->subquestions as $subquestion) {
1265 $files = $fs->get_area_files($contextid, 'qtype_match',
1266 'subquestion', $subquestion->id);
1267 $expout .= " <subquestion " .
1268 $this->format($subquestion->questiontextformat) . ">\n";
1269 $expout .= $this->writetext($subquestion->questiontext, 3);
1270 $expout .= $this->write_files($files);
1271 $expout .= " <answer>\n";
1272 $expout .= $this->writetext($subquestion->answertext, 4);
1273 $expout .= " </answer>\n";
1274 $expout .= " </subquestion>\n";
1279 // Nothing else to do.
1283 foreach ($question->options->questions as $index => $subq) {
1284 $expout = str_replace('{#' . $index . '}', $subq->questiontext, $expout);
1289 $expout .= " <responseformat>" . $question->options->responseformat .
1290 "</responseformat>\n";
1291 $expout .= " <responserequired>" . $question->options->responserequired .
1292 "</responserequired>\n";
1293 $expout .= " <responsefieldlines>" . $question->options->responsefieldlines .
1294 "</responsefieldlines>\n";
1295 $expout .= " <attachments>" . $question->options->attachments .
1297 $expout .= " <attachmentsrequired>" . $question->options->attachmentsrequired .
1298 "</attachmentsrequired>\n";
1299 $expout .= " <graderinfo " .
1300 $this->format($question->options->graderinfoformat) . ">\n";
1301 $expout .= $this->writetext($question->options->graderinfo, 3);
1302 $expout .= $this->write_files($fs->get_area_files($contextid, 'qtype_essay',
1303 'graderinfo', $question->id));
1304 $expout .= " </graderinfo>\n";
1305 $expout .= " <responsetemplate " .
1306 $this->format($question->options->responsetemplateformat) . ">\n";
1307 $expout .= $this->writetext($question->options->responsetemplate, 3);
1308 $expout .= " </responsetemplate>\n";
1312 case 'calculatedsimple':
1313 case 'calculatedmulti':
1314 $expout .= " <synchronize>{$question->options->synchronize}</synchronize>\n";
1315 $expout .= " <single>{$question->options->single}</single>\n";
1316 $expout .= " <answernumbering>" . $question->options->answernumbering .
1317 "</answernumbering>\n";
1318 $expout .= " <shuffleanswers>" . $question->options->shuffleanswers .
1319 "</shuffleanswers>\n";
1321 $component = 'qtype_' . $question->qtype;
1322 $files = $fs->get_area_files($contextid, $component,
1323 'correctfeedback', $question->id);
1324 $expout .= " <correctfeedback>\n";
1325 $expout .= $this->writetext($question->options->correctfeedback, 3);
1326 $expout .= $this->write_files($files);
1327 $expout .= " </correctfeedback>\n";
1329 $files = $fs->get_area_files($contextid, $component,
1330 'partiallycorrectfeedback', $question->id);
1331 $expout .= " <partiallycorrectfeedback>\n";
1332 $expout .= $this->writetext($question->options->partiallycorrectfeedback, 3);
1333 $expout .= $this->write_files($files);
1334 $expout .= " </partiallycorrectfeedback>\n";
1336 $files = $fs->get_area_files($contextid, $component,
1337 'incorrectfeedback', $question->id);
1338 $expout .= " <incorrectfeedback>\n";
1339 $expout .= $this->writetext($question->options->incorrectfeedback, 3);
1340 $expout .= $this->write_files($files);
1341 $expout .= " </incorrectfeedback>\n";
1343 foreach ($question->options->answers as $answer) {
1344 $percent = 100 * $answer->fraction;
1345 $expout .= "<answer fraction=\"{$percent}\">\n";
1346 // The "<text/>" tags are an added feature, old files won't have them.
1347 $expout .= " <text>{$answer->answer}</text>\n";
1348 $expout .= " <tolerance>{$answer->tolerance}</tolerance>\n";
1349 $expout .= " <tolerancetype>{$answer->tolerancetype}</tolerancetype>\n";
1350 $expout .= " <correctanswerformat>" .
1351 $answer->correctanswerformat . "</correctanswerformat>\n";
1352 $expout .= " <correctanswerlength>" .
1353 $answer->correctanswerlength . "</correctanswerlength>\n";
1354 $expout .= " <feedback {$this->format($answer->feedbackformat)}>\n";
1355 $files = $fs->get_area_files($contextid, $component,
1356 'instruction', $question->id);
1357 $expout .= $this->writetext($answer->feedback);
1358 $expout .= $this->write_files($answer->feedbackfiles);
1359 $expout .= " </feedback>\n";
1360 $expout .= "</answer>\n";
1362 if (isset($question->options->unitgradingtype)) {
1363 $expout .= " <unitgradingtype>" .
1364 $question->options->unitgradingtype . "</unitgradingtype>\n";
1366 if (isset($question->options->unitpenalty)) {
1367 $expout .= " <unitpenalty>" .
1368 $question->options->unitpenalty . "</unitpenalty>\n";
1370 if (isset($question->options->showunits)) {
1371 $expout .= " <showunits>{$question->options->showunits}</showunits>\n";
1373 if (isset($question->options->unitsleft)) {
1374 $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
1377 if (isset($question->options->instructionsformat)) {
1378 $files = $fs->get_area_files($contextid, $component,
1379 'instruction', $question->id);
1380 $expout .= " <instructions " .
1381 $this->format($question->options->instructionsformat) . ">\n";
1382 $expout .= $this->writetext($question->options->instructions, 3);
1383 $expout .= $this->write_files($files);
1384 $expout .= " </instructions>\n";
1387 if (isset($question->options->units)) {
1388 $units = $question->options->units;
1389 if (count($units)) {
1390 $expout .= "<units>\n";
1391 foreach ($units as $unit) {
1392 $expout .= " <unit>\n";
1393 $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n";
1394 $expout .= " <unit_name>{$unit->unit}</unit_name>\n";
1395 $expout .= " </unit>\n";
1397 $expout .= "</units>\n";
1401 // The tag $question->export_process has been set so we get all the
1402 // data items in the database from the function
1403 // qtype_calculated::get_question_options calculatedsimple defaults
1405 if (isset($question->options->datasets) && count($question->options->datasets)) {
1406 $expout .= "<dataset_definitions>\n";
1407 foreach ($question->options->datasets as $def) {
1408 $expout .= "<dataset_definition>\n";
1409 $expout .= " <status>".$this->writetext($def->status)."</status>\n";
1410 $expout .= " <name>".$this->writetext($def->name)."</name>\n";
1411 if ($question->qtype == 'calculated') {
1412 $expout .= " <type>calculated</type>\n";
1414 $expout .= " <type>calculatedsimple</type>\n";
1416 $expout .= " <distribution>" . $this->writetext($def->distribution) .
1417 "</distribution>\n";
1418 $expout .= " <minimum>" . $this->writetext($def->minimum) .
1420 $expout .= " <maximum>" . $this->writetext($def->maximum) .
1422 $expout .= " <decimals>" . $this->writetext($def->decimals) .
1424 $expout .= " <itemcount>{$def->itemcount}</itemcount>\n";
1425 if ($def->itemcount > 0) {
1426 $expout .= " <dataset_items>\n";
1427 foreach ($def->items as $item) {
1428 $expout .= " <dataset_item>\n";
1429 $expout .= " <number>".$item->itemnumber."</number>\n";
1430 $expout .= " <value>".$item->value."</value>\n";
1431 $expout .= " </dataset_item>\n";
1433 $expout .= " </dataset_items>\n";
1434 $expout .= " <number_of_items>" . $def->number_of_items .
1435 "</number_of_items>\n";
1437 $expout .= "</dataset_definition>\n";
1439 $expout .= "</dataset_definitions>\n";
1444 // Try support by optional plugin.
1445 if (!$data = $this->try_exporting_using_qtypes($question->qtype, $question)) {
1446 $invalidquestion = true;
1452 // Output any hints.
1453 $expout .= $this->write_hints($question);
1455 // Write the question tags.
1456 if (!empty($CFG->usetags)) {
1457 require_once($CFG->dirroot.'/tag/lib.php');
1458 $tags = tag_get_tags_array('question', $question->id);
1459 if (!empty($tags)) {
1460 $expout .= " <tags>\n";
1461 foreach ($tags as $tag) {
1462 $expout .= " <tag>" . $this->writetext($tag, 0, true) . "</tag>\n";
1464 $expout .= " </tags>\n";
1468 // Close the question tag.
1469 $expout .= " </question>\n";
1470 if ($invalidquestion) {
1477 public function write_answers($answers) {
1478 if (empty($answers)) {
1482 foreach ($answers as $answer) {
1483 $output .= $this->write_answer($answer);
1488 public function write_answer($answer, $extra = '') {
1489 $percent = $answer->fraction * 100;
1491 $output .= " <answer fraction=\"{$percent}\" {$this->format($answer->answerformat)}>\n";
1492 $output .= $this->writetext($answer->answer, 3);
1493 $output .= $this->write_files($answer->answerfiles);
1494 $output .= " <feedback {$this->format($answer->feedbackformat)}>\n";
1495 $output .= $this->writetext($answer->feedback, 4);
1496 $output .= $this->write_files($answer->feedbackfiles);
1497 $output .= " </feedback>\n";
1499 $output .= " </answer>\n";
1504 * Write out the hints.
1505 * @param object $question the question definition data.
1506 * @return string XML to output.
1508 public function write_hints($question) {
1509 if (empty($question->hints)) {
1514 foreach ($question->hints as $hint) {
1515 $output .= $this->write_hint($hint, $question->contextid);
1521 * @param int $format a FORMAT_... constant.
1522 * @return string the attribute to add to an XML tag.
1524 public function format($format) {
1525 return 'format="' . $this->get_format($format) . '"';
1528 public function write_hint($hint, $contextid) {
1529 $fs = get_file_storage();
1530 $files = $fs->get_area_files($contextid, 'question', 'hint', $hint->id);
1533 $output .= " <hint {$this->format($hint->hintformat)}>\n";
1534 $output .= ' ' . $this->writetext($hint->hint);
1536 if (!empty($hint->shownumcorrect)) {
1537 $output .= " <shownumcorrect/>\n";
1539 if (!empty($hint->clearwrong)) {
1540 $output .= " <clearwrong/>\n";
1543 if (!empty($hint->options)) {
1544 $output .= ' <options>' . $this->xml_escape($hint->options) . "</options>\n";
1546 $output .= $this->write_files($files);
1547 $output .= " </hint>\n";
1552 * Output the combined feedback fields.
1553 * @param object $questionoptions the question definition data.
1554 * @param int $questionid the question id.
1555 * @param int $contextid the question context id.
1556 * @return string XML to output.
1558 public function write_combined_feedback($questionoptions, $questionid, $contextid) {
1559 $fs = get_file_storage();
1562 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
1563 foreach ($fields as $field) {
1564 $formatfield = $field . 'format';
1565 $files = $fs->get_area_files($contextid, 'question', $field, $questionid);
1567 $output .= " <{$field} {$this->format($questionoptions->$formatfield)}>\n";
1568 $output .= ' ' . $this->writetext($questionoptions->$field);
1569 $output .= $this->write_files($files);
1570 $output .= " </{$field}>\n";
1573 if (!empty($questionoptions->shownumcorrect)) {
1574 $output .= " <shownumcorrect/>\n";