Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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   * Defines the base class for question import and export formats.
  19   *
  20   * @package    moodlecore
  21   * @subpackage questionbank
  22   * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  
  30  /**
  31   * Base class for question import and export formats.
  32   *
  33   * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class qformat_default {
  37  
  38      public $displayerrors = true;
  39      public $category = null;
  40      public $questions = array();
  41      public $course = null;
  42      public $filename = '';
  43      public $realfilename = '';
  44      public $matchgrades = 'error';
  45      public $catfromfile = 0;
  46      public $contextfromfile = 0;
  47      public $cattofile = 0;
  48      public $contexttofile = 0;
  49      public $questionids = array();
  50      public $importerrors = 0;
  51      public $stoponerror = true;
  52      public $translator = null;
  53      public $canaccessbackupdata = true;
  54      protected $importcontext = null;
  55      /** @var bool $displayprogress Whether to display progress. */
  56      public $displayprogress = true;
  57  
  58      // functions to indicate import/export functionality
  59      // override to return true if implemented
  60  
  61      /** @return bool whether this plugin provides import functionality. */
  62      public function provide_import() {
  63          return false;
  64      }
  65  
  66      /** @return bool whether this plugin provides export functionality. */
  67      public function provide_export() {
  68          return false;
  69      }
  70  
  71      /** The string mime-type of the files that this plugin reads or writes. */
  72      public function mime_type() {
  73          return mimeinfo('type', $this->export_file_extension());
  74      }
  75  
  76      /**
  77       * @return string the file extension (including .) that is normally used for
  78       * files handled by this plugin.
  79       */
  80      public function export_file_extension() {
  81          return '.txt';
  82      }
  83  
  84      /**
  85       * Check if the given file is capable of being imported by this plugin.
  86       *
  87       * Note that expensive or detailed integrity checks on the file should
  88       * not be performed by this method. Simple file type or magic-number tests
  89       * would be suitable.
  90       *
  91       * @param stored_file $file the file to check
  92       * @return bool whether this plugin can import the file
  93       */
  94      public function can_import_file($file) {
  95          return ($file->get_mimetype() == $this->mime_type());
  96      }
  97  
  98      /**
  99       * Validate the given file.
 100       *
 101       * For more expensive or detailed integrity checks.
 102       *
 103       * @param stored_file $file the file to check
 104       * @return string the error message that occurred while validating the given file
 105       */
 106      public function validate_file(stored_file $file): string {
 107          return '';
 108      }
 109  
 110      /**
 111       * Check if the given file has the required utf8 encoding.
 112       *
 113       * @param stored_file $file the file to check
 114       * @return string the error message if the file encoding is not UTF-8
 115       */
 116      protected function validate_is_utf8_file(stored_file $file): string {
 117          if (!mb_check_encoding($file->get_content(), "UTF-8")) {
 118              return get_string('importwrongfileencoding', 'question',  $this->get_name());
 119          }
 120          return '';
 121      }
 122  
 123      /**
 124       * Return the localized pluginname string for the question format.
 125       *
 126       * @return string the pluginname string for the question format
 127       */
 128      protected function get_name(): string {
 129          return get_string('pluginname', get_class($this));
 130      }
 131  
 132      // Accessor methods
 133  
 134      /**
 135       * set the category
 136       * @param object category the category object
 137       */
 138      public function setCategory($category) {
 139          if (count($this->questions)) {
 140              debugging('You shouldn\'t call setCategory after setQuestions');
 141          }
 142          $this->category = $category;
 143          $this->importcontext = context::instance_by_id($this->category->contextid);
 144      }
 145  
 146      /**
 147       * Set the specific questions to export. Should not include questions with
 148       * parents (sub questions of cloze question type).
 149       * Only used for question export.
 150       * @param array of question objects
 151       */
 152      public function setQuestions($questions) {
 153          if ($this->category !== null) {
 154              debugging('You shouldn\'t call setQuestions after setCategory');
 155          }
 156          $this->questions = $questions;
 157      }
 158  
 159      /**
 160       * set the course class variable
 161       * @param course object Moodle course variable
 162       */
 163      public function setCourse($course) {
 164          $this->course = $course;
 165      }
 166  
 167      /**
 168       * set an array of contexts.
 169       * @param array $contexts Moodle course variable
 170       */
 171      public function setContexts($contexts) {
 172          $this->contexts = $contexts;
 173          $this->translator = new core_question\local\bank\context_to_string_translator($this->contexts);
 174      }
 175  
 176      /**
 177       * set the filename
 178       * @param string filename name of file to import/export
 179       */
 180      public function setFilename($filename) {
 181          $this->filename = $filename;
 182      }
 183  
 184      /**
 185       * set the "real" filename
 186       * (this is what the user typed, regardless of wha happened next)
 187       * @param string realfilename name of file as typed by user
 188       */
 189      public function setRealfilename($realfilename) {
 190          $this->realfilename = $realfilename;
 191      }
 192  
 193      /**
 194       * set matchgrades
 195       * @param string matchgrades error or nearest for grades
 196       */
 197      public function setMatchgrades($matchgrades) {
 198          $this->matchgrades = $matchgrades;
 199      }
 200  
 201      /**
 202       * set catfromfile
 203       * @param bool catfromfile allow categories embedded in import file
 204       */
 205      public function setCatfromfile($catfromfile) {
 206          $this->catfromfile = $catfromfile;
 207      }
 208  
 209      /**
 210       * set contextfromfile
 211       * @param bool $contextfromfile allow contexts embedded in import file
 212       */
 213      public function setContextfromfile($contextfromfile) {
 214          $this->contextfromfile = $contextfromfile;
 215      }
 216  
 217      /**
 218       * set cattofile
 219       * @param bool cattofile exports categories within export file
 220       */
 221      public function setCattofile($cattofile) {
 222          $this->cattofile = $cattofile;
 223      }
 224  
 225      /**
 226       * set contexttofile
 227       * @param bool cattofile exports categories within export file
 228       */
 229      public function setContexttofile($contexttofile) {
 230          $this->contexttofile = $contexttofile;
 231      }
 232  
 233      /**
 234       * set stoponerror
 235       * @param bool stoponerror stops database write if any errors reported
 236       */
 237      public function setStoponerror($stoponerror) {
 238          $this->stoponerror = $stoponerror;
 239      }
 240  
 241      /**
 242       * @param bool $canaccess Whether the current use can access the backup data folder. Determines
 243       * where export files are saved.
 244       */
 245      public function set_can_access_backupdata($canaccess) {
 246          $this->canaccessbackupdata = $canaccess;
 247      }
 248  
 249      /**
 250       * Change whether to display progress messages.
 251       * There is normally no need to use this function as the
 252       * default for $displayprogress is true.
 253       * Set to false for unit tests.
 254       * @param bool $displayprogress
 255       */
 256      public function set_display_progress($displayprogress) {
 257          $this->displayprogress = $displayprogress;
 258      }
 259  
 260      /***********************
 261       * IMPORTING FUNCTIONS
 262       ***********************/
 263  
 264      /**
 265       * Handle parsing error
 266       */
 267      protected function error($message, $text='', $questionname='') {
 268          $importerrorquestion = get_string('importerrorquestion', 'question');
 269  
 270          echo "<div class=\"importerror\">\n";
 271          echo "<strong>{$importerrorquestion} {$questionname}</strong>";
 272          if (!empty($text)) {
 273              $text = s($text);
 274              echo "<blockquote>{$text}</blockquote>\n";
 275          }
 276          echo "<strong>{$message}</strong>\n";
 277          echo "</div>";
 278  
 279          $this->importerrors++;
 280      }
 281  
 282      /**
 283       * Import for questiontype plugins
 284       * Do not override.
 285       * @param data mixed The segment of data containing the question
 286       * @param question object processed (so far) by standard import code if appropriate
 287       * @param extra mixed any additional format specific data that may be passed by the format
 288       * @param qtypehint hint about a question type from format
 289       * @return object question object suitable for save_options() or false if cannot handle
 290       */
 291      public function try_importing_using_qtypes($data, $question = null, $extra = null,
 292              $qtypehint = '') {
 293  
 294          // work out what format we are using
 295          $formatname = substr(get_class($this), strlen('qformat_'));
 296          $methodname = "import_from_{$formatname}";
 297  
 298          //first try importing using a hint from format
 299          if (!empty($qtypehint)) {
 300              $qtype = question_bank::get_qtype($qtypehint, false);
 301              if (is_object($qtype) && method_exists($qtype, $methodname)) {
 302                  $question = $qtype->$methodname($data, $question, $this, $extra);
 303                  if ($question) {
 304                      return $question;
 305                  }
 306              }
 307          }
 308  
 309          // loop through installed questiontypes checking for
 310          // function to handle this question
 311          foreach (question_bank::get_all_qtypes() as $qtype) {
 312              if (method_exists($qtype, $methodname)) {
 313                  if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
 314                      return $question;
 315                  }
 316              }
 317          }
 318          return false;
 319      }
 320  
 321      /**
 322       * Perform any required pre-processing
 323       * @return bool success
 324       */
 325      public function importpreprocess() {
 326          return true;
 327      }
 328  
 329      /**
 330       * Process the file
 331       * This method should not normally be overidden
 332       * @return bool success
 333       */
 334      public function importprocess() {
 335          global $USER, $DB, $OUTPUT;
 336  
 337          // Raise time and memory, as importing can be quite intensive.
 338          core_php_time_limit::raise();
 339          raise_memory_limit(MEMORY_EXTRA);
 340  
 341          // STAGE 1: Parse the file
 342          if ($this->displayprogress) {
 343              echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
 344          }
 345  
 346          if (! $lines = $this->readdata($this->filename)) {
 347              echo $OUTPUT->notification(get_string('cannotread', 'question'));
 348              return false;
 349          }
 350  
 351          if (!$questions = $this->readquestions($lines)) {   // Extract all the questions
 352              echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
 353              return false;
 354          }
 355  
 356          // STAGE 2: Write data to database
 357          if ($this->displayprogress) {
 358              echo $OUTPUT->notification(get_string('importingquestions', 'question',
 359                      $this->count_questions($questions)), 'notifysuccess');
 360          }
 361  
 362          // check for errors before we continue
 363          if ($this->stoponerror and ($this->importerrors>0)) {
 364              echo $OUTPUT->notification(get_string('importparseerror', 'question'));
 365              return true;
 366          }
 367  
 368          // get list of valid answer grades
 369          $gradeoptionsfull = question_bank::fraction_options_full();
 370  
 371          // check answer grades are valid
 372          // (now need to do this here because of 'stop on error': MDL-10689)
 373          $gradeerrors = 0;
 374          $goodquestions = array();
 375          foreach ($questions as $question) {
 376              if (!empty($question->fraction) and (is_array($question->fraction))) {
 377                  $fractions = $question->fraction;
 378                  $invalidfractions = array();
 379                  foreach ($fractions as $key => $fraction) {
 380                      $newfraction = match_grade_options($gradeoptionsfull, $fraction,
 381                              $this->matchgrades);
 382                      if ($newfraction === false) {
 383                          $invalidfractions[] = $fraction;
 384                      } else {
 385                          $fractions[$key] = $newfraction;
 386                      }
 387                  }
 388                  if ($invalidfractions) {
 389                      echo $OUTPUT->notification(get_string('invalidgrade', 'question',
 390                              implode(', ', $invalidfractions)));
 391                      ++$gradeerrors;
 392                      continue;
 393                  } else {
 394                      $question->fraction = $fractions;
 395                  }
 396              }
 397              $goodquestions[] = $question;
 398          }
 399          $questions = $goodquestions;
 400  
 401          // check for errors before we continue
 402          if ($this->stoponerror && $gradeerrors > 0) {
 403              return false;
 404          }
 405  
 406          // count number of questions processed
 407          $count = 0;
 408  
 409          foreach ($questions as $question) {   // Process and store each question
 410              $transaction = $DB->start_delegated_transaction();
 411  
 412              // reset the php timeout
 413              core_php_time_limit::raise();
 414  
 415              // check for category modifiers
 416              if ($question->qtype == 'category') {
 417                  if ($this->catfromfile) {
 418                      // find/create category object
 419                      $catpath = $question->category;
 420                      $newcategory = $this->create_category_path($catpath, $question);
 421                      if (!empty($newcategory)) {
 422                          $this->category = $newcategory;
 423                      }
 424                  }
 425                  $transaction->allow_commit();
 426                  continue;
 427              }
 428              $question->context = $this->importcontext;
 429  
 430              $count++;
 431  
 432              if ($this->displayprogress) {
 433                  echo "<hr /><p><b>{$count}</b>. " . $this->format_question_text($question) . "</p>";
 434              }
 435  
 436              $question->category = $this->category->id;
 437              $question->stamp = make_unique_id_code();  // Set the unique code (not to be changed)
 438  
 439              $question->createdby = $USER->id;
 440              $question->timecreated = time();
 441              $question->modifiedby = $USER->id;
 442              $question->timemodified = time();
 443              if (isset($question->idnumber)) {
 444                  if ((string) $question->idnumber === '') {
 445                      // Id number not really set. Get rid of it.
 446                      unset($question->idnumber);
 447                  } else {
 448                      if ($DB->record_exists('question_bank_entries',
 449                              ['idnumber' => $question->idnumber, 'questioncategoryid' => $question->category])) {
 450                          // We cannot have duplicate idnumbers in a category. Just remove it.
 451                          unset($question->idnumber);
 452                      }
 453                  }
 454              }
 455  
 456              $fileoptions = array(
 457                      'subdirs' => true,
 458                      'maxfiles' => -1,
 459                      'maxbytes' => 0,
 460                  );
 461  
 462              $question->id = $DB->insert_record('question', $question);
 463              // Create a bank entry for each question imported.
 464              $questionbankentry = new \stdClass();
 465              $questionbankentry->questioncategoryid = $question->category;
 466              $questionbankentry->idnumber = $question->idnumber ?? null;
 467              $questionbankentry->ownerid = $question->createdby;
 468              $questionbankentry->id = $DB->insert_record('question_bank_entries', $questionbankentry);
 469              // Create a version for each question imported.
 470              $questionversion = new \stdClass();
 471              $questionversion->questionbankentryid = $questionbankentry->id;
 472              $questionversion->questionid = $question->id;
 473              $questionversion->version = 1;
 474              $questionversion->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
 475              $questionversion->id = $DB->insert_record('question_versions', $questionversion);
 476  
 477              if (isset($question->questiontextitemid)) {
 478                  $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
 479                          $this->importcontext->id, 'question', 'questiontext', $question->id,
 480                          $fileoptions, $question->questiontext);
 481              } else if (isset($question->questiontextfiles)) {
 482                  foreach ($question->questiontextfiles as $file) {
 483                      question_bank::get_qtype($question->qtype)->import_file(
 484                              $this->importcontext, 'question', 'questiontext', $question->id, $file);
 485                  }
 486              }
 487              if (isset($question->generalfeedbackitemid)) {
 488                  $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
 489                          $this->importcontext->id, 'question', 'generalfeedback', $question->id,
 490                          $fileoptions, $question->generalfeedback);
 491              } else if (isset($question->generalfeedbackfiles)) {
 492                  foreach ($question->generalfeedbackfiles as $file) {
 493                      question_bank::get_qtype($question->qtype)->import_file(
 494                              $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
 495                  }
 496              }
 497              $DB->update_record('question', $question);
 498  
 499              $this->questionids[] = $question->id;
 500  
 501              // Now to save all the answers and type-specific options
 502  
 503              $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
 504              $event = \core\event\question_created::create_from_question_instance($question, $this->importcontext);
 505              $event->trigger();
 506  
 507              if (core_tag_tag::is_enabled('core_question', 'question')) {
 508                  // Is the current context we're importing in a course context?
 509                  $importingcontext = $this->importcontext;
 510                  $importingcoursecontext = $importingcontext->get_course_context(false);
 511                  $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
 512  
 513                  if (!empty($question->coursetags)) {
 514                      if ($isimportingcontextcourseoractivity) {
 515                          $mergedtags = array_merge($question->coursetags, $question->tags);
 516  
 517                          core_tag_tag::set_item_tags('core_question', 'question', $question->id,
 518                              $question->context, $mergedtags);
 519                      } else {
 520                          core_tag_tag::set_item_tags('core_question', 'question', $question->id,
 521                              context_course::instance($this->course->id), $question->coursetags);
 522  
 523                          if (!empty($question->tags)) {
 524                              core_tag_tag::set_item_tags('core_question', 'question', $question->id,
 525                                  $importingcontext, $question->tags);
 526                          }
 527                      }
 528                  } else if (!empty($question->tags)) {
 529                      core_tag_tag::set_item_tags('core_question', 'question', $question->id,
 530                          $question->context, $question->tags);
 531                  }
 532              }
 533  
 534              if (!empty($result->error)) {
 535                  echo $OUTPUT->notification($result->error);
 536                  // Can't use $transaction->rollback(); since it requires an exception,
 537                  // and I don't want to rewrite this code to change the error handling now.
 538                  $DB->force_transaction_rollback();
 539                  return false;
 540              }
 541  
 542              $transaction->allow_commit();
 543  
 544              if (!empty($result->notice)) {
 545                  echo $OUTPUT->notification($result->notice);
 546                  return true;
 547              }
 548  
 549          }
 550          return true;
 551      }
 552  
 553      /**
 554       * Count all non-category questions in the questions array.
 555       *
 556       * @param array questions An array of question objects.
 557       * @return int The count.
 558       *
 559       */
 560      protected function count_questions($questions) {
 561          $count = 0;
 562          if (!is_array($questions)) {
 563              return $count;
 564          }
 565          foreach ($questions as $question) {
 566              if (!is_object($question) || !isset($question->qtype) ||
 567                      ($question->qtype == 'category')) {
 568                  continue;
 569              }
 570              $count++;
 571          }
 572          return $count;
 573      }
 574  
 575      /**
 576       * find and/or create the category described by a delimited list
 577       * e.g. $course$/tom/dick/harry or tom/dick/harry
 578       *
 579       * removes any context string no matter whether $getcontext is set
 580       * but if $getcontext is set then ignore the context and use selected category context.
 581       *
 582       * @param string catpath delimited category path
 583       * @param object $lastcategoryinfo Contains category information
 584       * @return mixed category object or null if fails
 585       */
 586      protected function create_category_path($catpath, $lastcategoryinfo = null) {
 587          global $DB;
 588          $catnames = $this->split_category_path($catpath);
 589          $parent = 0;
 590          $category = null;
 591  
 592          // check for context id in path, it might not be there in pre 1.9 exports
 593          $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
 594          if ($matchcount == 1) {
 595              $contextid = $this->translator->string_to_context($matches[1]);
 596              array_shift($catnames);
 597          } else {
 598              $contextid = false;
 599          }
 600  
 601          // Before 3.5, question categories could be created at top level.
 602          // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
 603          if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
 604              array_unshift($catnames, 'top');
 605          }
 606  
 607          if ($this->contextfromfile && $contextid !== false) {
 608              $context = context::instance_by_id($contextid);
 609              require_capability('moodle/question:add', $context);
 610          } else {
 611              $context = context::instance_by_id($this->category->contextid);
 612          }
 613          $this->importcontext = $context;
 614  
 615          // Now create any categories that need to be created.
 616          foreach ($catnames as $key => $catname) {
 617              if ($parent == 0) {
 618                  $category = question_get_top_category($context->id, true);
 619                  $parent = $category->id;
 620              } else if ($category = $DB->get_record('question_categories',
 621                      array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
 622                  // If this category is now the last one in the path we are processing ...
 623                  if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
 624                      // Do nothing unless the child category appears before the parent category
 625                      // in the imported xml file. Because the parent was created without info being available
 626                      // at that time, this allows the info to be added from the xml data.
 627                      if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== ''
 628                              && $category->info === '') {
 629                          $category->info = $lastcategoryinfo->info;
 630                          if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
 631                              $category->infoformat = $lastcategoryinfo->infoformat;
 632                          }
 633                      }
 634                      // Same for idnumber.
 635                      if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== ''
 636                              && $category->idnumber === '') {
 637                          $category->idnumber = $lastcategoryinfo->idnumber;
 638                      }
 639                      $DB->update_record('question_categories', $category);
 640                  }
 641                  $parent = $category->id;
 642              } else {
 643                  if ($catname == 'top') {
 644                      // Should not happen, but if it does just move on.
 645                      // Occurs when there has been some import/export that has created
 646                      // multiple nested 'top' categories (due to old bug solved by MDL-63165).
 647                      // This basically silently cleans up old errors. Not throwing an exception here.
 648                      continue;
 649                  }
 650                  require_capability('moodle/question:managecategory', $context);
 651                  // Create the new category. This will create all the categories in the catpath,
 652                  // though only the final category will have any info added if available.
 653                  $category = new stdClass();
 654                  $category->contextid = $context->id;
 655                  $category->name = $catname;
 656                  $category->info = '';
 657                  // Only add info (category description) for the final category in the catpath.
 658                  if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
 659                      if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== '') {
 660                          $category->info = $lastcategoryinfo->info;
 661                          if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
 662                              $category->infoformat = $lastcategoryinfo->infoformat;
 663                          }
 664                      }
 665                      // Same for idnumber.
 666                      if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== '') {
 667                          $category->idnumber = $lastcategoryinfo->idnumber;
 668                      }
 669                  }
 670                  $category->parent = $parent;
 671                  $category->sortorder = 999;
 672                  $category->stamp = make_unique_id_code();
 673                  $category->id = $DB->insert_record('question_categories', $category);
 674                  $parent = $category->id;
 675                  $event = \core\event\question_category_created::create_from_question_category_instance($category, $context);
 676                  $event->trigger();
 677              }
 678          }
 679          return $category;
 680      }
 681  
 682      /**
 683       * Return complete file within an array, one item per line
 684       * @param string filename name of file
 685       * @return mixed contents array or false on failure
 686       */
 687      protected function readdata($filename) {
 688          if (is_readable($filename)) {
 689              $filearray = file($filename);
 690  
 691              // If the first line of the file starts with a UTF-8 BOM, remove it.
 692              $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
 693  
 694              // Check for Macintosh OS line returns (ie file on one line), and fix.
 695              if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
 696                  return explode("\r", $filearray[0]);
 697              } else {
 698                  return $filearray;
 699              }
 700          }
 701          return false;
 702      }
 703  
 704      /**
 705       * Parses an array of lines into an array of questions,
 706       * where each item is a question object as defined by
 707       * readquestion().   Questions are defined as anything
 708       * between blank lines.
 709       *
 710       * NOTE this method used to take $context as a second argument. However, at
 711       * the point where this method was called, it was impossible to know what
 712       * context the quetsions were going to be saved into, so the value could be
 713       * wrong. Also, none of the standard question formats were using this argument,
 714       * so it was removed. See MDL-32220.
 715       *
 716       * If your format does not use blank lines as a delimiter
 717       * then you will need to override this method. Even then
 718       * try to use readquestion for each question
 719       * @param array lines array of lines from readdata
 720       * @return array array of question objects
 721       */
 722      protected function readquestions($lines) {
 723  
 724          $questions = array();
 725          $currentquestion = array();
 726  
 727          foreach ($lines as $line) {
 728              $line = trim($line);
 729              if (empty($line)) {
 730                  if (!empty($currentquestion)) {
 731                      if ($question = $this->readquestion($currentquestion)) {
 732                          $questions[] = $question;
 733                      }
 734                      $currentquestion = array();
 735                  }
 736              } else {
 737                  $currentquestion[] = $line;
 738              }
 739          }
 740  
 741          if (!empty($currentquestion)) {  // There may be a final question
 742              if ($question = $this->readquestion($currentquestion)) {
 743                  $questions[] = $question;
 744              }
 745          }
 746  
 747          return $questions;
 748      }
 749  
 750      /**
 751       * return an "empty" question
 752       * Somewhere to specify question parameters that are not handled
 753       * by import but are required db fields.
 754       * This should not be overridden.
 755       * @return object default question
 756       */
 757      protected function defaultquestion() {
 758          global $CFG;
 759          static $defaultshuffleanswers = null;
 760          if (is_null($defaultshuffleanswers)) {
 761              $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
 762          }
 763  
 764          $question = new stdClass();
 765          $question->shuffleanswers = $defaultshuffleanswers;
 766          $question->defaultmark = 1;
 767          $question->image = '';
 768          $question->usecase = 0;
 769          $question->multiplier = array();
 770          $question->questiontextformat = FORMAT_MOODLE;
 771          $question->generalfeedback = '';
 772          $question->generalfeedbackformat = FORMAT_MOODLE;
 773          $question->answernumbering = 'abc';
 774          $question->penalty = 0.3333333;
 775          $question->length = 1;
 776  
 777          // this option in case the questiontypes class wants
 778          // to know where the data came from
 779          $question->export_process = true;
 780          $question->import_process = true;
 781  
 782          $this->add_blank_combined_feedback($question);
 783  
 784          return $question;
 785      }
 786  
 787      /**
 788       * Construct a reasonable default question name, based on the start of the question text.
 789       * @param string $questiontext the question text.
 790       * @param string $default default question name to use if the constructed one comes out blank.
 791       * @return string a reasonable question name.
 792       */
 793      public function create_default_question_name($questiontext, $default) {
 794          $name = $this->clean_question_name(shorten_text($questiontext, 80));
 795          if ($name) {
 796              return $name;
 797          } else {
 798              return $default;
 799          }
 800      }
 801  
 802      /**
 803       * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
 804       * @param string $name the raw question name.
 805       * @return string a safe question name.
 806       */
 807      public function clean_question_name($name) {
 808          $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
 809          $name = trim($name);
 810          $trimlength = 251;
 811          while (core_text::strlen($name) > 255 && $trimlength > 0) {
 812              $name = shorten_text($name, $trimlength);
 813              $trimlength -= 10;
 814          }
 815          return $name;
 816      }
 817  
 818      /**
 819       * Add a blank combined feedback to a question object.
 820       * @param object question
 821       * @return object question
 822       */
 823      protected function add_blank_combined_feedback($question) {
 824          $question->correctfeedback = [
 825              'text' => '',
 826              'format' => $question->questiontextformat,
 827              'files' => []
 828          ];
 829          $question->partiallycorrectfeedback = [
 830              'text' => '',
 831              'format' => $question->questiontextformat,
 832              'files' => []
 833          ];
 834          $question->incorrectfeedback = [
 835              'text' => '',
 836              'format' => $question->questiontextformat,
 837              'files' => []
 838          ];
 839          return $question;
 840      }
 841  
 842      /**
 843       * Given the data known to define a question in
 844       * this format, this function converts it into a question
 845       * object suitable for processing and insertion into Moodle.
 846       *
 847       * If your format does not use blank lines to delimit questions
 848       * (e.g. an XML format) you must override 'readquestions' too
 849       * @param $lines mixed data that represents question
 850       * @return object question object
 851       */
 852      protected function readquestion($lines) {
 853          // We should never get there unless the qformat plugin is broken.
 854          throw new coding_exception('Question format plugin is missing important code: readquestion.');
 855  
 856          return null;
 857      }
 858  
 859      /**
 860       * Override if any post-processing is required
 861       * @return bool success
 862       */
 863      public function importpostprocess() {
 864          return true;
 865      }
 866  
 867      /*******************
 868       * EXPORT FUNCTIONS
 869       *******************/
 870  
 871      /**
 872       * Provide export functionality for plugin questiontypes
 873       * Do not override
 874       * @param name questiontype name
 875       * @param question object data to export
 876       * @param extra mixed any addition format specific data needed
 877       * @return string the data to append to export or false if error (or unhandled)
 878       */
 879      protected function try_exporting_using_qtypes($name, $question, $extra=null) {
 880          // work out the name of format in use
 881          $formatname = substr(get_class($this), strlen('qformat_'));
 882          $methodname = "export_to_{$formatname}";
 883  
 884          $qtype = question_bank::get_qtype($name, false);
 885          if (method_exists($qtype, $methodname)) {
 886              return $qtype->$methodname($question, $this, $extra);
 887          }
 888          return false;
 889      }
 890  
 891      /**
 892       * Do any pre-processing that may be required
 893       * @param bool success
 894       */
 895      public function exportpreprocess() {
 896          return true;
 897      }
 898  
 899      /**
 900       * Enable any processing to be done on the content
 901       * just prior to the file being saved
 902       * default is to do nothing
 903       * @param string output text
 904       * @param string processed output text
 905       */
 906      protected function presave_process($content) {
 907          return $content;
 908      }
 909  
 910      /**
 911       * Perform the export.
 912       * For most types this should not need to be overrided.
 913       *
 914       * @param   bool    $checkcapabilities Whether to check capabilities when exporting the questions.
 915       * @return  string  The content of the export.
 916       */
 917      public function exportprocess($checkcapabilities = true) {
 918          global $CFG, $DB;
 919  
 920          // Raise time and memory, as exporting can be quite intensive.
 921          core_php_time_limit::raise();
 922          raise_memory_limit(MEMORY_EXTRA);
 923  
 924          // Get the parents (from database) for this category.
 925          $parents = [];
 926          if ($this->category) {
 927              $parents = question_categorylist_parents($this->category->id);
 928          }
 929  
 930          // get the questions (from database) in this category
 931          // only get q's with no parents (no cloze subquestions specifically)
 932          if ($this->category) {
 933              // Export only the latest version of a question.
 934              $questions = get_questions_category($this->category, true, true, true, true);
 935          } else {
 936              $questions = $this->questions;
 937          }
 938  
 939          $count = 0;
 940  
 941          // results are first written into string (and then to a file)
 942          // so create/initialize the string here
 943          $expout = '';
 944  
 945          // track which category questions are in
 946          // if it changes we will record the category change in the output
 947          // file if selected. 0 means that it will get printed before the 1st question
 948          $trackcategory = 0;
 949  
 950          // Array of categories written to file.
 951          $writtencategories = [];
 952  
 953          foreach ($questions as $question) {
 954              // used by file api
 955              $questionbankentry = question_bank::load_question($question->id);
 956              $qcategory = $questionbankentry->category;
 957              $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $qcategory]);
 958              $question->contextid = $contextid;
 959              $question->idnumber = $questionbankentry->idnumber;
 960              if ($question->status === \core_question\local\bank\question_version_status::QUESTION_STATUS_READY) {
 961                  $question->status = 0;
 962              } else {
 963                  $question->status = 1;
 964              }
 965  
 966              // do not export hidden questions
 967              if (!empty($question->hidden)) {
 968                  continue;
 969              }
 970  
 971              // do not export random questions
 972              if ($question->qtype == 'random') {
 973                  continue;
 974              }
 975  
 976              // check if we need to record category change
 977              if ($this->cattofile) {
 978                  $addnewcat = false;
 979                  if ($question->category != $trackcategory) {
 980                      $addnewcat = true;
 981                      $trackcategory = $question->category;
 982                  }
 983                  $trackcategoryparents = question_categorylist_parents($trackcategory);
 984                  // Check if we need to record empty parents categories.
 985                  foreach ($trackcategoryparents as $trackcategoryparent) {
 986                      // If parent wasn't written.
 987                      if (!in_array($trackcategoryparent, $writtencategories)) {
 988                          // If parent is empty.
 989                          if (!count($DB->get_records('question_bank_entries', ['questioncategoryid' => $trackcategoryparent]))) {
 990                              $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
 991                              $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
 992                                  'name, info, infoformat, idnumber', MUST_EXIST);
 993                              if ($categoryinfo->name != 'top') {
 994                                  // Create 'dummy' question for parent category.
 995                                  $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
 996                                  $expout .= $this->writequestion($dummyquestion) . "\n";
 997                                  $writtencategories[] = $trackcategoryparent;
 998                              }
 999                          }
1000                      }
1001                  }
1002                  if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
1003                      $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
1004                      $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
1005                              'info, infoformat, idnumber', MUST_EXIST);
1006                      // Create 'dummy' question for category.
1007                      $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
1008                      $expout .= $this->writequestion($dummyquestion) . "\n";
1009                      $writtencategories[] = $trackcategory;
1010                  }
1011              }
1012  
1013              // Add the question to result.
1014              if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
1015                  $expquestion = $this->writequestion($question, $contextid);
1016                  // Don't add anything if witequestion returned nothing.
1017                  // This will permit qformat plugins to exclude some questions.
1018                  if ($expquestion !== null) {
1019                      $expout .= $expquestion . "\n";
1020                      $count++;
1021                  }
1022              }
1023          }
1024  
1025          // continue path for following error checks
1026          $course = $this->course;
1027          $continuepath = "{$CFG->wwwroot}/question/bank/exportquestions/export.php?courseid={$course->id}";
1028  
1029          // did we actually process anything
1030          if ($count==0) {
1031              throw new \moodle_exception('noquestions', 'question', $continuepath);
1032          }
1033  
1034          // final pre-process on exported data
1035          $expout = $this->presave_process($expout);
1036          return $expout;
1037      }
1038  
1039      /**
1040       * Create 'dummy' question for category export.
1041       * @param string $categoryname the name of the category
1042       * @param object $categoryinfo description of the category
1043       * @return stdClass 'dummy' question for category
1044       */
1045      protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
1046          $dummyquestion = new stdClass();
1047          $dummyquestion->qtype = 'category';
1048          $dummyquestion->category = $categoryname;
1049          $dummyquestion->id = 0;
1050          $dummyquestion->questiontextformat = '';
1051          $dummyquestion->contextid = 0;
1052          $dummyquestion->info = $categoryinfo->info;
1053          $dummyquestion->infoformat = $categoryinfo->infoformat;
1054          $dummyquestion->idnumber = $categoryinfo->idnumber;
1055          $dummyquestion->name = 'Switch category to ' . $categoryname;
1056          return $dummyquestion;
1057      }
1058  
1059      /**
1060       * get the category as a path (e.g., tom/dick/harry)
1061       * @param int id the id of the most nested catgory
1062       * @return string the path
1063       */
1064      protected function get_category_path($id, $includecontext = true) {
1065          global $DB;
1066  
1067          if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1068              throw new \moodle_exception('cannotfindcategory', 'error', '', $id);
1069          }
1070          $contextstring = $this->translator->context_to_string($category->contextid);
1071  
1072          $pathsections = array();
1073          do {
1074              $pathsections[] = $category->name;
1075              $id = $category->parent;
1076          } while ($category = $DB->get_record('question_categories', array('id' => $id)));
1077  
1078          if ($includecontext) {
1079              $pathsections[] = '$' . $contextstring . '$';
1080          }
1081  
1082          $path = $this->assemble_category_path(array_reverse($pathsections));
1083  
1084          return $path;
1085      }
1086  
1087      /**
1088       * Convert a list of category names, possibly preceeded by one of the
1089       * context tokens like $course$, into a string representation of the
1090       * category path.
1091       *
1092       * Names are separated by / delimiters. And /s in the name are replaced by //.
1093       *
1094       * To reverse the process and split the paths into names, use
1095       * {@link split_category_path()}.
1096       *
1097       * @param array $names
1098       * @return string
1099       */
1100      protected function assemble_category_path($names) {
1101          $escapednames = array();
1102          foreach ($names as $name) {
1103              $escapedname = str_replace('/', '//', $name);
1104              if (substr($escapedname, 0, 1) == '/') {
1105                  $escapedname = ' ' . $escapedname;
1106              }
1107              if (substr($escapedname, -1) == '/') {
1108                  $escapedname = $escapedname . ' ';
1109              }
1110              $escapednames[] = $escapedname;
1111          }
1112          return implode('/', $escapednames);
1113      }
1114  
1115      /**
1116       * Convert a string, as returned by {@link assemble_category_path()},
1117       * back into an array of category names.
1118       *
1119       * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
1120       * which matches the cleaning in question/bank/managecategories/category_form.php.
1121       *
1122       * @param string $path
1123       * @return array of category names.
1124       */
1125      protected function split_category_path($path) {
1126          $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1127          $names = array();
1128          foreach ($rawnames as $rawname) {
1129              $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
1130          }
1131          return $names;
1132      }
1133  
1134      /**
1135       * Do an post-processing that may be required
1136       * @return bool success
1137       */
1138      protected function exportpostprocess() {
1139          return true;
1140      }
1141  
1142      /**
1143       * convert a single question object into text output in the given
1144       * format.
1145       * This must be overriden
1146       * @param object question question object
1147       * @return mixed question export text or null if not implemented
1148       */
1149      protected function writequestion($question) {
1150          // if not overidden, then this is an error.
1151          throw new coding_exception('Question format plugin is missing important code: writequestion.');
1152          return null;
1153      }
1154  
1155      /**
1156       * Convert the question text to plain text, so it can safely be displayed
1157       * during import to let the user see roughly what is going on.
1158       */
1159      protected function format_question_text($question) {
1160          return s(question_utils::to_plain_text($question->questiontext,
1161                  $question->questiontextformat));
1162      }
1163  }
1164  
1165  class qformat_based_on_xml extends qformat_default {
1166  
1167      /**
1168       * A lot of imported files contain unwanted entities.
1169       * This method tries to clean up all known problems.
1170       * @param string str string to correct
1171       * @return string the corrected string
1172       */
1173      public function cleaninput($str) {
1174  
1175          $html_code_list = array(
1176              "&#039;" => "'",
1177              "&#8217;" => "'",
1178              "&#8220;" => "\"",
1179              "&#8221;" => "\"",
1180              "&#8211;" => "-",
1181              "&#8212;" => "-",
1182          );
1183          $str = strtr($str, $html_code_list);
1184          // Use core_text entities_to_utf8 function to convert only numerical entities.
1185          $str = core_text::entities_to_utf8($str, false);
1186          return $str;
1187      }
1188  
1189      /**
1190       * Return the array moodle is expecting
1191       * for an HTML text. No processing is done on $text.
1192       * qformat classes that want to process $text
1193       * for instance to import external images files
1194       * and recode urls in $text must overwrite this method.
1195       * @param array $text some HTML text string
1196       * @return array with keys text, format and files.
1197       */
1198      public function text_field($text) {
1199          return array(
1200              'text' => trim($text),
1201              'format' => FORMAT_HTML,
1202              'files' => array(),
1203          );
1204      }
1205  
1206      /**
1207       * Return the value of a node, given a path to the node
1208       * if it doesn't exist return the default value.
1209       * @param array xml data to read
1210       * @param array path path to node expressed as array
1211       * @param mixed default
1212       * @param bool istext process as text
1213       * @param string error if set value must exist, return false and issue message if not
1214       * @return mixed value
1215       */
1216      public function getpath($xml, $path, $default, $istext=false, $error='') {
1217          foreach ($path as $index) {
1218              if (!isset($xml[$index])) {
1219                  if (!empty($error)) {
1220                      $this->error($error);
1221                      return false;
1222                  } else {
1223                      return $default;
1224                  }
1225              }
1226  
1227              $xml = $xml[$index];
1228          }
1229  
1230          if ($istext) {
1231              if (!is_string($xml)) {
1232                  $this->error(get_string('invalidxml', 'qformat_xml'));
1233              }
1234              $xml = trim($xml);
1235          }
1236  
1237          return $xml;
1238      }
1239  }