Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

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