See Release Notes
Long Term Support Release
Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 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/>. 16 17 /** 18 * Code for exporting questions as Moodle XML. 19 * 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 23 */ 24 25 26 defined('MOODLE_INTERNAL') || die(); 27 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'); 36 } 37 38 39 /** 40 * Importer for Moodle XML question format. 41 * 42 * See http://docs.moodle.org/en/Moodle_XML_format for a description of the format. 43 * 44 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 46 */ 47 class qformat_xml extends qformat_default { 48 49 public function provide_import() { 50 return true; 51 } 52 53 public function provide_export() { 54 return true; 55 } 56 57 public function mime_type() { 58 return 'application/xml'; 59 } 60 61 // IMPORT FUNCTIONS START HERE. 62 63 /** 64 * Translate human readable format name 65 * into internal Moodle code number 66 * Note the reverse function is called get_format. 67 * @param string name format name from xml file 68 * @return int Moodle format code 69 */ 70 public function trans_format($name) { 71 $name = trim($name); 72 73 if ($name == 'moodle_auto_format') { 74 return FORMAT_MOODLE; 75 } else if ($name == 'html') { 76 return FORMAT_HTML; 77 } else if ($name == 'plain_text') { 78 return FORMAT_PLAIN; 79 } else if ($name == 'wiki_like') { 80 return FORMAT_WIKI; 81 } else if ($name == 'markdown') { 82 return FORMAT_MARKDOWN; 83 } else { 84 debugging("Unrecognised text format '{$name}' in the import file. Assuming 'html'."); 85 return FORMAT_HTML; 86 } 87 } 88 89 /** 90 * Translate human readable single answer option 91 * to internal code number 92 * @param string name true/false 93 * @return int internal code number 94 */ 95 public function trans_single($name) { 96 $name = trim($name); 97 if ($name == "false" || !$name) { 98 return 0; 99 } else { 100 return 1; 101 } 102 } 103 104 /** 105 * process text string from xml file 106 * @param array $text bit of xml tree after ['text'] 107 * @return string processed text. 108 */ 109 public function import_text($text) { 110 // Quick sanity check. 111 if (empty($text)) { 112 return ''; 113 } 114 $data = $text[0]['#']; 115 return trim($data); 116 } 117 118 /** 119 * return the value of a node, given a path to the node 120 * if it doesn't exist return the default value 121 * @param array xml data to read 122 * @param array path path to node expressed as array 123 * @param mixed default 124 * @param bool istext process as text 125 * @param string error if set value must exist, return false and issue message if not 126 * @return mixed value 127 */ 128 public function getpath($xml, $path, $default, $istext=false, $error='') { 129 foreach ($path as $index) { 130 if (!isset($xml[$index])) { 131 if (!empty($error)) { 132 $this->error($error); 133 return false; 134 } else { 135 return $default; 136 } 137 } 138 139 $xml = $xml[$index]; 140 } 141 142 if ($istext) { 143 if (!is_string($xml)) { 144 $this->error(get_string('invalidxml', 'qformat_xml')); 145 } 146 $xml = trim($xml); 147 } 148 149 return $xml; 150 } 151 152 public function import_text_with_files($data, $path, $defaultvalue = '', $defaultformat = 'html') { 153 $field = array(); 154 $field['text'] = $this->getpath($data, 155 array_merge($path, array('#', 'text', 0, '#')), $defaultvalue, true); 156 $field['format'] = $this->trans_format($this->getpath($data, 157 array_merge($path, array('@', 'format')), $defaultformat)); 158 $itemid = $this->import_files_as_draft($this->getpath($data, 159 array_merge($path, array('#', 'file')), array(), false)); 160 if (!empty($itemid)) { 161 $field['itemid'] = $itemid; 162 } 163 return $field; 164 } 165 166 public function import_files_as_draft($xml) { 167 global $USER; 168 if (empty($xml)) { 169 return null; 170 } 171 $fs = get_file_storage(); 172 $itemid = file_get_unused_draft_itemid(); 173 $filepaths = array(); 174 foreach ($xml as $file) { 175 $filename = $this->getpath($file, array('@', 'name'), '', true); 176 $filepath = $this->getpath($file, array('@', 'path'), '/', true); 177 $fullpath = $filepath . $filename; 178 if (in_array($fullpath, $filepaths)) { 179 debugging('Duplicate file in XML: ' . $fullpath, DEBUG_DEVELOPER); 180 continue; 181 } 182 $filerecord = array( 183 'contextid' => context_user::instance($USER->id)->id, 184 'component' => 'user', 185 'filearea' => 'draft', 186 'itemid' => $itemid, 187 'filepath' => $filepath, 188 'filename' => $filename, 189 ); 190 $fs->create_file_from_string($filerecord, base64_decode($file['#'])); 191 $filepaths[] = $fullpath; 192 } 193 return $itemid; 194 } 195 196 /** 197 * import parts of question common to all types 198 * @param $question array question question array from xml tree 199 * @return object question object 200 */ 201 public function import_headers($question) { 202 global $USER; 203 204 // This routine initialises the question object. 205 $qo = $this->defaultquestion(); 206 207 // Question name. 208 $qo->name = $this->clean_question_name($this->getpath($question, 209 array('#', 'name', 0, '#', 'text', 0, '#'), '', true, 210 get_string('xmlimportnoname', 'qformat_xml'))); 211 $questiontext = $this->import_text_with_files($question, 212 array('#', 'questiontext', 0)); 213 $qo->questiontext = $questiontext['text']; 214 $qo->questiontextformat = $questiontext['format']; 215 if (!empty($questiontext['itemid'])) { 216 $qo->questiontextitemid = $questiontext['itemid']; 217 } 218 // Backwards compatibility, deal with the old image tag. 219 $filedata = $this->getpath($question, array('#', 'image_base64', '0', '#'), null, false); 220 $filename = $this->getpath($question, array('#', 'image', '0', '#'), null, false); 221 if ($filedata && $filename) { 222 $fs = get_file_storage(); 223 if (empty($qo->questiontextitemid)) { 224 $qo->questiontextitemid = file_get_unused_draft_itemid(); 225 } 226 $filename = clean_param(str_replace('/', '_', $filename), PARAM_FILE); 227 $filerecord = array( 228 'contextid' => context_user::instance($USER->id)->id, 229 'component' => 'user', 230 'filearea' => 'draft', 231 'itemid' => $qo->questiontextitemid, 232 'filepath' => '/', 233 'filename' => $filename, 234 ); 235 $fs->create_file_from_string($filerecord, base64_decode($filedata)); 236 $qo->questiontext .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />'; 237 } 238 239 $qo->idnumber = $this->getpath($question, ['#', 'idnumber', 0, '#'], null); 240 241 // Restore files in generalfeedback. 242 $generalfeedback = $this->import_text_with_files($question, 243 array('#', 'generalfeedback', 0), '', $this->get_format($qo->questiontextformat)); 244 $qo->generalfeedback = $generalfeedback['text']; 245 $qo->generalfeedbackformat = $generalfeedback['format']; 246 if (!empty($generalfeedback['itemid'])) { 247 $qo->generalfeedbackitemid = $generalfeedback['itemid']; 248 } 249 250 $qo->defaultmark = $this->getpath($question, 251 array('#', 'defaultgrade', 0, '#'), $qo->defaultmark); 252 $qo->penalty = $this->getpath($question, 253 array('#', 'penalty', 0, '#'), $qo->penalty); 254 255 // Fix problematic rounding from old files. 256 if (abs($qo->penalty - 0.3333333) < 0.005) { 257 $qo->penalty = 0.3333333; 258 } 259 260 // Read the question tags. 261 $this->import_question_tags($qo, $question); 262 263 return $qo; 264 } 265 266 /** 267 * Import the common parts of a single answer 268 * @param array answer xml tree for single answer 269 * @param bool $withanswerfiles if true, the answers are HTML (or $defaultformat) 270 * and so may contain files, otherwise the answers are plain text. 271 * @param array Default text format for the feedback, and the answers if $withanswerfiles 272 * is true. 273 * @return object answer object 274 */ 275 public function import_answer($answer, $withanswerfiles = false, $defaultformat = 'html') { 276 $ans = new stdClass(); 277 278 if ($withanswerfiles) { 279 $ans->answer = $this->import_text_with_files($answer, array(), '', $defaultformat); 280 } else { 281 $ans->answer = array(); 282 $ans->answer['text'] = $this->getpath($answer, array('#', 'text', 0, '#'), '', true); 283 $ans->answer['format'] = FORMAT_PLAIN; 284 } 285 286 $ans->feedback = $this->import_text_with_files($answer, array('#', 'feedback', 0), '', $defaultformat); 287 288 $ans->fraction = $this->getpath($answer, array('@', 'fraction'), 0) / 100; 289 290 return $ans; 291 } 292 293 /** 294 * Import the common overall feedback fields. 295 * @param object $question the part of the XML relating to this question. 296 * @param object $qo the question data to add the fields to. 297 * @param bool $withshownumpartscorrect include the shownumcorrect field. 298 */ 299 public function import_combined_feedback($qo, $questionxml, $withshownumpartscorrect = false) { 300 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'); 301 foreach ($fields as $field) { 302 $qo->$field = $this->import_text_with_files($questionxml, 303 array('#', $field, 0), '', $this->get_format($qo->questiontextformat)); 304 } 305 306 if ($withshownumpartscorrect) { 307 $qo->shownumcorrect = array_key_exists('shownumcorrect', $questionxml['#']); 308 309 // Backwards compatibility. 310 if (array_key_exists('correctresponsesfeedback', $questionxml['#'])) { 311 $qo->shownumcorrect = $this->trans_single($this->getpath($questionxml, 312 array('#', 'correctresponsesfeedback', 0, '#'), 1)); 313 } 314 } 315 } 316 317 /** 318 * Import a question hint 319 * @param array $hintxml hint xml fragment. 320 * @param string $defaultformat the text format to assume for hints that do not specify. 321 * @return object hint for storing in the database. 322 */ 323 public function import_hint($hintxml, $defaultformat) { 324 $hint = new stdClass(); 325 if (array_key_exists('hintcontent', $hintxml['#'])) { 326 // Backwards compatibility. 327 328 $hint->hint = $this->import_text_with_files($hintxml, 329 array('#', 'hintcontent', 0), '', $defaultformat); 330 331 $hint->shownumcorrect = $this->getpath($hintxml, 332 array('#', 'statenumberofcorrectresponses', 0, '#'), 0); 333 $hint->clearwrong = $this->getpath($hintxml, 334 array('#', 'clearincorrectresponses', 0, '#'), 0); 335 $hint->options = $this->getpath($hintxml, 336 array('#', 'showfeedbacktoresponses', 0, '#'), 0); 337 338 return $hint; 339 } 340 $hint->hint = $this->import_text_with_files($hintxml, array(), '', $defaultformat); 341 $hint->shownumcorrect = array_key_exists('shownumcorrect', $hintxml['#']); 342 $hint->clearwrong = array_key_exists('clearwrong', $hintxml['#']); 343 $hint->options = $this->getpath($hintxml, array('#', 'options', 0, '#'), '', true); 344 345 return $hint; 346 } 347 348 /** 349 * Import all the question hints 350 * 351 * @param object $qo the question data that is being constructed. 352 * @param array $questionxml The xml representing the question. 353 * @param bool $withparts whether the extra fields relating to parts should be imported. 354 * @param bool $withoptions whether the extra options field should be imported. 355 * @param string $defaultformat the text format to assume for hints that do not specify. 356 * @return array of objects representing the hints in the file. 357 */ 358 public function import_hints($qo, $questionxml, $withparts = false, 359 $withoptions = false, $defaultformat = 'html') { 360 if (!isset($questionxml['#']['hint'])) { 361 return; 362 } 363 364 foreach ($questionxml['#']['hint'] as $hintxml) { 365 $hint = $this->import_hint($hintxml, $defaultformat); 366 $qo->hint[] = $hint->hint; 367 368 if ($withparts) { 369 $qo->hintshownumcorrect[] = $hint->shownumcorrect; 370 $qo->hintclearwrong[] = $hint->clearwrong; 371 } 372 373 if ($withoptions) { 374 $qo->hintoptions[] = $hint->options; 375 } 376 } 377 } 378 379 /** 380 * Import all the question tags 381 * 382 * @param object $qo the question data that is being constructed. 383 * @param array $questionxml The xml representing the question. 384 * @return array of objects representing the tags in the file. 385 */ 386 public function import_question_tags($qo, $questionxml) { 387 global $CFG; 388 389 if (core_tag_tag::is_enabled('core_question', 'question')) { 390 391 $qo->tags = []; 392 if (!empty($questionxml['#']['tags'][0]['#']['tag'])) { 393 foreach ($questionxml['#']['tags'][0]['#']['tag'] as $tagdata) { 394 $qo->tags[] = $this->getpath($tagdata, array('#', 'text', 0, '#'), '', true); 395 } 396 } 397 398 $qo->coursetags = []; 399 if (!empty($questionxml['#']['coursetags'][0]['#']['tag'])) { 400 foreach ($questionxml['#']['coursetags'][0]['#']['tag'] as $tagdata) { 401 $qo->coursetags[] = $this->getpath($tagdata, array('#', 'text', 0, '#'), '', true); 402 } 403 } 404 } 405 } 406 407 /** 408 * Import files from a node in the XML. 409 * @param array $xml an array of <file> nodes from the the parsed XML. 410 * @return array of things representing files - in the form that save_question expects. 411 */ 412 public function import_files($xml) { 413 $files = array(); 414 foreach ($xml as $file) { 415 $data = new stdClass(); 416 $data->content = $file['#']; 417 $data->encoding = $file['@']['encoding']; 418 $data->name = $file['@']['name']; 419 $files[] = $data; 420 } 421 return $files; 422 } 423 424 /** 425 * import multiple choice question 426 * @param array question question array from xml tree 427 * @return object question object 428 */ 429 public function import_multichoice($question) { 430 // Get common parts. 431 $qo = $this->import_headers($question); 432 433 // Header parts particular to multichoice. 434 $qo->qtype = 'multichoice'; 435 $single = $this->getpath($question, array('#', 'single', 0, '#'), 'true'); 436 $qo->single = $this->trans_single($single); 437 $shuffleanswers = $this->getpath($question, 438 array('#', 'shuffleanswers', 0, '#'), 'false'); 439 $qo->answernumbering = $this->getpath($question, 440 array('#', 'answernumbering', 0, '#'), 'abc'); 441 $qo->shuffleanswers = $this->trans_single($shuffleanswers); 442 $qo->showstandardinstruction = $this->getpath($question, 443 array('#', 'showstandardinstruction', 0, '#'), '1'); 444 445 // There was a time on the 1.8 branch when it could output an empty 446 // answernumbering tag, so fix up any found. 447 if (empty($qo->answernumbering)) { 448 $qo->answernumbering = 'abc'; 449 } 450 451 // Run through the answers. 452 $answers = $question['#']['answer']; 453 $acount = 0; 454 foreach ($answers as $answer) { 455 $ans = $this->import_answer($answer, true, $this->get_format($qo->questiontextformat)); 456 $qo->answer[$acount] = $ans->answer; 457 $qo->fraction[$acount] = $ans->fraction; 458 $qo->feedback[$acount] = $ans->feedback; 459 ++$acount; 460 } 461 462 $this->import_combined_feedback($qo, $question, true); 463 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat)); 464 465 return $qo; 466 } 467 468 /** 469 * Import cloze type question 470 * @param array question question array from xml tree 471 * @return object question object 472 */ 473 public function import_multianswer($question) { 474 global $USER; 475 question_bank::get_qtype('multianswer'); 476 477 $questiontext = $this->import_text_with_files($question, 478 array('#', 'questiontext', 0)); 479 $qo = qtype_multianswer_extract_question($questiontext); 480 $errors = qtype_multianswer_validate_question($qo); 481 if ($errors) { 482 $this->error(get_string('invalidmultianswerquestion', 'qtype_multianswer', implode(' ', $errors))); 483 return null; 484 } 485 486 // Header parts particular to multianswer. 487 $qo->qtype = 'multianswer'; 488 489 // Only set the course if the data is available. 490 if (isset($this->course)) { 491 $qo->course = $this->course; 492 } 493 if (isset($question['#']['name'])) { 494 $qo->name = $this->clean_question_name($this->import_text($question['#']['name'][0]['#']['text'])); 495 } else { 496 $qo->name = $this->create_default_question_name($qo->questiontext['text'], 497 get_string('questionname', 'question')); 498 } 499 $qo->questiontextformat = $questiontext['format']; 500 $qo->questiontext = $qo->questiontext['text']; 501 if (!empty($questiontext['itemid'])) { 502 $qo->questiontextitemid = $questiontext['itemid']; 503 } 504 505 // Backwards compatibility, deal with the old image tag. 506 $filedata = $this->getpath($question, array('#', 'image_base64', '0', '#'), null, false); 507 $filename = $this->getpath($question, array('#', 'image', '0', '#'), null, false); 508 if ($filedata && $filename) { 509 $fs = get_file_storage(); 510 if (empty($qo->questiontextitemid)) { 511 $qo->questiontextitemid = file_get_unused_draft_itemid(); 512 } 513 $filename = clean_param(str_replace('/', '_', $filename), PARAM_FILE); 514 $filerecord = array( 515 'contextid' => context_user::instance($USER->id)->id, 516 'component' => 'user', 517 'filearea' => 'draft', 518 'itemid' => $qo->questiontextitemid, 519 'filepath' => '/', 520 'filename' => $filename, 521 ); 522 $fs->create_file_from_string($filerecord, base64_decode($filedata)); 523 $qo->questiontext .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />'; 524 } 525 526 // Restore files in generalfeedback. 527 $generalfeedback = $this->import_text_with_files($question, 528 array('#', 'generalfeedback', 0), '', $this->get_format($qo->questiontextformat)); 529 $qo->generalfeedback = $generalfeedback['text']; 530 $qo->generalfeedbackformat = $generalfeedback['format']; 531 if (!empty($generalfeedback['itemid'])) { 532 $qo->generalfeedbackitemid = $generalfeedback['itemid']; 533 } 534 535 $qo->penalty = $this->getpath($question, 536 array('#', 'penalty', 0, '#'), $this->defaultquestion()->penalty); 537 // Fix problematic rounding from old files. 538 if (abs($qo->penalty - 0.3333333) < 0.005) { 539 $qo->penalty = 0.3333333; 540 } 541 542 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat)); 543 $this->import_question_tags($qo, $question); 544 545 return $qo; 546 } 547 548 /** 549 * Import true/false type question 550 * @param array question question array from xml tree 551 * @return object question object 552 */ 553 public function import_truefalse($question) { 554 // Get common parts. 555 global $OUTPUT; 556 $qo = $this->import_headers($question); 557 558 // Header parts particular to true/false. 559 $qo->qtype = 'truefalse'; 560 561 // In the past, it used to be assumed that the two answers were in the file 562 // true first, then false. Howevever that was not always true. Now, we 563 // try to match on the answer text, but in old exports, this will be a localised 564 // string, so if we don't find true or false, we fall back to the old system. 565 $first = true; 566 $warning = false; 567 foreach ($question['#']['answer'] as $answer) { 568 $answertext = $this->getpath($answer, 569 array('#', 'text', 0, '#'), '', true); 570 $feedback = $this->import_text_with_files($answer, 571 array('#', 'feedback', 0), '', $this->get_format($qo->questiontextformat)); 572 573 if ($answertext != 'true' && $answertext != 'false') { 574 // Old style file, assume order is true/false. 575 $warning = true; 576 if ($first) { 577 $answertext = 'true'; 578 } else { 579 $answertext = 'false'; 580 } 581 } 582 583 if ($answertext == 'true') { 584 $qo->answer = ($answer['@']['fraction'] == 100); 585 $qo->correctanswer = $qo->answer; 586 $qo->feedbacktrue = $feedback; 587 } else { 588 $qo->answer = ($answer['@']['fraction'] != 100); 589 $qo->correctanswer = $qo->answer; 590 $qo->feedbackfalse = $feedback; 591 } 592 $first = false; 593 } 594 595 if ($warning) { 596 $a = new stdClass(); 597 $a->questiontext = $qo->questiontext; 598 $a->answer = get_string($qo->correctanswer ? 'true' : 'false', 'qtype_truefalse'); 599 echo $OUTPUT->notification(get_string('truefalseimporterror', 'qformat_xml', $a)); 600 } 601 602 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat)); 603 604 return $qo; 605 } 606 607 /** 608 * Import short answer type question 609 * @param array question question array from xml tree 610 * @return object question object 611 */ 612 public function import_shortanswer($question) { 613 // Get common parts. 614 $qo = $this->import_headers($question); 615 616 // Header parts particular to shortanswer. 617 $qo->qtype = 'shortanswer'; 618 619 // Get usecase. 620 $qo->usecase = $this->getpath($question, array('#', 'usecase', 0, '#'), $qo->usecase); 621 622 // Run through the answers. 623 $answers = $question['#']['answer']; 624 $acount = 0; 625 foreach ($answers as $answer) { 626 $ans = $this->import_answer($answer, false, $this->get_format($qo->questiontextformat)); 627 $qo->answer[$acount] = $ans->answer['text']; 628 $qo->fraction[$acount] = $ans->fraction; 629 $qo->feedback[$acount] = $ans->feedback; 630 ++$acount; 631 } 632 633 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat)); 634 635 return $qo; 636 } 637 638 /** 639 * Import description type question 640 * @param array question question array from xml tree 641 * @return object question object 642 */ 643 public function import_description($question) { 644 // Get common parts. 645 $qo = $this->import_headers($question); 646 // Header parts particular to shortanswer. 647 $qo->qtype = 'description'; 648 $qo->defaultmark = 0; 649 $qo->length = 0; 650 return $qo; 651 } 652 653 /** 654 * Import numerical type question 655 * @param array question question array from xml tree 656 * @return object question object 657 */ 658 public function import_numerical($question) { 659 // Get common parts. 660 $qo = $this->import_headers($question); 661 662 // Header parts particular to numerical. 663 $qo->qtype = 'numerical'; 664 665 // Get answers array. 666 $answers = $question['#']['answer']; 667 $qo->answer = array(); 668 $qo->feedback = array(); 669 $qo->fraction = array(); 670 $qo->tolerance = array(); 671 foreach ($answers as $answer) { 672 // Answer outside of <text> is deprecated. 673 $obj = $this->import_answer($answer, false, $this->get_format($qo->questiontextformat)); 674 $qo->answer[] = $obj->answer['text']; 675 if (empty($qo->answer)) { 676 $qo->answer = '*'; 677 } 678 $qo->feedback[] = $obj->feedback; 679 $qo->tolerance[] = $this->getpath($answer, array('#', 'tolerance', 0, '#'), 0); 680 681 // Fraction as a tag is deprecated. 682 $fraction = $this->getpath($answer, array('@', 'fraction'), 0) / 100; 683 $qo->fraction[] = $this->getpath($answer, 684 array('#', 'fraction', 0, '#'), $fraction); // Deprecated. 685 } 686 687 // Get the units array. 688 $qo->unit = array(); 689 $units = $this->getpath($question, array('#', 'units', 0, '#', 'unit'), array()); 690 if (!empty($units)) { 691 $qo->multiplier = array(); 692 foreach ($units as $unit) { 693 $qo->multiplier[] = $this->getpath($unit, array('#', 'multiplier', 0, '#'), 1); 694 $qo->unit[] = $this->getpath($unit, array('#', 'unit_name', 0, '#'), '', true); 695 } 696 } 697 $qo->unitgradingtype = $this->getpath($question, array('#', 'unitgradingtype', 0, '#'), 0); 698 $qo->unitpenalty = $this->getpath($question, array('#', 'unitpenalty', 0, '#'), 0.1); 699 $qo->showunits = $this->getpath($question, array('#', 'showunits', 0, '#'), null); 700 $qo->unitsleft = $this->getpath($question, array('#', 'unitsleft', 0, '#'), 0); 701 $qo->instructions['text'] = ''; 702 $qo->instructions['format'] = FORMAT_HTML; 703 $instructions = $this->getpath($question, array('#', 'instructions'), array()); 704 if (!empty($instructions)) { 705 $qo->instructions = $this->import_text_with_files($instructions, 706 array('0'), '', $this->get_format($qo->questiontextformat)); 707 } 708 709 if (is_null($qo->showunits)) { 710 // Set a good default, depending on whether there are any units defined. 711 if (empty($qo->unit)) { 712 $qo->showunits = 3; // This is qtype_numerical::UNITNONE, but we cannot refer to that constant here. 713 } else { 714 $qo->showunits = 0; // This is qtype_numerical::UNITOPTIONAL, but we cannot refer to that constant here. 715 } 716 } 717 718 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat)); 719 720 return $qo; 721 } 722 723 /** 724 * Import matching type question 725 * @param array question question array from xml tree 726 * @return object question object 727 */ 728 public function import_match($question) { 729 // Get common parts. 730 $qo = $this->import_headers($question); 731 732 // Header parts particular to matching. 733 $qo->qtype = 'match'; 734 $qo->shuffleanswers = $this->trans_single($this->getpath($question, 735 array('#', 'shuffleanswers', 0, '#'), 1)); 736 737 // Run through subquestions. 738 $qo->subquestions = array(); 739 $qo->subanswers = array(); 740 foreach ($question['#']['subquestion'] as $subqxml) { 741 $qo->subquestions[] = $this->import_text_with_files($subqxml, 742 array(), '', $this->get_format($qo->questiontextformat)); 743 744 $answers = $this->getpath($subqxml, array('#', 'answer'), array()); 745 $qo->subanswers[] = $this->getpath($subqxml, 746 array('#', 'answer', 0, '#', 'text', 0, '#'), '', true); 747 } 748 749 $this->import_combined_feedback($qo, $question, true); 750 $this->import_hints($qo, $question, true, false, $this->get_format($qo->questiontextformat)); 751 752 return $qo; 753 } 754 755 /** 756 * Import essay type question 757 * @param array question question array from xml tree 758 * @return object question object 759 */ 760 public function import_essay($question) { 761 // Get common parts. 762 $qo = $this->import_headers($question); 763 764 // Header parts particular to essay. 765 $qo->qtype = 'essay'; 766 767 $qo->responseformat = $this->getpath($question, 768 array('#', 'responseformat', 0, '#'), 'editor'); 769 $qo->responsefieldlines = $this->getpath($question, 770 array('#', 'responsefieldlines', 0, '#'), 15); 771 $qo->responserequired = $this->getpath($question, 772 array('#', 'responserequired', 0, '#'), 1); 773 $qo->attachments = $this->getpath($question, 774 array('#', 'attachments', 0, '#'), 0); 775 $qo->attachmentsrequired = $this->getpath($question, 776 array('#', 'attachmentsrequired', 0, '#'), 0); 777 $qo->filetypeslist = $this->getpath($question, 778 array('#', 'filetypeslist', 0, '#'), null); 779 $qo->graderinfo = $this->import_text_with_files($question, 780 array('#', 'graderinfo', 0), '', $this->get_format($qo->questiontextformat)); 781 $qo->responsetemplate['text'] = $this->getpath($question, 782 array('#', 'responsetemplate', 0, '#', 'text', 0, '#'), '', true); 783 $qo->responsetemplate['format'] = $this->trans_format($this->getpath($question, 784 array('#', 'responsetemplate', 0, '@', 'format'), $this->get_format($qo->questiontextformat))); 785 786 return $qo; 787 } 788 789 /** 790 * Import a calculated question 791 * @param object $question the imported XML data. 792 */ 793 public function import_calculated($question) { 794 795 // Get common parts. 796 $qo = $this->import_headers($question); 797 798 // Header parts particular to calculated. 799 $qo->qtype = 'calculated'; 800 $qo->synchronize = $this->getpath($question, array('#', 'synchronize', 0, '#'), 0); 801 $single = $this->getpath($question, array('#', 'single', 0, '#'), 'true'); 802 $qo->single = $this->trans_single($single); 803 $shuffleanswers = $this->getpath($question, array('#', 'shuffleanswers', 0, '#'), 'false'); 804 $qo->answernumbering = $this->getpath($question, 805 array('#', 'answernumbering', 0, '#'), 'abc'); 806 $qo->shuffleanswers = $this->trans_single($shuffleanswers); 807 808 $this->import_combined_feedback($qo, $question); 809 810 $qo->unitgradingtype = $this->getpath($question, 811 array('#', 'unitgradingtype', 0, '#'), 0); 812 $qo->unitpenalty = $this->getpath($question, array('#', 'unitpenalty', 0, '#'), null); 813 $qo->showunits = $this->getpath($question, array('#', 'showunits', 0, '#'), 0); 814 $qo->unitsleft = $this->getpath($question, array('#', 'unitsleft', 0, '#'), 0); 815 $qo->instructions = $this->getpath($question, 816 array('#', 'instructions', 0, '#', 'text', 0, '#'), '', true); 817 if (!empty($instructions)) { 818 $qo->instructions = $this->import_text_with_files($instructions, 819 array('0'), '', $this->get_format($qo->questiontextformat)); 820 } 821 822 // Get answers array. 823 $answers = $question['#']['answer']; 824 $qo->answer = array(); 825 $qo->feedback = array(); 826 $qo->fraction = array(); 827 $qo->tolerance = array(); 828 $qo->tolerancetype = array(); 829 $qo->correctanswerformat = array(); 830 $qo->correctanswerlength = array(); 831 $qo->feedback = array(); 832 foreach ($answers as $answer) { 833 $ans = $this->import_answer($answer, true, $this->get_format($qo->questiontextformat)); 834 // Answer outside of <text> is deprecated. 835 if (empty($ans->answer['text'])) { 836 $ans->answer['text'] = '*'; 837 } 838 $qo->answer[] = $ans->answer['text']; 839 $qo->feedback[] = $ans->feedback; 840 $qo->tolerance[] = $answer['#']['tolerance'][0]['#']; 841 // Fraction as a tag is deprecated. 842 if (!empty($answer['#']['fraction'][0]['#'])) { 843 $qo->fraction[] = $answer['#']['fraction'][0]['#']; 844 } else { 845 $qo->fraction[] = $answer['@']['fraction'] / 100; 846 } 847 $qo->tolerancetype[] = $answer['#']['tolerancetype'][0]['#']; 848 $qo->correctanswerformat[] = $answer['#']['correctanswerformat'][0]['#']; 849 $qo->correctanswerlength[] = $answer['#']['correctanswerlength'][0]['#']; 850 } 851 // Get units array. 852 $qo->unit = array(); 853 if (isset($question['#']['units'][0]['#']['unit'])) { 854 $units = $question['#']['units'][0]['#']['unit']; 855 $qo->multiplier = array(); 856 foreach ($units as $unit) { 857 $qo->multiplier[] = $unit['#']['multiplier'][0]['#']; 858 $qo->unit[] = $unit['#']['unit_name'][0]['#']; 859 } 860 } 861 $instructions = $this->getpath($question, array('#', 'instructions'), array()); 862 if (!empty($instructions)) { 863 $qo->instructions = $this->import_text_with_files($instructions, 864 array('0'), '', $this->get_format($qo->questiontextformat)); 865 } 866 867 if (is_null($qo->unitpenalty)) { 868 // Set a good default, depending on whether there are any units defined. 869 if (empty($qo->unit)) { 870 $qo->showunits = 3; // This is qtype_numerical::UNITNONE, but we cannot refer to that constant here. 871 } else { 872 $qo->showunits = 0; // This is qtype_numerical::UNITOPTIONAL, but we cannot refer to that constant here. 873 } 874 } 875 876 $datasets = $question['#']['dataset_definitions'][0]['#']['dataset_definition']; 877 $qo->dataset = array(); 878 $qo->datasetindex= 0; 879 foreach ($datasets as $dataset) { 880 $qo->datasetindex++; 881 $qo->dataset[$qo->datasetindex] = new stdClass(); 882 $qo->dataset[$qo->datasetindex]->status = 883 $this->import_text($dataset['#']['status'][0]['#']['text']); 884 $qo->dataset[$qo->datasetindex]->name = 885 $this->import_text($dataset['#']['name'][0]['#']['text']); 886 $qo->dataset[$qo->datasetindex]->type = 887 $dataset['#']['type'][0]['#']; 888 $qo->dataset[$qo->datasetindex]->distribution = 889 $this->import_text($dataset['#']['distribution'][0]['#']['text']); 890 $qo->dataset[$qo->datasetindex]->max = 891 $this->import_text($dataset['#']['maximum'][0]['#']['text']); 892 $qo->dataset[$qo->datasetindex]->min = 893 $this->import_text($dataset['#']['minimum'][0]['#']['text']); 894 $qo->dataset[$qo->datasetindex]->length = 895 $this->import_text($dataset['#']['decimals'][0]['#']['text']); 896 $qo->dataset[$qo->datasetindex]->distribution = 897 $this->import_text($dataset['#']['distribution'][0]['#']['text']); 898 $qo->dataset[$qo->datasetindex]->itemcount = $dataset['#']['itemcount'][0]['#']; 899 $qo->dataset[$qo->datasetindex]->datasetitem = array(); 900 $qo->dataset[$qo->datasetindex]->itemindex = 0; 901 $qo->dataset[$qo->datasetindex]->number_of_items = $this->getpath($dataset, 902 array('#', 'number_of_items', 0, '#'), 0); 903 $datasetitems = $this->getpath($dataset, 904 array('#', 'dataset_items', 0, '#', 'dataset_item'), array()); 905 foreach ($datasetitems as $datasetitem) { 906 $qo->dataset[$qo->datasetindex]->itemindex++; 907 $qo->dataset[$qo->datasetindex]->datasetitem[ 908 $qo->dataset[$qo->datasetindex]->itemindex] = new stdClass(); 909 $qo->dataset[$qo->datasetindex]->datasetitem[ 910 $qo->dataset[$qo->datasetindex]->itemindex]->itemnumber = 911 $datasetitem['#']['number'][0]['#']; 912 $qo->dataset[$qo->datasetindex]->datasetitem[ 913 $qo->dataset[$qo->datasetindex]->itemindex]->value = 914 $datasetitem['#']['value'][0]['#']; 915 } 916 } 917 918 $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat)); 919 920 return $qo; 921 } 922 923 /** 924 * This is not a real question type. It's a dummy type used to specify the 925 * import category. The format is: 926 * <question type="category"> 927 * <category>tom/dick/harry</category> 928 * <info format="moodle_auto_format"><text>Category description</text></info> 929 * </question> 930 */ 931 protected function import_category($question) { 932 $qo = new stdClass(); 933 $qo->qtype = 'category'; 934 $qo->category = $this->import_text($question['#']['category'][0]['#']['text']); 935 $qo->info = ''; 936 $qo->infoformat = FORMAT_MOODLE; 937 if (array_key_exists('info', $question['#'])) { 938 $qo->info = $this->import_text($question['#']['info'][0]['#']['text']); 939 // The import should have the format in human readable form, so translate to machine readable format. 940 $qo->infoformat = $this->trans_format($question['#']['info'][0]['@']['format']); 941 } 942 $qo->idnumber = $this->getpath($question, array('#', 'idnumber', 0, '#'), null); 943 return $qo; 944 } 945 946 /** 947 * Parse the array of lines into an array of questions 948 * this *could* burn memory - but it won't happen that much 949 * so fingers crossed! 950 * @param array of lines from the input file. 951 * @param stdClass $context 952 * @return array (of objects) question objects. 953 */ 954 public function readquestions($lines) { 955 // We just need it as one big string. 956 $lines = implode('', $lines); 957 958 // This converts xml to big nasty data structure 959 // the 0 means keep white space as it is (important for markdown format). 960 try { 961 $xml = xmlize($lines, 0, 'UTF-8', true); 962 } catch (xml_format_exception $e) { 963 $this->error($e->getMessage(), ''); 964 return false; 965 } 966 unset($lines); // No need to keep this in memory. 967 return $this->import_questions($xml['quiz']['#']['question']); 968 } 969 970 /** 971 * @param array $xml the xmlized xml 972 * @return stdClass[] question objects to pass to question type save_question_options 973 */ 974 public function import_questions($xml) { 975 $questions = array(); 976 977 // Iterate through questions. 978 foreach ($xml as $questionxml) { 979 $qo = $this->import_question($questionxml); 980 981 // Stick the result in the $questions array. 982 if ($qo) { 983 $questions[] = $qo; 984 } 985 } 986 return $questions; 987 } 988 989 /** 990 * @param array $questionxml xml describing the question 991 * @return null|stdClass an object with data to be fed to question type save_question_options 992 */ 993 protected function import_question($questionxml) { 994 $questiontype = $questionxml['@']['type']; 995 996 if ($questiontype == 'multichoice') { 997 return $this->import_multichoice($questionxml); 998 } else if ($questiontype == 'truefalse') { 999 return $this->import_truefalse($questionxml); 1000 } else if ($questiontype == 'shortanswer') { 1001 return $this->import_shortanswer($questionxml); 1002 } else if ($questiontype == 'numerical') { 1003 return $this->import_numerical($questionxml); 1004 } else if ($questiontype == 'description') { 1005 return $this->import_description($questionxml); 1006 } else if ($questiontype == 'matching' || $questiontype == 'match') { 1007 return $this->import_match($questionxml); 1008 } else if ($questiontype == 'cloze' || $questiontype == 'multianswer') { 1009 return $this->import_multianswer($questionxml); 1010 } else if ($questiontype == 'essay') { 1011 return $this->import_essay($questionxml); 1012 } else if ($questiontype == 'calculated') { 1013 return $this->import_calculated($questionxml); 1014 } else if ($questiontype == 'calculatedsimple') { 1015 $qo = $this->import_calculated($questionxml); 1016 $qo->qtype = 'calculatedsimple'; 1017 return $qo; 1018 } else if ($questiontype == 'calculatedmulti') { 1019 $qo = $this->import_calculated($questionxml); 1020 $qo->qtype = 'calculatedmulti'; 1021 return $qo; 1022 } else if ($questiontype == 'category') { 1023 return $this->import_category($questionxml); 1024 1025 } else { 1026 // Not a type we handle ourselves. See if the question type wants 1027 // to handle it. 1028 if (!$qo = $this->try_importing_using_qtypes($questionxml, null, null, $questiontype)) { 1029 $this->error(get_string('xmltypeunsupported', 'qformat_xml', $questiontype)); 1030 return null; 1031 } 1032 return $qo; 1033 } 1034 } 1035 1036 // EXPORT FUNCTIONS START HERE. 1037 1038 public function export_file_extension() { 1039 return '.xml'; 1040 } 1041 1042 /** 1043 * Turn the internal question type name into a human readable form. 1044 * (In the past, the code used to use integers internally. Now, it uses 1045 * strings, so there is less need for this, but to maintain 1046 * backwards-compatibility we change two of the type names.) 1047 * @param string $qtype question type plugin name. 1048 * @return string $qtype string to use in the file. 1049 */ 1050 protected function get_qtype($qtype) { 1051 switch($qtype) { 1052 case 'match': 1053 return 'matching'; 1054 case 'multianswer': 1055 return 'cloze'; 1056 default: 1057 return $qtype; 1058 } 1059 } 1060 1061 /** 1062 * Convert internal Moodle text format code into 1063 * human readable form 1064 * @param int id internal code 1065 * @return string format text 1066 */ 1067 public function get_format($id) { 1068 switch($id) { 1069 case FORMAT_MOODLE: 1070 return 'moodle_auto_format'; 1071 case FORMAT_HTML: 1072 return 'html'; 1073 case FORMAT_PLAIN: 1074 return 'plain_text'; 1075 case FORMAT_WIKI: 1076 return 'wiki_like'; 1077 case FORMAT_MARKDOWN: 1078 return 'markdown'; 1079 default: 1080 return 'unknown'; 1081 } 1082 } 1083 1084 /** 1085 * Convert internal single question code into 1086 * human readable form 1087 * @param int id single question code 1088 * @return string single question string 1089 */ 1090 public function get_single($id) { 1091 switch($id) { 1092 case 0: 1093 return 'false'; 1094 case 1: 1095 return 'true'; 1096 default: 1097 return 'unknown'; 1098 } 1099 } 1100 1101 /** 1102 * Take a string, and wrap it in a CDATA secion, if that is required to make 1103 * the output XML valid. 1104 * @param string $string a string 1105 * @return string the string, wrapped in CDATA if necessary. 1106 */ 1107 public function xml_escape($string) { 1108 if (!empty($string) && htmlspecialchars($string) != $string) { 1109 // If the string contains something that looks like the end 1110 // of a CDATA section, then we need to avoid errors by splitting 1111 // the string between two CDATA sections. 1112 $string = str_replace(']]>', ']]]]><![CDATA[>', $string); 1113 return "<![CDATA[{$string}]]>"; 1114 } else { 1115 return $string; 1116 } 1117 } 1118 1119 /** 1120 * Generates <text></text> tags, processing raw text therein 1121 * @param string $raw the content to output. 1122 * @param int $indent the current indent level. 1123 * @param bool $short stick it on one line. 1124 * @return string formatted text. 1125 */ 1126 public function writetext($raw, $indent = 0, $short = true) { 1127 $indent = str_repeat(' ', $indent); 1128 $raw = $this->xml_escape($raw); 1129 1130 if ($short) { 1131 $xml = "{$indent}<text>{$raw}</text>\n"; 1132 } else { 1133 $xml = "{$indent}<text>\n{$raw}\n{$indent}</text>\n"; 1134 } 1135 1136 return $xml; 1137 } 1138 1139 /** 1140 * Generte the XML to represent some files. 1141 * @param array of store array of stored_file objects. 1142 * @return string $string the XML. 1143 */ 1144 public function write_files($files) { 1145 if (empty($files)) { 1146 return ''; 1147 } 1148 $string = ''; 1149 foreach ($files as $file) { 1150 if ($file->is_directory()) { 1151 continue; 1152 } 1153 $string .= '<file name="' . $file->get_filename() . '" path="' . $file->get_filepath() . '" encoding="base64">'; 1154 $string .= base64_encode($file->get_content()); 1155 $string .= "</file>\n"; 1156 } 1157 return $string; 1158 } 1159 1160 protected function presave_process($content) { 1161 // Override to allow us to add xml headers and footers. 1162 return '<?xml version="1.0" encoding="UTF-8"?> 1163 <quiz> 1164 ' . $content . '</quiz>'; 1165 } 1166 1167 /** 1168 * Turns question into an xml segment 1169 * @param object $question the question data. 1170 * @return string xml segment 1171 */ 1172 public function writequestion($question) { 1173 1174 $invalidquestion = false; 1175 $fs = get_file_storage(); 1176 $contextid = $question->contextid; 1177 // Get files used by the questiontext. 1178 $question->questiontextfiles = $fs->get_area_files( 1179 $contextid, 'question', 'questiontext', $question->id); 1180 // Get files used by the generalfeedback. 1181 $question->generalfeedbackfiles = $fs->get_area_files( 1182 $contextid, 'question', 'generalfeedback', $question->id); 1183 if (!empty($question->options->answers)) { 1184 foreach ($question->options->answers as $answer) { 1185 $answer->answerfiles = $fs->get_area_files( 1186 $contextid, 'question', 'answer', $answer->id); 1187 $answer->feedbackfiles = $fs->get_area_files( 1188 $contextid, 'question', 'answerfeedback', $answer->id); 1189 } 1190 } 1191 1192 $expout = ''; 1193 1194 // Add a comment linking this to the original question id. 1195 $expout .= "<!-- question: {$question->id} -->\n"; 1196 1197 // Check question type. 1198 $questiontype = $this->get_qtype($question->qtype); 1199 1200 $idnumber = htmlspecialchars($question->idnumber); 1201 1202 // Categories are a special case. 1203 if ($question->qtype == 'category') { 1204 $categorypath = $this->writetext($question->category); 1205 $categoryinfo = $this->writetext($question->info); 1206 $infoformat = $this->format($question->infoformat); 1207 $expout .= " <question type=\"category\">\n"; 1208 $expout .= " <category>\n"; 1209 $expout .= " {$categorypath}"; 1210 $expout .= " </category>\n"; 1211 $expout .= " <info {$infoformat}>\n"; 1212 $expout .= " {$categoryinfo}"; 1213 $expout .= " </info>\n"; 1214 $expout .= " <idnumber>{$idnumber}</idnumber>\n"; 1215 $expout .= " </question>\n"; 1216 return $expout; 1217 } 1218 1219 // Now we know we are are handing a real question. 1220 // Output the generic information. 1221 $expout .= " <question type=\"{$questiontype}\">\n"; 1222 $expout .= " <name>\n"; 1223 $expout .= $this->writetext($question->name, 3); 1224 $expout .= " </name>\n"; 1225 $expout .= " <questiontext {$this->format($question->questiontextformat)}>\n"; 1226 $expout .= $this->writetext($question->questiontext, 3); 1227 $expout .= $this->write_files($question->questiontextfiles); 1228 $expout .= " </questiontext>\n"; 1229 $expout .= " <generalfeedback {$this->format($question->generalfeedbackformat)}>\n"; 1230 $expout .= $this->writetext($question->generalfeedback, 3); 1231 $expout .= $this->write_files($question->generalfeedbackfiles); 1232 $expout .= " </generalfeedback>\n"; 1233 if ($question->qtype != 'multianswer') { 1234 $expout .= " <defaultgrade>{$question->defaultmark}</defaultgrade>\n"; 1235 } 1236 $expout .= " <penalty>{$question->penalty}</penalty>\n"; 1237 $expout .= " <hidden>{$question->hidden}</hidden>\n"; 1238 $expout .= " <idnumber>{$idnumber}</idnumber>\n"; 1239 1240 // The rest of the output depends on question type. 1241 switch($question->qtype) { 1242 case 'category': 1243 // Not a qtype really - dummy used for category switching. 1244 break; 1245 1246 case 'truefalse': 1247 $trueanswer = $question->options->answers[$question->options->trueanswer]; 1248 $trueanswer->answer = 'true'; 1249 $expout .= $this->write_answer($trueanswer); 1250 1251 $falseanswer = $question->options->answers[$question->options->falseanswer]; 1252 $falseanswer->answer = 'false'; 1253 $expout .= $this->write_answer($falseanswer); 1254 break; 1255 1256 case 'multichoice': 1257 $expout .= " <single>" . $this->get_single($question->options->single) . 1258 "</single>\n"; 1259 $expout .= " <shuffleanswers>" . 1260 $this->get_single($question->options->shuffleanswers) . 1261 "</shuffleanswers>\n"; 1262 $expout .= " <answernumbering>" . $question->options->answernumbering . 1263 "</answernumbering>\n"; 1264 $expout .= " <showstandardinstruction>" . $question->options->showstandardinstruction . 1265 "</showstandardinstruction>\n"; 1266 $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid); 1267 $expout .= $this->write_answers($question->options->answers); 1268 break; 1269 1270 case 'shortanswer': 1271 $expout .= " <usecase>{$question->options->usecase}</usecase>\n"; 1272 $expout .= $this->write_answers($question->options->answers); 1273 break; 1274 1275 case 'numerical': 1276 foreach ($question->options->answers as $answer) { 1277 $expout .= $this->write_answer($answer, 1278 " <tolerance>{$answer->tolerance}</tolerance>\n"); 1279 } 1280 1281 $units = $question->options->units; 1282 if (count($units)) { 1283 $expout .= "<units>\n"; 1284 foreach ($units as $unit) { 1285 $expout .= " <unit>\n"; 1286 $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n"; 1287 $expout .= " <unit_name>{$unit->unit}</unit_name>\n"; 1288 $expout .= " </unit>\n"; 1289 } 1290 $expout .= "</units>\n"; 1291 } 1292 if (isset($question->options->unitgradingtype)) { 1293 $expout .= " <unitgradingtype>" . $question->options->unitgradingtype . 1294 "</unitgradingtype>\n"; 1295 } 1296 if (isset($question->options->unitpenalty)) { 1297 $expout .= " <unitpenalty>{$question->options->unitpenalty}</unitpenalty>\n"; 1298 } 1299 if (isset($question->options->showunits)) { 1300 $expout .= " <showunits>{$question->options->showunits}</showunits>\n"; 1301 } 1302 if (isset($question->options->unitsleft)) { 1303 $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n"; 1304 } 1305 if (!empty($question->options->instructionsformat)) { 1306 $files = $fs->get_area_files($contextid, 'qtype_numerical', 1307 'instruction', $question->id); 1308 $expout .= " <instructions " . 1309 $this->format($question->options->instructionsformat) . ">\n"; 1310 $expout .= $this->writetext($question->options->instructions, 3); 1311 $expout .= $this->write_files($files); 1312 $expout .= " </instructions>\n"; 1313 } 1314 break; 1315 1316 case 'match': 1317 $expout .= " <shuffleanswers>" . 1318 $this->get_single($question->options->shuffleanswers) . 1319 "</shuffleanswers>\n"; 1320 $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid); 1321 foreach ($question->options->subquestions as $subquestion) { 1322 $files = $fs->get_area_files($contextid, 'qtype_match', 1323 'subquestion', $subquestion->id); 1324 $expout .= " <subquestion " . 1325 $this->format($subquestion->questiontextformat) . ">\n"; 1326 $expout .= $this->writetext($subquestion->questiontext, 3); 1327 $expout .= $this->write_files($files); 1328 $expout .= " <answer>\n"; 1329 $expout .= $this->writetext($subquestion->answertext, 4); 1330 $expout .= " </answer>\n"; 1331 $expout .= " </subquestion>\n"; 1332 } 1333 break; 1334 1335 case 'description': 1336 // Nothing else to do. 1337 break; 1338 1339 case 'multianswer': 1340 foreach ($question->options->questions as $index => $subq) { 1341 $expout = str_replace('{#' . $index . '}', $subq->questiontext, $expout); 1342 } 1343 break; 1344 1345 case 'essay': 1346 $expout .= " <responseformat>" . $question->options->responseformat . 1347 "</responseformat>\n"; 1348 $expout .= " <responserequired>" . $question->options->responserequired . 1349 "</responserequired>\n"; 1350 $expout .= " <responsefieldlines>" . $question->options->responsefieldlines . 1351 "</responsefieldlines>\n"; 1352 $expout .= " <attachments>" . $question->options->attachments . 1353 "</attachments>\n"; 1354 $expout .= " <attachmentsrequired>" . $question->options->attachmentsrequired . 1355 "</attachmentsrequired>\n"; 1356 $expout .= " <filetypeslist>" . $question->options->filetypeslist . 1357 "</filetypeslist>\n"; 1358 $expout .= " <graderinfo " . 1359 $this->format($question->options->graderinfoformat) . ">\n"; 1360 $expout .= $this->writetext($question->options->graderinfo, 3); 1361 $expout .= $this->write_files($fs->get_area_files($contextid, 'qtype_essay', 1362 'graderinfo', $question->id)); 1363 $expout .= " </graderinfo>\n"; 1364 $expout .= " <responsetemplate " . 1365 $this->format($question->options->responsetemplateformat) . ">\n"; 1366 $expout .= $this->writetext($question->options->responsetemplate, 3); 1367 $expout .= " </responsetemplate>\n"; 1368 break; 1369 1370 case 'calculated': 1371 case 'calculatedsimple': 1372 case 'calculatedmulti': 1373 $expout .= " <synchronize>{$question->options->synchronize}</synchronize>\n"; 1374 $expout .= " <single>{$question->options->single}</single>\n"; 1375 $expout .= " <answernumbering>" . $question->options->answernumbering . 1376 "</answernumbering>\n"; 1377 $expout .= " <shuffleanswers>" . $question->options->shuffleanswers . 1378 "</shuffleanswers>\n"; 1379 1380 $component = 'qtype_' . $question->qtype; 1381 $files = $fs->get_area_files($contextid, $component, 1382 'correctfeedback', $question->id); 1383 $expout .= " <correctfeedback>\n"; 1384 $expout .= $this->writetext($question->options->correctfeedback, 3); 1385 $expout .= $this->write_files($files); 1386 $expout .= " </correctfeedback>\n"; 1387 1388 $files = $fs->get_area_files($contextid, $component, 1389 'partiallycorrectfeedback', $question->id); 1390 $expout .= " <partiallycorrectfeedback>\n"; 1391 $expout .= $this->writetext($question->options->partiallycorrectfeedback, 3); 1392 $expout .= $this->write_files($files); 1393 $expout .= " </partiallycorrectfeedback>\n"; 1394 1395 $files = $fs->get_area_files($contextid, $component, 1396 'incorrectfeedback', $question->id); 1397 $expout .= " <incorrectfeedback>\n"; 1398 $expout .= $this->writetext($question->options->incorrectfeedback, 3); 1399 $expout .= $this->write_files($files); 1400 $expout .= " </incorrectfeedback>\n"; 1401 1402 foreach ($question->options->answers as $answer) { 1403 $percent = 100 * $answer->fraction; 1404 $expout .= "<answer fraction=\"{$percent}\">\n"; 1405 // The "<text/>" tags are an added feature, old files won't have them. 1406 $expout .= " <text>{$answer->answer}</text>\n"; 1407 $expout .= " <tolerance>{$answer->tolerance}</tolerance>\n"; 1408 $expout .= " <tolerancetype>{$answer->tolerancetype}</tolerancetype>\n"; 1409 $expout .= " <correctanswerformat>" . 1410 $answer->correctanswerformat . "</correctanswerformat>\n"; 1411 $expout .= " <correctanswerlength>" . 1412 $answer->correctanswerlength . "</correctanswerlength>\n"; 1413 $expout .= " <feedback {$this->format($answer->feedbackformat)}>\n"; 1414 $files = $fs->get_area_files($contextid, $component, 1415 'instruction', $question->id); 1416 $expout .= $this->writetext($answer->feedback); 1417 $expout .= $this->write_files($answer->feedbackfiles); 1418 $expout .= " </feedback>\n"; 1419 $expout .= "</answer>\n"; 1420 } 1421 if (isset($question->options->unitgradingtype)) { 1422 $expout .= " <unitgradingtype>" . 1423 $question->options->unitgradingtype . "</unitgradingtype>\n"; 1424 } 1425 if (isset($question->options->unitpenalty)) { 1426 $expout .= " <unitpenalty>" . 1427 $question->options->unitpenalty . "</unitpenalty>\n"; 1428 } 1429 if (isset($question->options->showunits)) { 1430 $expout .= " <showunits>{$question->options->showunits}</showunits>\n"; 1431 } 1432 if (isset($question->options->unitsleft)) { 1433 $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n"; 1434 } 1435 1436 if (isset($question->options->instructionsformat)) { 1437 $files = $fs->get_area_files($contextid, $component, 1438 'instruction', $question->id); 1439 $expout .= " <instructions " . 1440 $this->format($question->options->instructionsformat) . ">\n"; 1441 $expout .= $this->writetext($question->options->instructions, 3); 1442 $expout .= $this->write_files($files); 1443 $expout .= " </instructions>\n"; 1444 } 1445 1446 if (isset($question->options->units)) { 1447 $units = $question->options->units; 1448 if (count($units)) { 1449 $expout .= "<units>\n"; 1450 foreach ($units as $unit) { 1451 $expout .= " <unit>\n"; 1452 $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n"; 1453 $expout .= " <unit_name>{$unit->unit}</unit_name>\n"; 1454 $expout .= " </unit>\n"; 1455 } 1456 $expout .= "</units>\n"; 1457 } 1458 } 1459 1460 // The tag $question->export_process has been set so we get all the 1461 // data items in the database from the function 1462 // qtype_calculated::get_question_options calculatedsimple defaults 1463 // to calculated. 1464 if (isset($question->options->datasets) && count($question->options->datasets)) { 1465 $expout .= "<dataset_definitions>\n"; 1466 foreach ($question->options->datasets as $def) { 1467 $expout .= "<dataset_definition>\n"; 1468 $expout .= " <status>".$this->writetext($def->status)."</status>\n"; 1469 $expout .= " <name>".$this->writetext($def->name)."</name>\n"; 1470 if ($question->qtype == 'calculated') { 1471 $expout .= " <type>calculated</type>\n"; 1472 } else { 1473 $expout .= " <type>calculatedsimple</type>\n"; 1474 } 1475 $expout .= " <distribution>" . $this->writetext($def->distribution) . 1476 "</distribution>\n"; 1477 $expout .= " <minimum>" . $this->writetext($def->minimum) . 1478 "</minimum>\n"; 1479 $expout .= " <maximum>" . $this->writetext($def->maximum) . 1480 "</maximum>\n"; 1481 $expout .= " <decimals>" . $this->writetext($def->decimals) . 1482 "</decimals>\n"; 1483 $expout .= " <itemcount>{$def->itemcount}</itemcount>\n"; 1484 if ($def->itemcount > 0) { 1485 $expout .= " <dataset_items>\n"; 1486 foreach ($def->items as $item) { 1487 $expout .= " <dataset_item>\n"; 1488 $expout .= " <number>".$item->itemnumber."</number>\n"; 1489 $expout .= " <value>".$item->value."</value>\n"; 1490 $expout .= " </dataset_item>\n"; 1491 } 1492 $expout .= " </dataset_items>\n"; 1493 $expout .= " <number_of_items>" . $def->number_of_items . 1494 "</number_of_items>\n"; 1495 } 1496 $expout .= "</dataset_definition>\n"; 1497 } 1498 $expout .= "</dataset_definitions>\n"; 1499 } 1500 break; 1501 1502 default: 1503 // Try support by optional plugin. 1504 if (!$data = $this->try_exporting_using_qtypes($question->qtype, $question)) { 1505 $invalidquestion = true; 1506 } else { 1507 $expout .= $data; 1508 } 1509 } 1510 1511 // Output any hints. 1512 $expout .= $this->write_hints($question); 1513 1514 // Write the question tags. 1515 if (core_tag_tag::is_enabled('core_question', 'question')) { 1516 $tagobjects = core_tag_tag::get_item_tags('core_question', 'question', $question->id); 1517 1518 if (!empty($tagobjects)) { 1519 $context = context::instance_by_id($contextid); 1520 $sortedtagobjects = question_sort_tags($tagobjects, $context, [$this->course]); 1521 1522 if (!empty($sortedtagobjects->coursetags)) { 1523 // Set them on the form to be rendered as existing tags. 1524 $expout .= " <coursetags>\n"; 1525 foreach ($sortedtagobjects->coursetags as $coursetag) { 1526 $expout .= " <tag>" . $this->writetext($coursetag, 0, true) . "</tag>\n"; 1527 } 1528 $expout .= " </coursetags>\n"; 1529 } 1530 1531 if (!empty($sortedtagobjects->tags)) { 1532 $expout .= " <tags>\n"; 1533 foreach ($sortedtagobjects->tags as $tag) { 1534 $expout .= " <tag>" . $this->writetext($tag, 0, true) . "</tag>\n"; 1535 } 1536 $expout .= " </tags>\n"; 1537 } 1538 } 1539 } 1540 1541 // Close the question tag. 1542 $expout .= " </question>\n"; 1543 if ($invalidquestion) { 1544 return ''; 1545 } else { 1546 return $expout; 1547 } 1548 } 1549 1550 public function write_answers($answers) { 1551 if (empty($answers)) { 1552 return; 1553 } 1554 $output = ''; 1555 foreach ($answers as $answer) { 1556 $output .= $this->write_answer($answer); 1557 } 1558 return $output; 1559 } 1560 1561 public function write_answer($answer, $extra = '') { 1562 $percent = $answer->fraction * 100; 1563 $output = ''; 1564 $output .= " <answer fraction=\"{$percent}\" {$this->format($answer->answerformat)}>\n"; 1565 $output .= $this->writetext($answer->answer, 3); 1566 $output .= $this->write_files($answer->answerfiles); 1567 $output .= " <feedback {$this->format($answer->feedbackformat)}>\n"; 1568 $output .= $this->writetext($answer->feedback, 4); 1569 $output .= $this->write_files($answer->feedbackfiles); 1570 $output .= " </feedback>\n"; 1571 $output .= $extra; 1572 $output .= " </answer>\n"; 1573 return $output; 1574 } 1575 1576 /** 1577 * Write out the hints. 1578 * @param object $question the question definition data. 1579 * @return string XML to output. 1580 */ 1581 public function write_hints($question) { 1582 if (empty($question->hints)) { 1583 return ''; 1584 } 1585 1586 $output = ''; 1587 foreach ($question->hints as $hint) { 1588 $output .= $this->write_hint($hint, $question->contextid); 1589 } 1590 return $output; 1591 } 1592 1593 /** 1594 * @param int $format a FORMAT_... constant. 1595 * @return string the attribute to add to an XML tag. 1596 */ 1597 public function format($format) { 1598 return 'format="' . $this->get_format($format) . '"'; 1599 } 1600 1601 public function write_hint($hint, $contextid) { 1602 $fs = get_file_storage(); 1603 $files = $fs->get_area_files($contextid, 'question', 'hint', $hint->id); 1604 1605 $output = ''; 1606 $output .= " <hint {$this->format($hint->hintformat)}>\n"; 1607 $output .= ' ' . $this->writetext($hint->hint); 1608 1609 if (!empty($hint->shownumcorrect)) { 1610 $output .= " <shownumcorrect/>\n"; 1611 } 1612 if (!empty($hint->clearwrong)) { 1613 $output .= " <clearwrong/>\n"; 1614 } 1615 1616 if (!empty($hint->options)) { 1617 $output .= ' <options>' . $this->xml_escape($hint->options) . "</options>\n"; 1618 } 1619 $output .= $this->write_files($files); 1620 $output .= " </hint>\n"; 1621 return $output; 1622 } 1623 1624 /** 1625 * Output the combined feedback fields. 1626 * @param object $questionoptions the question definition data. 1627 * @param int $questionid the question id. 1628 * @param int $contextid the question context id. 1629 * @return string XML to output. 1630 */ 1631 public function write_combined_feedback($questionoptions, $questionid, $contextid) { 1632 $fs = get_file_storage(); 1633 $output = ''; 1634 1635 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'); 1636 foreach ($fields as $field) { 1637 $formatfield = $field . 'format'; 1638 $files = $fs->get_area_files($contextid, 'question', $field, $questionid); 1639 1640 $output .= " <{$field} {$this->format($questionoptions->$formatfield)}>\n"; 1641 $output .= ' ' . $this->writetext($questionoptions->$field); 1642 $output .= $this->write_files($files); 1643 $output .= " </{$field}>\n"; 1644 } 1645 1646 if (!empty($questionoptions->shownumcorrect)) { 1647 $output .= " <shownumcorrect/>\n"; 1648 } 1649 return $output; 1650 } 1651 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body