Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

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