Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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      /**
  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          $question->status = 0;
1198          // Get files used by the questiontext.
1199          $question->questiontextfiles = $fs->get_area_files(
1200                  $contextid, 'question', 'questiontext', $question->id);
1201          // Get files used by the generalfeedback.
1202          $question->generalfeedbackfiles = $fs->get_area_files(
1203                  $contextid, 'question', 'generalfeedback', $question->id);
1204          if (!empty($question->options->answers)) {
1205              foreach ($question->options->answers as $answer) {
1206                  $answer->answerfiles = $fs->get_area_files(
1207                          $contextid, 'question', 'answer', $answer->id);
1208                  $answer->feedbackfiles = $fs->get_area_files(
1209                          $contextid, 'question', 'answerfeedback', $answer->id);
1210              }
1211          }
1212  
1213          $expout = '';
1214  
1215          // Add a comment linking this to the original question id.
1216          $expout .= "<!-- question: {$question->id}  -->\n";
1217  
1218          // Check question type.
1219          $questiontype = $this->get_qtype($question->qtype);
1220  
1221          $idnumber = '';
1222          if (isset($question->idnumber)) {
1223              $idnumber = htmlspecialchars($question->idnumber);
1224          }
1225  
1226          // Categories are a special case.
1227          if ($question->qtype == 'category') {
1228              $categorypath = $this->writetext($question->category);
1229              $categoryinfo = $this->writetext($question->info);
1230              $infoformat = $this->format($question->infoformat);
1231              $expout .= "  <question type=\"category\">\n";
1232              $expout .= "    <category>\n";
1233              $expout .= "      {$categorypath}";
1234              $expout .= "    </category>\n";
1235              $expout .= "    <info {$infoformat}>\n";
1236              $expout .= "      {$categoryinfo}";
1237              $expout .= "    </info>\n";
1238              $expout .= "    <idnumber>{$idnumber}</idnumber>\n";
1239              $expout .= "  </question>\n";
1240              return $expout;
1241          }
1242  
1243          // Now we know we are are handing a real question.
1244          // Output the generic information.
1245          $expout .= "  <question type=\"{$questiontype}\">\n";
1246          $expout .= "    <name>\n";
1247          $expout .= $this->writetext($question->name, 3);
1248          $expout .= "    </name>\n";
1249          $expout .= "    <questiontext {$this->format($question->questiontextformat)}>\n";
1250          $expout .= $this->writetext($question->questiontext, 3);
1251          $expout .= $this->write_files($question->questiontextfiles);
1252          $expout .= "    </questiontext>\n";
1253          $expout .= "    <generalfeedback {$this->format($question->generalfeedbackformat)}>\n";
1254          $expout .= $this->writetext($question->generalfeedback, 3);
1255          $expout .= $this->write_files($question->generalfeedbackfiles);
1256          $expout .= "    </generalfeedback>\n";
1257          if ($question->qtype != 'multianswer') {
1258              $expout .= "    <defaultgrade>{$question->defaultmark}</defaultgrade>\n";
1259          }
1260          $expout .= "    <penalty>{$question->penalty}</penalty>\n";
1261          $expout .= "    <hidden>{$question->status}</hidden>\n";
1262          $expout .= "    <idnumber>{$idnumber}</idnumber>\n";
1263  
1264          // The rest of the output depends on question type.
1265          switch($question->qtype) {
1266              case 'category':
1267                  // Not a qtype really - dummy used for category switching.
1268                  break;
1269  
1270              case 'truefalse':
1271                  $trueanswer = $question->options->answers[$question->options->trueanswer];
1272                  $trueanswer->answer = 'true';
1273                  $expout .= $this->write_answer($trueanswer);
1274  
1275                  $falseanswer = $question->options->answers[$question->options->falseanswer];
1276                  $falseanswer->answer = 'false';
1277                  $expout .= $this->write_answer($falseanswer);
1278                  break;
1279  
1280              case 'multichoice':
1281                  $expout .= "    <single>" . $this->get_single($question->options->single) .
1282                          "</single>\n";
1283                  $expout .= "    <shuffleanswers>" .
1284                          $this->get_single($question->options->shuffleanswers) .
1285                          "</shuffleanswers>\n";
1286                  $expout .= "    <answernumbering>" . $question->options->answernumbering .
1287                      "</answernumbering>\n";
1288                  $expout .= "    <showstandardinstruction>" . $question->options->showstandardinstruction .
1289                      "</showstandardinstruction>\n";
1290                  $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
1291                  $expout .= $this->write_answers($question->options->answers);
1292                  break;
1293  
1294              case 'shortanswer':
1295                  $expout .= "    <usecase>{$question->options->usecase}</usecase>\n";
1296                  $expout .= $this->write_answers($question->options->answers);
1297                  break;
1298  
1299              case 'numerical':
1300                  foreach ($question->options->answers as $answer) {
1301                      $expout .= $this->write_answer($answer,
1302                              "      <tolerance>{$answer->tolerance}</tolerance>\n");
1303                  }
1304  
1305                  $units = $question->options->units;
1306                  if (count($units)) {
1307                      $expout .= "<units>\n";
1308                      foreach ($units as $unit) {
1309                          $expout .= "  <unit>\n";
1310                          $expout .= "    <multiplier>{$unit->multiplier}</multiplier>\n";
1311                          $expout .= "    <unit_name>{$unit->unit}</unit_name>\n";
1312                          $expout .= "  </unit>\n";
1313                      }
1314                      $expout .= "</units>\n";
1315                  }
1316                  if (isset($question->options->unitgradingtype)) {
1317                      $expout .= "    <unitgradingtype>" . $question->options->unitgradingtype .
1318                              "</unitgradingtype>\n";
1319                  }
1320                  if (isset($question->options->unitpenalty)) {
1321                      $expout .= "    <unitpenalty>{$question->options->unitpenalty}</unitpenalty>\n";
1322                  }
1323                  if (isset($question->options->showunits)) {
1324                      $expout .= "    <showunits>{$question->options->showunits}</showunits>\n";
1325                  }
1326                  if (isset($question->options->unitsleft)) {
1327                      $expout .= "    <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
1328                  }
1329                  if (!empty($question->options->instructionsformat)) {
1330                      $files = $fs->get_area_files($contextid, 'qtype_numerical',
1331                              'instruction', $question->id);
1332                      $expout .= "    <instructions " .
1333                              $this->format($question->options->instructionsformat) . ">\n";
1334                      $expout .= $this->writetext($question->options->instructions, 3);
1335                      $expout .= $this->write_files($files);
1336                      $expout .= "    </instructions>\n";
1337                  }
1338                  break;
1339  
1340              case 'match':
1341                  $expout .= "    <shuffleanswers>" .
1342                          $this->get_single($question->options->shuffleanswers) .
1343                          "</shuffleanswers>\n";
1344                  $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
1345                  foreach ($question->options->subquestions as $subquestion) {
1346                      $files = $fs->get_area_files($contextid, 'qtype_match',
1347                              'subquestion', $subquestion->id);
1348                      $expout .= "    <subquestion " .
1349                              $this->format($subquestion->questiontextformat) . ">\n";
1350                      $expout .= $this->writetext($subquestion->questiontext, 3);
1351                      $expout .= $this->write_files($files);
1352                      $expout .= "      <answer>\n";
1353                      $expout .= $this->writetext($subquestion->answertext, 4);
1354                      $expout .= "      </answer>\n";
1355                      $expout .= "    </subquestion>\n";
1356                  }
1357                  break;
1358  
1359              case 'description':
1360                  // Nothing else to do.
1361                  break;
1362  
1363              case 'multianswer':
1364                  foreach ($question->options->questions as $index => $subq) {
1365                      $expout = str_replace('{#' . $index . '}', $subq->questiontext, $expout);
1366                  }
1367                  break;
1368  
1369              case 'essay':
1370                  $expout .= "    <responseformat>" . $question->options->responseformat .
1371                          "</responseformat>\n";
1372                  $expout .= "    <responserequired>" . $question->options->responserequired .
1373                          "</responserequired>\n";
1374                  $expout .= "    <responsefieldlines>" . $question->options->responsefieldlines .
1375                          "</responsefieldlines>\n";
1376                  $expout .= "    <minwordlimit>" . $question->options->minwordlimit .
1377                          "</minwordlimit>\n";
1378                  $expout .= "    <maxwordlimit>" . $question->options->maxwordlimit .
1379                          "</maxwordlimit>\n";
1380                  $expout .= "    <attachments>" . $question->options->attachments .
1381                          "</attachments>\n";
1382                  $expout .= "    <attachmentsrequired>" . $question->options->attachmentsrequired .
1383                          "</attachmentsrequired>\n";
1384                  $expout .= "    <maxbytes>" . $question->options->maxbytes .
1385                          "</maxbytes>\n";
1386                  $expout .= "    <filetypeslist>" . $question->options->filetypeslist .
1387                          "</filetypeslist>\n";
1388                  $expout .= "    <graderinfo " .
1389                          $this->format($question->options->graderinfoformat) . ">\n";
1390                  $expout .= $this->writetext($question->options->graderinfo, 3);
1391                  $expout .= $this->write_files($fs->get_area_files($contextid, 'qtype_essay',
1392                          'graderinfo', $question->id));
1393                  $expout .= "    </graderinfo>\n";
1394                  $expout .= "    <responsetemplate " .
1395                          $this->format($question->options->responsetemplateformat) . ">\n";
1396                  $expout .= $this->writetext($question->options->responsetemplate, 3);
1397                  $expout .= "    </responsetemplate>\n";
1398                  break;
1399  
1400              case 'calculated':
1401              case 'calculatedsimple':
1402              case 'calculatedmulti':
1403                  $expout .= "    <synchronize>{$question->options->synchronize}</synchronize>\n";
1404                  $expout .= "    <single>{$question->options->single}</single>\n";
1405                  $expout .= "    <answernumbering>" . $question->options->answernumbering .
1406                          "</answernumbering>\n";
1407                  $expout .= "    <shuffleanswers>" . $question->options->shuffleanswers .
1408                          "</shuffleanswers>\n";
1409  
1410                  $component = 'qtype_' . $question->qtype;
1411                  $files = $fs->get_area_files($contextid, $component,
1412                          'correctfeedback', $question->id);
1413                  $expout .= "    <correctfeedback>\n";
1414                  $expout .= $this->writetext($question->options->correctfeedback, 3);
1415                  $expout .= $this->write_files($files);
1416                  $expout .= "    </correctfeedback>\n";
1417  
1418                  $files = $fs->get_area_files($contextid, $component,
1419                          'partiallycorrectfeedback', $question->id);
1420                  $expout .= "    <partiallycorrectfeedback>\n";
1421                  $expout .= $this->writetext($question->options->partiallycorrectfeedback, 3);
1422                  $expout .= $this->write_files($files);
1423                  $expout .= "    </partiallycorrectfeedback>\n";
1424  
1425                  $files = $fs->get_area_files($contextid, $component,
1426                          'incorrectfeedback', $question->id);
1427                  $expout .= "    <incorrectfeedback>\n";
1428                  $expout .= $this->writetext($question->options->incorrectfeedback, 3);
1429                  $expout .= $this->write_files($files);
1430                  $expout .= "    </incorrectfeedback>\n";
1431  
1432                  foreach ($question->options->answers as $answer) {
1433                      $percent = 100 * $answer->fraction;
1434                      $expout .= "<answer fraction=\"{$percent}\">\n";
1435                      // The "<text/>" tags are an added feature, old files won't have them.
1436                      $expout .= "    <text>{$answer->answer}</text>\n";
1437                      $expout .= "    <tolerance>{$answer->tolerance}</tolerance>\n";
1438                      $expout .= "    <tolerancetype>{$answer->tolerancetype}</tolerancetype>\n";
1439                      $expout .= "    <correctanswerformat>" .
1440                              $answer->correctanswerformat . "</correctanswerformat>\n";
1441                      $expout .= "    <correctanswerlength>" .
1442                              $answer->correctanswerlength . "</correctanswerlength>\n";
1443                      $expout .= "    <feedback {$this->format($answer->feedbackformat)}>\n";
1444                      $files = $fs->get_area_files($contextid, $component,
1445                              'instruction', $question->id);
1446                      $expout .= $this->writetext($answer->feedback);
1447                      $expout .= $this->write_files($answer->feedbackfiles);
1448                      $expout .= "    </feedback>\n";
1449                      $expout .= "</answer>\n";
1450                  }
1451                  if (isset($question->options->unitgradingtype)) {
1452                      $expout .= "    <unitgradingtype>" .
1453                              $question->options->unitgradingtype . "</unitgradingtype>\n";
1454                  }
1455                  if (isset($question->options->unitpenalty)) {
1456                      $expout .= "    <unitpenalty>" .
1457                              $question->options->unitpenalty . "</unitpenalty>\n";
1458                  }
1459                  if (isset($question->options->showunits)) {
1460                      $expout .= "    <showunits>{$question->options->showunits}</showunits>\n";
1461                  }
1462                  if (isset($question->options->unitsleft)) {
1463                      $expout .= "    <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
1464                  }
1465  
1466                  if (isset($question->options->instructionsformat)) {
1467                      $files = $fs->get_area_files($contextid, $component,
1468                              'instruction', $question->id);
1469                      $expout .= "    <instructions " .
1470                              $this->format($question->options->instructionsformat) . ">\n";
1471                      $expout .= $this->writetext($question->options->instructions, 3);
1472                      $expout .= $this->write_files($files);
1473                      $expout .= "    </instructions>\n";
1474                  }
1475  
1476                  if (isset($question->options->units)) {
1477                      $units = $question->options->units;
1478                      if (count($units)) {
1479                          $expout .= "<units>\n";
1480                          foreach ($units as $unit) {
1481                              $expout .= "  <unit>\n";
1482                              $expout .= "    <multiplier>{$unit->multiplier}</multiplier>\n";
1483                              $expout .= "    <unit_name>{$unit->unit}</unit_name>\n";
1484                              $expout .= "  </unit>\n";
1485                          }
1486                          $expout .= "</units>\n";
1487                      }
1488                  }
1489  
1490                  // The tag $question->export_process has been set so we get all the
1491                  // data items in the database from the function
1492                  // qtype_calculated::get_question_options calculatedsimple defaults
1493                  // to calculated.
1494                  if (isset($question->options->datasets) && count($question->options->datasets)) {
1495                      $expout .= "<dataset_definitions>\n";
1496                      foreach ($question->options->datasets as $def) {
1497                          $expout .= "<dataset_definition>\n";
1498                          $expout .= "    <status>".$this->writetext($def->status)."</status>\n";
1499                          $expout .= "    <name>".$this->writetext($def->name)."</name>\n";
1500                          if ($question->qtype == 'calculated') {
1501                              $expout .= "    <type>calculated</type>\n";
1502                          } else {
1503                              $expout .= "    <type>calculatedsimple</type>\n";
1504                          }
1505                          $expout .= "    <distribution>" . $this->writetext($def->distribution) .
1506                                  "</distribution>\n";
1507                          $expout .= "    <minimum>" . $this->writetext($def->minimum) .
1508                                  "</minimum>\n";
1509                          $expout .= "    <maximum>" . $this->writetext($def->maximum) .
1510                                  "</maximum>\n";
1511                          $expout .= "    <decimals>" . $this->writetext($def->decimals) .
1512                                  "</decimals>\n";
1513                          $expout .= "    <itemcount>{$def->itemcount}</itemcount>\n";
1514                          if ($def->itemcount > 0) {
1515                              $expout .= "    <dataset_items>\n";
1516                              foreach ($def->items as $item) {
1517                                    $expout .= "        <dataset_item>\n";
1518                                    $expout .= "           <number>".$item->itemnumber."</number>\n";
1519                                    $expout .= "           <value>".$item->value."</value>\n";
1520                                    $expout .= "        </dataset_item>\n";
1521                              }
1522                              $expout .= "    </dataset_items>\n";
1523                              $expout .= "    <number_of_items>" . $def->number_of_items .
1524                                      "</number_of_items>\n";
1525                          }
1526                          $expout .= "</dataset_definition>\n";
1527                      }
1528                      $expout .= "</dataset_definitions>\n";
1529                  }
1530                  break;
1531  
1532              default:
1533                  // Try support by optional plugin.
1534                  if (!$data = $this->try_exporting_using_qtypes($question->qtype, $question)) {
1535                      $invalidquestion = true;
1536                  } else {
1537                      $expout .= $data;
1538                  }
1539          }
1540  
1541          // Output any hints.
1542          $expout .= $this->write_hints($question);
1543  
1544          // Write the question tags.
1545          if (core_tag_tag::is_enabled('core_question', 'question')) {
1546              $tagobjects = core_tag_tag::get_item_tags('core_question', 'question', $question->id);
1547  
1548              if (!empty($tagobjects)) {
1549                  $context = context::instance_by_id($contextid);
1550                  $sortedtagobjects = question_sort_tags($tagobjects, $context, [$this->course]);
1551  
1552                  if (!empty($sortedtagobjects->coursetags)) {
1553                      // Set them on the form to be rendered as existing tags.
1554                      $expout .= "    <coursetags>\n";
1555                      foreach ($sortedtagobjects->coursetags as $coursetag) {
1556                          $expout .= "      <tag>" . $this->writetext($coursetag, 0, true) . "</tag>\n";
1557                      }
1558                      $expout .= "    </coursetags>\n";
1559                  }
1560  
1561                  if (!empty($sortedtagobjects->tags)) {
1562                      $expout .= "    <tags>\n";
1563                      foreach ($sortedtagobjects->tags as $tag) {
1564                          $expout .= "      <tag>" . $this->writetext($tag, 0, true) . "</tag>\n";
1565                      }
1566                      $expout .= "    </tags>\n";
1567                  }
1568              }
1569          }
1570  
1571          // Close the question tag.
1572          $expout .= "  </question>\n";
1573          if ($invalidquestion) {
1574              return '';
1575          } else {
1576              return $expout;
1577          }
1578      }
1579  
1580      public function write_answers($answers) {
1581          if (empty($answers)) {
1582              return;
1583          }
1584          $output = '';
1585          foreach ($answers as $answer) {
1586              $output .= $this->write_answer($answer);
1587          }
1588          return $output;
1589      }
1590  
1591      public function write_answer($answer, $extra = '') {
1592          $percent = $answer->fraction * 100;
1593          $output = '';
1594          $output .= "    <answer fraction=\"{$percent}\" {$this->format($answer->answerformat)}>\n";
1595          $output .= $this->writetext($answer->answer, 3);
1596          $output .= $this->write_files($answer->answerfiles);
1597          $output .= "      <feedback {$this->format($answer->feedbackformat)}>\n";
1598          $output .= $this->writetext($answer->feedback, 4);
1599          $output .= $this->write_files($answer->feedbackfiles);
1600          $output .= "      </feedback>\n";
1601          $output .= $extra;
1602          $output .= "    </answer>\n";
1603          return $output;
1604      }
1605  
1606      /**
1607       * Write out the hints.
1608       * @param object $question the question definition data.
1609       * @return string XML to output.
1610       */
1611      public function write_hints($question) {
1612          if (empty($question->hints)) {
1613              return '';
1614          }
1615  
1616          $output = '';
1617          foreach ($question->hints as $hint) {
1618              $output .= $this->write_hint($hint, $question->contextid);
1619          }
1620          return $output;
1621      }
1622  
1623      /**
1624       * @param int $format a FORMAT_... constant.
1625       * @return string the attribute to add to an XML tag.
1626       */
1627      public function format($format) {
1628          return 'format="' . $this->get_format($format) . '"';
1629      }
1630  
1631      public function write_hint($hint, $contextid) {
1632          $fs = get_file_storage();
1633          $files = $fs->get_area_files($contextid, 'question', 'hint', $hint->id);
1634  
1635          $output = '';
1636          $output .= "    <hint {$this->format($hint->hintformat)}>\n";
1637          $output .= '      ' . $this->writetext($hint->hint);
1638  
1639          if (!empty($hint->shownumcorrect)) {
1640              $output .= "      <shownumcorrect/>\n";
1641          }
1642          if (!empty($hint->clearwrong)) {
1643              $output .= "      <clearwrong/>\n";
1644          }
1645  
1646          if (!empty($hint->options)) {
1647              $output .= '      <options>' . $this->xml_escape($hint->options) . "</options>\n";
1648          }
1649          $output .= $this->write_files($files);
1650          $output .= "    </hint>\n";
1651          return $output;
1652      }
1653  
1654      /**
1655       * Output the combined feedback fields.
1656       * @param object $questionoptions the question definition data.
1657       * @param int $questionid the question id.
1658       * @param int $contextid the question context id.
1659       * @return string XML to output.
1660       */
1661      public function write_combined_feedback($questionoptions, $questionid, $contextid) {
1662          $fs = get_file_storage();
1663          $output = '';
1664  
1665          $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
1666          foreach ($fields as $field) {
1667              $formatfield = $field . 'format';
1668              $files = $fs->get_area_files($contextid, 'question', $field, $questionid);
1669  
1670              $output .= "    <{$field} {$this->format($questionoptions->$formatfield)}>\n";
1671              $output .= '      ' . $this->writetext($questionoptions->$field);
1672              $output .= $this->write_files($files);
1673              $output .= "    </{$field}>\n";
1674          }
1675  
1676          if (!empty($questionoptions->shownumcorrect)) {
1677              $output .= "    <shownumcorrect/>\n";
1678          }
1679          return $output;
1680      }
1681  }