Search moodle.org's
Developer Documentation

See Release Notes

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * The default questiontype class.
  19   *
  20   * @package    moodlecore
  21   * @subpackage questiontypes
  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  require_once($CFG->dirroot . '/question/engine/lib.php');
  30  
  31  
  32  /**
  33   * This is the base class for Moodle question types.
  34   *
  35   * There are detailed comments on each method, explaining what the method is
  36   * for, and the circumstances under which you might need to override it.
  37   *
  38   * Note: the questiontype API should NOT be considered stable yet. Very few
  39   * question types have been produced yet, so we do not yet know all the places
  40   * where the current API is insufficient. I would rather learn from the
  41   * experiences of the first few question type implementors, and improve the
  42   * interface to meet their needs, rather the freeze the API prematurely and
  43   * condem everyone to working round a clunky interface for ever afterwards.
  44   *
  45   * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
  46   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  47   */
  48  class question_type {
  49      protected $fileoptions = array(
  50          'subdirs' => true,
  51          'maxfiles' => -1,
  52          'maxbytes' => 0,
  53      );
  54  
  55      public function __construct() {
  56      }
  57  
  58      /**
  59       * @return string the name of this question type.
  60       */
  61      public function name() {
  62          return substr(get_class($this), 6);
  63      }
  64  
  65      /**
  66       * @return string the full frankenstyle name for this plugin.
  67       */
  68      public function plugin_name() {
  69          return get_class($this);
  70      }
  71  
  72      /**
  73       * @return string the name of this question type in the user's language.
  74       * You should not need to override this method, the default behaviour should be fine.
  75       */
  76      public function local_name() {
  77          return get_string('pluginname', $this->plugin_name());
  78      }
  79  
  80      /**
  81       * The name this question should appear as in the create new question
  82       * dropdown. Override this method to return false if you don't want your
  83       * question type to be createable, for example if it is an abstract base type,
  84       * otherwise, you should not need to override this method.
  85       *
  86       * @return mixed the desired string, or false to hide this question type in the menu.
  87       */
  88      public function menu_name() {
  89          return $this->local_name();
  90      }
  91  
  92      /**
  93       * @return bool override this to return false if this is not really a
  94       *      question type, for example the description question type is not
  95       *      really a question type.
  96       */
  97      public function is_real_question_type() {
  98          return true;
  99      }
 100  
 101      /**
 102       * @return bool true if this question type sometimes requires manual grading.
 103       */
 104      public function is_manual_graded() {
 105          return false;
 106      }
 107  
 108      /**
 109       * @param object $question a question of this type.
 110       * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt.
 111       * @return bool true if a particular instance of this question requires manual grading.
 112       */
 113      public function is_question_manual_graded($question, $otherquestionsinuse) {
 114          return $this->is_manual_graded();
 115      }
 116  
 117      /**
 118       * @return bool true if this question type can be used by the random question type.
 119       */
 120      public function is_usable_by_random() {
 121          return true;
 122      }
 123  
 124      /**
 125       * Whether this question type can perform a frequency analysis of student
 126       * responses.
 127       *
 128       * If this method returns true, you must implement the get_possible_responses
 129       * method, and the question_definition class must implement the
 130       * classify_response method.
 131       *
 132       * @return bool whether this report can analyse all the student responses
 133       * for things like the quiz statistics report.
 134       */
 135      public function can_analyse_responses() {
 136          // This works in most cases.
 137          return !$this->is_manual_graded();
 138      }
 139  
 140      /**
 141       * @return whether the question_answers.answer field needs to have
 142       * restore_decode_content_links_worker called on it.
 143       */
 144      public function has_html_answers() {
 145          return false;
 146      }
 147  
 148      /**
 149       * If your question type has a table that extends the question table, and
 150       * you want the base class to automatically save, backup and restore the extra fields,
 151       * override this method to return an array wherer the first element is the table name,
 152       * and the subsequent entries are the column names (apart from id and questionid).
 153       *
 154       * @return mixed array as above, or null to tell the base class to do nothing.
 155       */
 156      public function extra_question_fields() {
 157          return null;
 158      }
 159  
 160      /**
 161       * If you use extra_question_fields, overload this function to return question id field name
 162       *  in case you table use another name for this column
 163       */
 164      public function questionid_column_name() {
 165          return 'questionid';
 166      }
 167  
 168      /**
 169       * If your question type has a table that extends the question_answers table,
 170       * make this method return an array wherer the first element is the table name,
 171       * and the subsequent entries are the column names (apart from id and answerid).
 172       *
 173       * @return mixed array as above, or null to tell the base class to do nothing.
 174       */
 175      public function extra_answer_fields() {
 176          return null;
 177      }
 178  
 179      /**
 180       * If the quetsion type uses files in responses, then this method should
 181       * return an array of all the response variables that might have corresponding
 182       * files. For example, the essay qtype returns array('attachments', 'answers').
 183       *
 184       * @return array response variable names that may have associated files.
 185       */
 186      public function response_file_areas() {
 187          return array();
 188      }
 189  
 190      /**
 191       * Return an instance of the question editing form definition. This looks for a
 192       * class called edit_{$this->name()}_question_form in the file
 193       * question/type/{$this->name()}/edit_{$this->name()}_question_form.php
 194       * and if it exists returns an instance of it.
 195       *
 196       * @param string $submiturl passed on to the constructor call.
 197       * @return object an instance of the form definition, or null if one could not be found.
 198       */
 199      public function create_editing_form($submiturl, $question, $category,
 200              $contexts, $formeditable) {
 201          global $CFG;
 202          require_once($CFG->dirroot . '/question/type/edit_question_form.php');
 203          $definitionfile = $CFG->dirroot . '/question/type/' . $this->name() .
 204                  '/edit_' . $this->name() . '_form.php';
 205          if (!is_readable($definitionfile) || !is_file($definitionfile)) {
 206              throw new coding_exception($this->plugin_name() .
 207                      ' is missing the definition of its editing formin file ' .
 208                      $definitionfile . '.');
 209          }
 210          require_once($definitionfile);
 211          $classname = $this->plugin_name() . '_edit_form';
 212          if (!class_exists($classname)) {
 213              throw new coding_exception($this->plugin_name() .
 214                      ' does not define the class ' . $this->plugin_name() .
 215                      '_edit_form.');
 216          }
 217          return new $classname($submiturl, $question, $category, $contexts, $formeditable);
 218      }
 219  
 220      /**
 221       * @return string the full path of the folder this plugin's files live in.
 222       */
 223      public function plugin_dir() {
 224          global $CFG;
 225          return $CFG->dirroot . '/question/type/' . $this->name();
 226      }
 227  
 228      /**
 229       * @return string the URL of the folder this plugin's files live in.
 230       */
 231      public function plugin_baseurl() {
 232          global $CFG;
 233          return $CFG->wwwroot . '/question/type/' . $this->name();
 234      }
 235  
 236      /**
 237       * Get extra actions for a question of this type to add to the question bank edit menu.
 238       *
 239       * This method is called if the {@link edit_menu_column} is being used in the
 240       * question bank, which it is by default since Moodle 3.8. If applicable for
 241       * your question type, you can return arn array of {@link action_menu_link}s.
 242       * These will be added at the end of the Edit menu for this question.
 243       *
 244       * The $question object passed in will have a hard-to-predict set of fields,
 245       * because the fields present depend on which columns are included in the
 246       * question bank view. However, you can rely on 'id', 'createdby',
 247       * 'contextid', 'hidden' and 'category' (id) being present, and so you
 248       * can call question_has_capability_on without causing performance problems.
 249       *
 250       * @param stdClass $question the available information about the particular question the action is for.
 251       * @return action_menu_link[] any actions you want to add to the Edit menu for this question.
 252       */
 253      public function get_extra_question_bank_actions(stdClass $question): array {
 254          return [];
 255      }
 256  
 257      /**
 258       * This method should be overriden if you want to include a special heading or some other
 259       * html on a question editing page besides the question editing form.
 260       *
 261       * @param question_edit_form $mform a child of question_edit_form
 262       * @param object $question
 263       * @param string $wizardnow is '' for first page.
 264       */
 265      public function display_question_editing_page($mform, $question, $wizardnow) {
 266          global $OUTPUT;
 267          $heading = $this->get_heading(empty($question->id));
 268          echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
 269          $mform->display();
 270      }
 271  
 272      /**
 273       * Method called by display_question_editing_page and by question.php to get
 274       * heading for breadcrumbs.
 275       *
 276       * @return string the heading
 277       */
 278      public function get_heading($adding = false) {
 279          if ($adding) {
 280              $string = 'pluginnameadding';
 281          } else {
 282              $string = 'pluginnameediting';
 283          }
 284          return get_string($string, $this->plugin_name());
 285      }
 286  
 287      /**
 288       * Set any missing settings for this question to the default values. This is
 289       * called before displaying the question editing form.
 290       *
 291       * @param object $questiondata the question data, loaded from the databsae,
 292       *      or more likely a newly created question object that is only partially
 293       *      initialised.
 294       */
 295      public function set_default_options($questiondata) {
 296      }
 297  
 298      /**
 299       * Return default value for a given form element either from user_preferences table or $default.
 300       *
 301       * @param string $name the name of the form element.
 302       * @param mixed $default default value.
 303       * @return string|null default value for a given  form element.
 304       */
 305      public function get_default_value(string $name, $default): ?string {
 306          return get_user_preferences($this->plugin_name() . '_' . $name, $default ?? '0');
 307      }
 308  
 309      /**
 310       * Save the default value for a given form element in user_preferences table.
 311       *
 312       * @param string $name the name of the value to set.
 313       * @param string $value the setting value.
 314       */
 315      public function set_default_value(string $name, string $value): void {
 316          set_user_preference($this->plugin_name() . '_' . $name, $value);
 317      }
 318  
 319      /**
 320       * Save question defaults when creating new questions.
 321       *
 322       * @param stdClass $fromform data from the form.
 323       */
 324      public function save_defaults_for_new_questions(stdClass $fromform): void {
 325          // Some question types may not make use of the certain form elements, so
 326          // we need to do a check on the following generic form elements. For instance,
 327          // 'defaultmark' is not use in qtype_multianswer and 'penalty' in not used in
 328          // qtype_essay and qtype_recordrtc.
 329          if (isset($fromform->defaultmark)) {
 330              $this->set_default_value('defaultmark', $fromform->defaultmark);
 331          }
 332          if (isset($fromform->penalty)) {
 333              $this->set_default_value('penalty', $fromform->penalty);
 334          }
 335      }
 336  
 337      /**
 338       * Saves (creates or updates) a question.
 339       *
 340       * Given some question info and some data about the answers
 341       * this function parses, organises and saves the question
 342       * It is used by {@link question.php} when saving new data from
 343       * a form, and also by {@link import.php} when importing questions
 344       * This function in turn calls {@link save_question_options}
 345       * to save question-type specific data.
 346       *
 347       * Whether we are saving a new question or updating an existing one can be
 348       * determined by testing !empty($question->id). If it is not empty, we are updating.
 349       *
 350       * The question will be saved in category $form->category.
 351       *
 352       * @param object $question the question object which should be updated. For a
 353       *      new question will be mostly empty.
 354       * @param object $form the object containing the information to save, as if
 355       *      from the question editing form.
 356       * @param object $course not really used any more.
 357       * @return object On success, return the new question object. On failure,
 358       *       return an object as follows. If the error object has an errors field,
 359       *       display that as an error message. Otherwise, the editing form will be
 360       *       redisplayed with validation errors, from validation_errors field, which
 361       *       is itself an object, shown next to the form fields. (I don't think this
 362       *       is accurate any more.)
 363       */
 364      public function save_question($question, $form) {
 365          global $USER, $DB;
 366  
 367          // The actual update/insert done with multiple DB access, so we do it in a transaction.
 368          $transaction = $DB->start_delegated_transaction ();
 369  
 370          list($question->category) = explode(',', $form->category);
 371          $context = $this->get_context_by_category_id($question->category);
 372  
 373          // This default implementation is suitable for most
 374          // question types.
 375  
 376          // First, save the basic question itself.
 377          $question->name = trim($form->name);
 378          $question->parent = isset($form->parent) ? $form->parent : 0;
 379          $question->length = $this->actual_number_of_questions($question);
 380          $question->penalty = isset($form->penalty) ? $form->penalty : 0;
 381  
 382          // The trim call below has the effect of casting any strange values received,
 383          // like null or false, to an appropriate string, so we only need to test for
 384          // missing values. Be careful not to break the value '0' here.
 385          if (!isset($form->questiontext['text'])) {
 386              $question->questiontext = '';
 387          } else {
 388              $question->questiontext = trim($form->questiontext['text']);
 389          }
 390          $question->questiontextformat = !empty($form->questiontext['format']) ?
 391                  $form->questiontext['format'] : 0;
 392  
 393          if (empty($form->generalfeedback['text'])) {
 394              $question->generalfeedback = '';
 395          } else {
 396              $question->generalfeedback = trim($form->generalfeedback['text']);
 397          }
 398          $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
 399                  $form->generalfeedback['format'] : 0;
 400  
 401          if ($question->name === '') {
 402              $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
 403              if ($question->name === '') {
 404                  $question->name = '-';
 405              }
 406          }
 407  
 408          if ($question->penalty > 1 or $question->penalty < 0) {
 409              $question->errors['penalty'] = get_string('invalidpenalty', 'question');
 410          }
 411  
 412          if (isset($form->defaultmark)) {
 413              $question->defaultmark = $form->defaultmark;
 414          }
 415  
 416          if (isset($form->idnumber)) {
 417              if ((string) $form->idnumber === '') {
 418                  $question->idnumber = null;
 419              } else {
 420                  // While this check already exists in the form validation,
 421                  // this is a backstop preventing unnecessary errors.
 422                  // Only set the idnumber if it has changed and will not cause a unique index violation.
 423                  if (strpos($form->category, ',') !== false) {
 424                      list($category, $categorycontextid) = explode(',', $form->category);
 425                  } else {
 426                      $category = $form->category;
 427                  }
 428                  if (!$DB->record_exists('question',
 429                          ['idnumber' => $form->idnumber, 'category' => $category])) {
 430                      $question->idnumber = $form->idnumber;
 431                  }
 432              }
 433          }
 434  
 435          // If the question is new, create it.
 436          $newquestion = false;
 437          if (empty($question->id)) {
 438              // Set the unique code.
 439              $question->stamp = make_unique_id_code();
 440              $question->createdby = $USER->id;
 441              $question->timecreated = time();
 442              $question->id = $DB->insert_record('question', $question);
 443              $newquestion = true;
 444          }
 445  
 446          // Now, whether we are updating a existing question, or creating a new
 447          // one, we have to do the files processing and update the record.
 448          // Question already exists, update.
 449          $question->modifiedby = $USER->id;
 450          $question->timemodified = time();
 451  
 452          if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
 453              $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
 454                      $context->id, 'question', 'questiontext', (int)$question->id,
 455                      $this->fileoptions, $question->questiontext);
 456          }
 457          if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
 458              $question->generalfeedback = file_save_draft_area_files(
 459                      $form->generalfeedback['itemid'], $context->id,
 460                      'question', 'generalfeedback', (int)$question->id,
 461                      $this->fileoptions, $question->generalfeedback);
 462          }
 463          $DB->update_record('question', $question);
 464  
 465          // Now to save all the answers and type-specific options.
 466          $form->id = $question->id;
 467          $form->qtype = $question->qtype;
 468          $form->category = $question->category;
 469          $form->questiontext = $question->questiontext;
 470          $form->questiontextformat = $question->questiontextformat;
 471          // Current context.
 472          $form->context = $context;
 473  
 474          $result = $this->save_question_options($form);
 475  
 476          if (!empty($result->error)) {
 477              print_error($result->error);
 478          }
 479  
 480          if (!empty($result->notice)) {
 481              notice($result->notice, "question.php?id={$question->id}");
 482          }
 483  
 484          if (!empty($result->noticeyesno)) {
 485              throw new coding_exception(
 486                      '$result->noticeyesno no longer supported in save_question.');
 487          }
 488  
 489          // Give the question a unique version stamp determined by question_hash().
 490          $DB->set_field('question', 'version', question_hash($question),
 491                  array('id' => $question->id));
 492  
 493          if ($newquestion) {
 494              // Log the creation of this question.
 495              $event = \core\event\question_created::create_from_question_instance($question, $context);
 496              $event->trigger();
 497          } else {
 498              // Log the update of this question.
 499              $event = \core\event\question_updated::create_from_question_instance($question, $context);
 500              $event->trigger();
 501          }
 502  
 503          $transaction->allow_commit();
 504  
 505          return $question;
 506      }
 507  
 508      /**
 509       * Saves question-type specific options
 510       *
 511       * This is called by {@link save_question()} to save the question-type specific data
 512       * @return object $result->error or $result->notice
 513       * @param object $question  This holds the information from the editing form,
 514       *      it is not a standard question object.
 515       */
 516      public function save_question_options($question) {
 517          global $DB;
 518          $extraquestionfields = $this->extra_question_fields();
 519  
 520          if (is_array($extraquestionfields)) {
 521              $question_extension_table = array_shift($extraquestionfields);
 522  
 523              $function = 'update_record';
 524              $questionidcolname = $this->questionid_column_name();
 525              $options = $DB->get_record($question_extension_table,
 526                      array($questionidcolname => $question->id));
 527              if (!$options) {
 528                  $function = 'insert_record';
 529                  $options = new stdClass();
 530                  $options->$questionidcolname = $question->id;
 531              }
 532              foreach ($extraquestionfields as $field) {
 533                  if (property_exists($question, $field)) {
 534                      $options->$field = $question->$field;
 535                  }
 536              }
 537  
 538              $DB->{$function}($question_extension_table, $options);
 539          }
 540      }
 541  
 542      /**
 543       * Save the answers, with any extra data.
 544       *
 545       * Questions that use answers will call it from {@link save_question_options()}.
 546       * @param object $question  This holds the information from the editing form,
 547       *      it is not a standard question object.
 548       * @return object $result->error or $result->notice
 549       */
 550      public function save_question_answers($question) {
 551          global $DB;
 552  
 553          $context = $question->context;
 554          $oldanswers = $DB->get_records('question_answers',
 555                  array('question' => $question->id), 'id ASC');
 556  
 557          // We need separate arrays for answers and extra answer data, so no JOINS there.
 558          $extraanswerfields = $this->extra_answer_fields();
 559          $isextraanswerfields = is_array($extraanswerfields);
 560          $extraanswertable = '';
 561          $oldanswerextras = array();
 562          if ($isextraanswerfields) {
 563              $extraanswertable = array_shift($extraanswerfields);
 564              if (!empty($oldanswers)) {
 565                  $oldanswerextras = $DB->get_records_sql("SELECT * FROM {{$extraanswertable}} WHERE " .
 566                      'answerid IN (SELECT id FROM {question_answers} WHERE question = ' . $question->id . ')' );
 567              }
 568          }
 569  
 570          // Insert all the new answers.
 571          foreach ($question->answer as $key => $answerdata) {
 572              // Check for, and ignore, completely blank answer from the form.
 573              if ($this->is_answer_empty($question, $key)) {
 574                  continue;
 575              }
 576  
 577              // Update an existing answer if possible.
 578              $answer = array_shift($oldanswers);
 579              if (!$answer) {
 580                  $answer = new stdClass();
 581                  $answer->question = $question->id;
 582                  $answer->answer = '';
 583                  $answer->feedback = '';
 584                  $answer->id = $DB->insert_record('question_answers', $answer);
 585              }
 586  
 587              $answer = $this->fill_answer_fields($answer, $question, $key, $context);
 588              $DB->update_record('question_answers', $answer);
 589  
 590              if ($isextraanswerfields) {
 591                  // Check, if this answer contains some extra field data.
 592                  if ($this->is_extra_answer_fields_empty($question, $key)) {
 593                      continue;
 594                  }
 595  
 596                  $answerextra = array_shift($oldanswerextras);
 597                  if (!$answerextra) {
 598                      $answerextra = new stdClass();
 599                      $answerextra->answerid = $answer->id;
 600                      // Avoid looking for correct default for any possible DB field type
 601                      // by setting real values.
 602                      $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
 603                      $answerextra->id = $DB->insert_record($extraanswertable, $answerextra);
 604                  } else {
 605                      // Update answerid, as record may be reused from another answer.
 606                      $answerextra->answerid = $answer->id;
 607                      $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
 608                      $DB->update_record($extraanswertable, $answerextra);
 609                  }
 610              }
 611          }
 612  
 613          if ($isextraanswerfields) {
 614              // Delete any left over extra answer fields records.
 615              $oldanswerextraids = array();
 616              foreach ($oldanswerextras as $oldextra) {
 617                  $oldanswerextraids[] = $oldextra->id;
 618              }
 619              $DB->delete_records_list($extraanswertable, 'id', $oldanswerextraids);
 620          }
 621  
 622          // Delete any left over old answer records.
 623          $fs = get_file_storage();
 624          foreach ($oldanswers as $oldanswer) {
 625              $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
 626              $DB->delete_records('question_answers', array('id' => $oldanswer->id));
 627          }
 628      }
 629  
 630      /**
 631       * Returns true is answer with the $key is empty in the question data and should not be saved in DB.
 632       *
 633       * The questions using question_answers table may want to overload this. Default code will work
 634       * for shortanswer and similar question types.
 635       * @param object $questiondata This holds the information from the question editing form or import.
 636       * @param int $key A key of the answer in question.
 637       * @return bool True if answer shouldn't be saved in DB.
 638       */
 639      protected function is_answer_empty($questiondata, $key) {
 640          return trim($questiondata->answer[$key]) == '' && $questiondata->fraction[$key] == 0 &&
 641                      html_is_blank($questiondata->feedback[$key]['text']);
 642      }
 643  
 644      /**
 645       * Return $answer, filling necessary fields for the question_answers table.
 646       *
 647       * The questions using question_answers table may want to overload this. Default code will work
 648       * for shortanswer and similar question types.
 649       * @param stdClass $answer Object to save data.
 650       * @param object $questiondata This holds the information from the question editing form or import.
 651       * @param int $key A key of the answer in question.
 652       * @param object $context needed for working with files.
 653       * @return $answer answer with filled data.
 654       */
 655      protected function fill_answer_fields($answer, $questiondata, $key, $context) {
 656          $answer->answer   = $questiondata->answer[$key];
 657          $answer->fraction = $questiondata->fraction[$key];
 658          $answer->feedback = $this->import_or_save_files($questiondata->feedback[$key],
 659                  $context, 'question', 'answerfeedback', $answer->id);
 660          $answer->feedbackformat = $questiondata->feedback[$key]['format'];
 661          return $answer;
 662      }
 663  
 664      /**
 665       * Returns true if extra answer fields for answer with the $key is empty
 666       * in the question data and should not be saved in DB.
 667       *
 668       * Questions where extra answer fields are optional will want to overload this.
 669       * @param object $questiondata This holds the information from the question editing form or import.
 670       * @param int $key A key of the answer in question.
 671       * @return bool True if extra answer data shouldn't be saved in DB.
 672       */
 673      protected function is_extra_answer_fields_empty($questiondata, $key) {
 674          // No extra answer data in base class.
 675          return true;
 676      }
 677  
 678      /**
 679       * Return $answerextra, filling necessary fields for the extra answer fields table.
 680       *
 681       * The questions may want to overload it to save files or do other data processing.
 682       * @param stdClass $answerextra Object to save data.
 683       * @param object $questiondata This holds the information from the question editing form or import.
 684       * @param int $key A key of the answer in question.
 685       * @param object $context needed for working with files.
 686       * @param array $extraanswerfields extra answer fields (without table name).
 687       * @return $answer answerextra with filled data.
 688       */
 689      protected function fill_extra_answer_fields($answerextra, $questiondata, $key, $context, $extraanswerfields) {
 690          foreach ($extraanswerfields as $field) {
 691              // The $questiondata->$field[$key] won't work in PHP, break it down to two strings of code.
 692              $fieldarray = $questiondata->$field;
 693              $answerextra->$field = $fieldarray[$key];
 694          }
 695          return $answerextra;
 696      }
 697  
 698      public function save_hints($formdata, $withparts = false) {
 699          global $DB;
 700          $context = $formdata->context;
 701  
 702          $oldhints = $DB->get_records('question_hints',
 703                  array('questionid' => $formdata->id), 'id ASC');
 704  
 705  
 706          $numhints = $this->count_hints_on_form($formdata, $withparts);
 707  
 708          for ($i = 0; $i < $numhints; $i += 1) {
 709              if (html_is_blank($formdata->hint[$i]['text'])) {
 710                  $formdata->hint[$i]['text'] = '';
 711              }
 712  
 713              if ($withparts) {
 714                  $clearwrong = !empty($formdata->hintclearwrong[$i]);
 715                  $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
 716              }
 717  
 718              if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) {
 719                  continue;
 720              }
 721  
 722              // Update an existing hint if possible.
 723              $hint = array_shift($oldhints);
 724              if (!$hint) {
 725                  $hint = new stdClass();
 726                  $hint->questionid = $formdata->id;
 727                  $hint->hint = '';
 728                  $hint->id = $DB->insert_record('question_hints', $hint);
 729              }
 730  
 731              $hint->hint = $this->import_or_save_files($formdata->hint[$i],
 732                      $context, 'question', 'hint', $hint->id);
 733              $hint->hintformat = $formdata->hint[$i]['format'];
 734              if ($withparts) {
 735                  $hint->clearwrong = $clearwrong;
 736                  $hint->shownumcorrect = $shownumcorrect;
 737              }
 738              $hint->options = $this->save_hint_options($formdata, $i, $withparts);
 739              $DB->update_record('question_hints', $hint);
 740          }
 741  
 742          // Delete any remaining old hints.
 743          $fs = get_file_storage();
 744          foreach ($oldhints as $oldhint) {
 745              $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
 746              $DB->delete_records('question_hints', array('id' => $oldhint->id));
 747          }
 748      }
 749  
 750      /**
 751       * Count number of hints on the form.
 752       * Overload if you use custom hint controls.
 753       * @param object $formdata the data from the form.
 754       * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
 755       * @return int count of hints on the form.
 756       */
 757      protected function count_hints_on_form($formdata, $withparts) {
 758          if (!empty($formdata->hint)) {
 759              $numhints = max(array_keys($formdata->hint)) + 1;
 760          } else {
 761              $numhints = 0;
 762          }
 763  
 764          if ($withparts) {
 765              if (!empty($formdata->hintclearwrong)) {
 766                  $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
 767              } else {
 768                  $numclears = 0;
 769              }
 770              if (!empty($formdata->hintshownumcorrect)) {
 771                  $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
 772              } else {
 773                  $numshows = 0;
 774              }
 775              $numhints = max($numhints, $numclears, $numshows);
 776          }
 777          return $numhints;
 778      }
 779  
 780      /**
 781       * Determine if the hint with specified number is not empty and should be saved.
 782       * Overload if you use custom hint controls.
 783       * @param object $formdata the data from the form.
 784       * @param int $number number of hint under question.
 785       * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
 786       * @return bool is this particular hint data empty.
 787       */
 788      protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
 789          if ($withparts) {
 790              return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) &&
 791                      empty($formdata->hintshownumcorrect[$number]);
 792          } else {
 793              return  empty($formdata->hint[$number]['text']);
 794          }
 795      }
 796  
 797      /**
 798       * Save additional question type data into the hint optional field.
 799       * Overload if you use custom hint information.
 800       * @param object $formdata the data from the form.
 801       * @param int $number number of hint to get options from.
 802       * @param bool $withparts whether question have parts.
 803       * @return string value to save into the options field of question_hints table.
 804       */
 805      protected function save_hint_options($formdata, $number, $withparts) {
 806          return null;    // By default, options field is unused.
 807      }
 808  
 809      /**
 810       * Can be used to {@link save_question_options()} to transfer the combined
 811       * feedback fields from $formdata to $options.
 812       * @param object $options the $question->options object being built.
 813       * @param object $formdata the data from the form.
 814       * @param object $context the context the quetsion is being saved into.
 815       * @param bool $withparts whether $options->shownumcorrect should be set.
 816       */
 817      protected function save_combined_feedback_helper($options, $formdata,
 818              $context, $withparts = false) {
 819          $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
 820                  $context, 'question', 'correctfeedback', $formdata->id);
 821          $options->correctfeedbackformat = $formdata->correctfeedback['format'];
 822  
 823          $options->partiallycorrectfeedback = $this->import_or_save_files(
 824                  $formdata->partiallycorrectfeedback,
 825                  $context, 'question', 'partiallycorrectfeedback', $formdata->id);
 826          $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
 827  
 828          $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
 829                  $context, 'question', 'incorrectfeedback', $formdata->id);
 830          $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
 831  
 832          if ($withparts) {
 833              $options->shownumcorrect = !empty($formdata->shownumcorrect);
 834          }
 835  
 836          return $options;
 837      }
 838  
 839      /**
 840       * Loads the question type specific options for the question.
 841       *
 842       * This function loads any question type specific options for the
 843       * question from the database into the question object. This information
 844       * is placed in the $question->options field. A question type is
 845       * free, however, to decide on a internal structure of the options field.
 846       * @return bool            Indicates success or failure.
 847       * @param object $question The question object for the question. This object
 848       *                         should be updated to include the question type
 849       *                         specific information (it is passed by reference).
 850       */
 851      public function get_question_options($question) {
 852          global $CFG, $DB, $OUTPUT;
 853  
 854          if (!isset($question->options)) {
 855              $question->options = new stdClass();
 856          }
 857  
 858          $extraquestionfields = $this->extra_question_fields();
 859          if (is_array($extraquestionfields)) {
 860              $question_extension_table = array_shift($extraquestionfields);
 861              $extra_data = $DB->get_record($question_extension_table,
 862                      array($this->questionid_column_name() => $question->id),
 863                      implode(', ', $extraquestionfields));
 864              if ($extra_data) {
 865                  foreach ($extraquestionfields as $field) {
 866                      $question->options->$field = $extra_data->$field;
 867                  }
 868              } else {
 869                  echo $OUTPUT->notification('Failed to load question options from the table ' .
 870                          $question_extension_table . ' for questionid ' . $question->id);
 871                  return false;
 872              }
 873          }
 874  
 875          $extraanswerfields = $this->extra_answer_fields();
 876          if (is_array($extraanswerfields)) {
 877              $answerextensiontable = array_shift($extraanswerfields);
 878              // Use LEFT JOIN in case not every answer has extra data.
 879              $question->options->answers = $DB->get_records_sql("
 880                      SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . '
 881                      FROM {question_answers} qa ' . "
 882                      LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid
 883                      WHERE qa.question = ?
 884                      ORDER BY qa.id", array($question->id));
 885              if (!$question->options->answers) {
 886                  echo $OUTPUT->notification('Failed to load question answers from the table ' .
 887                          $answerextensiontable . 'for questionid ' . $question->id);
 888                  return false;
 889              }
 890          } else {
 891              // Don't check for success or failure because some question types do
 892              // not use the answers table.
 893              $question->options->answers = $DB->get_records('question_answers',
 894                      array('question' => $question->id), 'id ASC');
 895          }
 896  
 897          $question->hints = $DB->get_records('question_hints',
 898                  array('questionid' => $question->id), 'id ASC');
 899  
 900          return true;
 901      }
 902  
 903      /**
 904       * Create an appropriate question_definition for the question of this type
 905       * using data loaded from the database.
 906       * @param object $questiondata the question data loaded from the database.
 907       * @return question_definition the corresponding question_definition.
 908       */
 909      public function make_question($questiondata) {
 910          $question = $this->make_question_instance($questiondata);
 911          $this->initialise_question_instance($question, $questiondata);
 912          return $question;
 913      }
 914  
 915      /**
 916       * Create an appropriate question_definition for the question of this type
 917       * using data loaded from the database.
 918       * @param object $questiondata the question data loaded from the database.
 919       * @return question_definition an instance of the appropriate question_definition subclass.
 920       *      Still needs to be initialised.
 921       */
 922      protected function make_question_instance($questiondata) {
 923          question_bank::load_question_definition_classes($this->name());
 924          $class = 'qtype_' . $this->name() . '_question';
 925          return new $class();
 926      }
 927  
 928      /**
 929       * Initialise the common question_definition fields.
 930       * @param question_definition $question the question_definition we are creating.
 931       * @param object $questiondata the question data loaded from the database.
 932       */
 933      protected function initialise_question_instance(question_definition $question, $questiondata) {
 934          $question->id = $questiondata->id;
 935          $question->category = $questiondata->category;
 936          $question->contextid = $questiondata->contextid;
 937          $question->parent = $questiondata->parent;
 938          $question->qtype = $this;
 939          $question->name = $questiondata->name;
 940          $question->questiontext = $questiondata->questiontext;
 941          $question->questiontextformat = $questiondata->questiontextformat;
 942          $question->generalfeedback = $questiondata->generalfeedback;
 943          $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
 944          $question->defaultmark = $questiondata->defaultmark + 0;
 945          $question->length = $questiondata->length;
 946          $question->penalty = $questiondata->penalty;
 947          $question->stamp = $questiondata->stamp;
 948          $question->version = $questiondata->version;
 949          $question->hidden = $questiondata->hidden;
 950          $question->idnumber = $questiondata->idnumber;
 951          $question->timecreated = $questiondata->timecreated;
 952          $question->timemodified = $questiondata->timemodified;
 953          $question->createdby = $questiondata->createdby;
 954          $question->modifiedby = $questiondata->modifiedby;
 955  
 956          // Fill extra question fields values.
 957          $extraquestionfields = $this->extra_question_fields();
 958          if (is_array($extraquestionfields)) {
 959              // Omit table name.
 960              array_shift($extraquestionfields);
 961              foreach ($extraquestionfields as $field) {
 962                  $question->$field = $questiondata->options->$field;
 963              }
 964          }
 965  
 966          $this->initialise_question_hints($question, $questiondata);
 967      }
 968  
 969      /**
 970       * Initialise question_definition::hints field.
 971       * @param question_definition $question the question_definition we are creating.
 972       * @param object $questiondata the question data loaded from the database.
 973       */
 974      protected function initialise_question_hints(question_definition $question, $questiondata) {
 975          if (empty($questiondata->hints)) {
 976              return;
 977          }
 978          foreach ($questiondata->hints as $hint) {
 979              $question->hints[] = $this->make_hint($hint);
 980          }
 981      }
 982  
 983      /**
 984       * Create a question_hint, or an appropriate subclass for this question,
 985       * from a row loaded from the database.
 986       * @param object $hint the DB row from the question hints table.
 987       * @return question_hint
 988       */
 989      protected function make_hint($hint) {
 990          return question_hint::load_from_record($hint);
 991      }
 992  
 993      /**
 994       * Initialise the combined feedback fields.
 995       * @param question_definition $question the question_definition we are creating.
 996       * @param object $questiondata the question data loaded from the database.
 997       * @param bool $withparts whether to set the shownumcorrect field.
 998       */
 999      protected function initialise_combined_feedback(question_definition $question,
1000              $questiondata, $withparts = false) {
1001          $question->correctfeedback = $questiondata->options->correctfeedback;
1002          $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
1003          $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
1004          $question->partiallycorrectfeedbackformat =
1005                  $questiondata->options->partiallycorrectfeedbackformat;
1006          $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
1007          $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
1008          if ($withparts) {
1009              $question->shownumcorrect = $questiondata->options->shownumcorrect;
1010          }
1011      }
1012  
1013      /**
1014       * Initialise question_definition::answers field.
1015       * @param question_definition $question the question_definition we are creating.
1016       * @param object $questiondata the question data loaded from the database.
1017       * @param bool $forceplaintextanswers most qtypes assume that answers are
1018       *      FORMAT_PLAIN, and dont use the answerformat DB column (it contains
1019       *      the default 0 = FORMAT_MOODLE). Therefore, by default this method
1020       *      ingores answerformat. Pass false here to use answerformat. For example
1021       *      multichoice does this.
1022       */
1023      protected function initialise_question_answers(question_definition $question,
1024              $questiondata, $forceplaintextanswers = true) {
1025          $question->answers = array();
1026          if (empty($questiondata->options->answers)) {
1027              return;
1028          }
1029          foreach ($questiondata->options->answers as $a) {
1030              $question->answers[$a->id] = $this->make_answer($a);
1031              if (!$forceplaintextanswers) {
1032                  $question->answers[$a->id]->answerformat = $a->answerformat;
1033              }
1034          }
1035      }
1036  
1037      /**
1038       * Create a question_answer, or an appropriate subclass for this question,
1039       * from a row loaded from the database.
1040       * @param object $answer the DB row from the question_answers table plus extra answer fields.
1041       * @return question_answer
1042       */
1043      protected function make_answer($answer) {
1044          return new question_answer($answer->id, $answer->answer,
1045                      $answer->fraction, $answer->feedback, $answer->feedbackformat);
1046      }
1047  
1048      /**
1049       * Deletes the question-type specific data when a question is deleted.
1050       * @param int $question the question being deleted.
1051       * @param int $contextid the context this quesiotn belongs to.
1052       */
1053      public function delete_question($questionid, $contextid) {
1054          global $DB;
1055  
1056          $this->delete_files($questionid, $contextid);
1057  
1058          $extraquestionfields = $this->extra_question_fields();
1059          if (is_array($extraquestionfields)) {
1060              $question_extension_table = array_shift($extraquestionfields);
1061              $DB->delete_records($question_extension_table,
1062                      array($this->questionid_column_name() => $questionid));
1063          }
1064  
1065          $extraanswerfields = $this->extra_answer_fields();
1066          if (is_array($extraanswerfields)) {
1067              $answer_extension_table = array_shift($extraanswerfields);
1068              $DB->delete_records_select($answer_extension_table,
1069                      'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
1070                      array($questionid));
1071          }
1072  
1073          $DB->delete_records('question_answers', array('question' => $questionid));
1074  
1075          $DB->delete_records('question_hints', array('questionid' => $questionid));
1076      }
1077  
1078      /**
1079       * Returns the number of question numbers which are used by the question
1080       *
1081       * This function returns the number of question numbers to be assigned
1082       * to the question. Most question types will have length one; they will be
1083       * assigned one number. The 'description' type, however does not use up a
1084       * number and so has a length of zero. Other question types may wish to
1085       * handle a bundle of questions and hence return a number greater than one.
1086       * @return int         The number of question numbers which should be
1087       *                         assigned to the question.
1088       * @param object $question The question whose length is to be determined.
1089       *                         Question type specific information is included.
1090       */
1091      public function actual_number_of_questions($question) {
1092          // By default, each question is given one number.
1093          return 1;
1094      }
1095  
1096      /**
1097       * Calculate the score a monkey would get on a question by clicking randomly.
1098       *
1099       * Some question types have significant non-zero average expected score
1100       * of the response is just selected randomly. For example 50% for a
1101       * true-false question. It is useful to know what this is. For example
1102       * it gets shown in the quiz statistics report.
1103       *
1104       * For almost any open-ended question type (E.g. shortanswer or numerical)
1105       * this should be 0.
1106       *
1107       * For selective response question types (e.g. multiple choice), you can probably compute this.
1108       *
1109       * For particularly complicated question types the may be impossible or very
1110       * difficult to compute. In this case return null. (Or, if the expected score
1111       * is very tiny even though the exact value is unknown, it may appropriate
1112       * to return 0.)
1113       *
1114       * @param stdClass $questiondata data defining a question, as returned by
1115       *      question_bank::load_question_data().
1116       * @return number|null either a fraction estimating what the student would
1117       *      score by guessing, or null, if it is not possible to estimate.
1118       */
1119      public function get_random_guess_score($questiondata) {
1120          return 0;
1121      }
1122  
1123      /**
1124       * Whether or not to break down question stats and response analysis, for a question defined by $questiondata.
1125       *
1126       * @param object $questiondata The full question definition data.
1127       * @return bool
1128       */
1129      public function break_down_stats_and_response_analysis_by_variant($questiondata) {
1130          return true;
1131      }
1132  
1133      /**
1134       * This method should return all the possible types of response that are
1135       * recognised for this question.
1136       *
1137       * The question is modelled as comprising one or more subparts. For each
1138       * subpart, there are one or more classes that that students response
1139       * might fall into, each of those classes earning a certain score.
1140       *
1141       * For example, in a shortanswer question, there is only one subpart, the
1142       * text entry field. The response the student gave will be classified according
1143       * to which of the possible $question->options->answers it matches.
1144       *
1145       * For the matching question type, there will be one subpart for each
1146       * question stem, and for each stem, each of the possible choices is a class
1147       * of student's response.
1148       *
1149       * A response is an object with two fields, ->responseclass is a string
1150       * presentation of that response, and ->fraction, the credit for a response
1151       * in that class.
1152       *
1153       * Array keys have no specific meaning, but must be unique, and must be
1154       * the same if this function is called repeatedly.
1155       *
1156       * @param object $question the question definition data.
1157       * @return array keys are subquestionid, values are arrays of possible
1158       *      responses to that subquestion.
1159       */
1160      public function get_possible_responses($questiondata) {
1161          return array();
1162      }
1163  
1164      /**
1165       * Utility method used by {@link qtype_renderer::head_code()}. It looks
1166       * for any of the files script.js or script.php that exist in the plugin
1167       * folder and ensures they get included.
1168       */
1169      public function find_standard_scripts() {
1170          global $PAGE;
1171  
1172          $plugindir = $this->plugin_dir();
1173          $plugindirrel = 'question/type/' . $this->name();
1174  
1175          if (file_exists($plugindir . '/script.js')) {
1176              $PAGE->requires->js('/' . $plugindirrel . '/script.js');
1177          }
1178          if (file_exists($plugindir . '/script.php')) {
1179              $PAGE->requires->js('/' . $plugindirrel . '/script.php');
1180          }
1181      }
1182  
1183      /**
1184       * Returns true if the editing wizard is finished, false otherwise.
1185       *
1186       * The default implementation returns true, which is suitable for all question-
1187       * types that only use one editing form. This function is used in
1188       * question.php to decide whether we can regrade any states of the edited
1189       * question and redirect to edit.php.
1190       *
1191       * The dataset dependent question-type, which is extended by the calculated
1192       * question-type, overwrites this method because it uses multiple pages (i.e.
1193       * a wizard) to set up the question and associated datasets.
1194       *
1195       * @param object $form  The data submitted by the previous page.
1196       *
1197       * @return bool      Whether the wizard's last page was submitted or not.
1198       */
1199      public function finished_edit_wizard($form) {
1200          // In the default case there is only one edit page.
1201          return true;
1202      }
1203  
1204      // IMPORT/EXPORT FUNCTIONS --------------------------------- .
1205  
1206      /*
1207       * Imports question from the Moodle XML format
1208       *
1209       * Imports question using information from extra_question_fields function
1210       * If some of you fields contains id's you'll need to reimplement this
1211       */
1212      public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
1213          $question_type = $data['@']['type'];
1214          if ($question_type != $this->name()) {
1215              return false;
1216          }
1217  
1218          $extraquestionfields = $this->extra_question_fields();
1219          if (!is_array($extraquestionfields)) {
1220              return false;
1221          }
1222  
1223          // Omit table name.
1224          array_shift($extraquestionfields);
1225          $qo = $format->import_headers($data);
1226          $qo->qtype = $question_type;
1227  
1228          foreach ($extraquestionfields as $field) {
1229              $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
1230          }
1231  
1232          // Run through the answers.
1233          $answers = $data['#']['answer'];
1234          $a_count = 0;
1235          $extraanswersfields = $this->extra_answer_fields();
1236          if (is_array($extraanswersfields)) {
1237              array_shift($extraanswersfields);
1238          }
1239          foreach ($answers as $answer) {
1240              $ans = $format->import_answer($answer);
1241              if (!$this->has_html_answers()) {
1242                  $qo->answer[$a_count] = $ans->answer['text'];
1243              } else {
1244                  $qo->answer[$a_count] = $ans->answer;
1245              }
1246              $qo->fraction[$a_count] = $ans->fraction;
1247              $qo->feedback[$a_count] = $ans->feedback;
1248              if (is_array($extraanswersfields)) {
1249                  foreach ($extraanswersfields as $field) {
1250                      $qo->{$field}[$a_count] =
1251                          $format->getpath($answer, array('#', $field, 0, '#'), '');
1252                  }
1253              }
1254              ++$a_count;
1255          }
1256          return $qo;
1257      }
1258  
1259      /*
1260       * Export question to the Moodle XML format
1261       *
1262       * Export question using information from extra_question_fields function
1263       * If some of you fields contains id's you'll need to reimplement this
1264       */
1265      public function export_to_xml($question, qformat_xml $format, $extra=null) {
1266          $extraquestionfields = $this->extra_question_fields();
1267          if (!is_array($extraquestionfields)) {
1268              return false;
1269          }
1270  
1271          // Omit table name.
1272          array_shift($extraquestionfields);
1273          $expout='';
1274          foreach ($extraquestionfields as $field) {
1275              $exportedvalue = $format->xml_escape($question->options->$field);
1276              $expout .= "    <{$field}>{$exportedvalue}</{$field}>\n";
1277          }
1278  
1279          $extraanswersfields = $this->extra_answer_fields();
1280          if (is_array($extraanswersfields)) {
1281              array_shift($extraanswersfields);
1282          }
1283          foreach ($question->options->answers as $answer) {
1284              $extra = '';
1285              if (is_array($extraanswersfields)) {
1286                  foreach ($extraanswersfields as $field) {
1287                      $exportedvalue = $format->xml_escape($answer->$field);
1288                      $extra .= "      <{$field}>{$exportedvalue}</{$field}>\n";
1289                  }
1290              }
1291  
1292              $expout .= $format->write_answer($answer, $extra);
1293          }
1294          return $expout;
1295      }
1296  
1297      /**
1298       * Abstract function implemented by each question type. It runs all the code
1299       * required to set up and save a question of any type for testing purposes.
1300       * Alternate DB table prefix may be used to facilitate data deletion.
1301       */
1302      public function generate_test($name, $courseid=null) {
1303          $form = new stdClass();
1304          $form->name = $name;
1305          $form->questiontextformat = 1;
1306          $form->questiontext = 'test question, generated by script';
1307          $form->defaultmark = 1;
1308          $form->penalty = 0.3333333;
1309          $form->generalfeedback = "Well done";
1310  
1311          $context = context_course::instance($courseid);
1312          $newcategory = question_make_default_categories(array($context));
1313          $form->category = $newcategory->id . ',1';
1314  
1315          $question = new stdClass();
1316          $question->courseid = $courseid;
1317          $question->qtype = $this->qtype;
1318          return array($form, $question);
1319      }
1320  
1321      /**
1322       * Get question context by category id
1323       * @param int $category
1324       * @return object $context
1325       */
1326      protected function get_context_by_category_id($category) {
1327          global $DB;
1328          $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
1329          $context = context::instance_by_id($contextid, IGNORE_MISSING);
1330          return $context;
1331      }
1332  
1333      /**
1334       * Save the file belonging to one text field.
1335       *
1336       * @param array $field the data from the form (or from import). This will
1337       *      normally have come from the formslib editor element, so it will be an
1338       *      array with keys 'text', 'format' and 'itemid'. However, when we are
1339       *      importing, it will be an array with keys 'text', 'format' and 'files'
1340       * @param object $context the context the question is in.
1341       * @param string $component indentifies the file area question.
1342       * @param string $filearea indentifies the file area questiontext,
1343       *      generalfeedback, answerfeedback, etc.
1344       * @param int $itemid identifies the file area.
1345       *
1346       * @return string the text for this field, after files have been processed.
1347       */
1348      protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1349          if (!empty($field['itemid'])) {
1350              // This is the normal case. We are safing the questions editing form.
1351              return file_save_draft_area_files($field['itemid'], $context->id, $component,
1352                      $filearea, $itemid, $this->fileoptions, trim($field['text']));
1353  
1354          } else if (!empty($field['files'])) {
1355              // This is the case when we are doing an import.
1356              foreach ($field['files'] as $file) {
1357                  $this->import_file($context, $component,  $filearea, $itemid, $file);
1358              }
1359          }
1360          return trim($field['text']);
1361      }
1362  
1363      /**
1364       * Move all the files belonging to this question from one context to another.
1365       * @param int $questionid the question being moved.
1366       * @param int $oldcontextid the context it is moving from.
1367       * @param int $newcontextid the context it is moving to.
1368       */
1369      public function move_files($questionid, $oldcontextid, $newcontextid) {
1370          $fs = get_file_storage();
1371          $fs->move_area_files_to_new_context($oldcontextid,
1372                  $newcontextid, 'question', 'questiontext', $questionid);
1373          $fs->move_area_files_to_new_context($oldcontextid,
1374                  $newcontextid, 'question', 'generalfeedback', $questionid);
1375      }
1376  
1377      /**
1378       * Move all the files belonging to this question's answers when the question
1379       * is moved from one context to another.
1380       * @param int $questionid the question being moved.
1381       * @param int $oldcontextid the context it is moving from.
1382       * @param int $newcontextid the context it is moving to.
1383       * @param bool $answerstoo whether there is an 'answer' question area,
1384       *      as well as an 'answerfeedback' one. Default false.
1385       */
1386      protected function move_files_in_answers($questionid, $oldcontextid,
1387              $newcontextid, $answerstoo = false) {
1388          global $DB;
1389          $fs = get_file_storage();
1390  
1391          $answerids = $DB->get_records_menu('question_answers',
1392                  array('question' => $questionid), 'id', 'id,1');
1393          foreach ($answerids as $answerid => $notused) {
1394              if ($answerstoo) {
1395                  $fs->move_area_files_to_new_context($oldcontextid,
1396                          $newcontextid, 'question', 'answer', $answerid);
1397              }
1398              $fs->move_area_files_to_new_context($oldcontextid,
1399                      $newcontextid, 'question', 'answerfeedback', $answerid);
1400          }
1401      }
1402  
1403      /**
1404       * Move all the files belonging to this question's hints when the question
1405       * is moved from one context to another.
1406       * @param int $questionid the question being moved.
1407       * @param int $oldcontextid the context it is moving from.
1408       * @param int $newcontextid the context it is moving to.
1409       * @param bool $answerstoo whether there is an 'answer' question area,
1410       *      as well as an 'answerfeedback' one. Default false.
1411       */
1412      protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1413          global $DB;
1414          $fs = get_file_storage();
1415  
1416          $hintids = $DB->get_records_menu('question_hints',
1417                  array('questionid' => $questionid), 'id', 'id,1');
1418          foreach ($hintids as $hintid => $notused) {
1419              $fs->move_area_files_to_new_context($oldcontextid,
1420                      $newcontextid, 'question', 'hint', $hintid);
1421          }
1422      }
1423  
1424      /**
1425       * Move all the files belonging to this question's answers when the question
1426       * is moved from one context to another.
1427       * @param int $questionid the question being moved.
1428       * @param int $oldcontextid the context it is moving from.
1429       * @param int $newcontextid the context it is moving to.
1430       * @param bool $answerstoo whether there is an 'answer' question area,
1431       *      as well as an 'answerfeedback' one. Default false.
1432       */
1433      protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1434              $newcontextid) {
1435          global $DB;
1436          $fs = get_file_storage();
1437  
1438          $fs->move_area_files_to_new_context($oldcontextid,
1439                  $newcontextid, 'question', 'correctfeedback', $questionid);
1440          $fs->move_area_files_to_new_context($oldcontextid,
1441                  $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1442          $fs->move_area_files_to_new_context($oldcontextid,
1443                  $newcontextid, 'question', 'incorrectfeedback', $questionid);
1444      }
1445  
1446      /**
1447       * Delete all the files belonging to this question.
1448       * @param int $questionid the question being deleted.
1449       * @param int $contextid the context the question is in.
1450       */
1451      protected function delete_files($questionid, $contextid) {
1452          $fs = get_file_storage();
1453          $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1454          $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1455      }
1456  
1457      /**
1458       * Delete all the files belonging to this question's answers.
1459       * @param int $questionid the question being deleted.
1460       * @param int $contextid the context the question is in.
1461       * @param bool $answerstoo whether there is an 'answer' question area,
1462       *      as well as an 'answerfeedback' one. Default false.
1463       */
1464      protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1465          global $DB;
1466          $fs = get_file_storage();
1467  
1468          $answerids = $DB->get_records_menu('question_answers',
1469                  array('question' => $questionid), 'id', 'id,1');
1470          foreach ($answerids as $answerid => $notused) {
1471              if ($answerstoo) {
1472                  $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1473              }
1474              $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1475          }
1476      }
1477  
1478      /**
1479       * Delete all the files belonging to this question's hints.
1480       * @param int $questionid the question being deleted.
1481       * @param int $contextid the context the question is in.
1482       */
1483      protected function delete_files_in_hints($questionid, $contextid) {
1484          global $DB;
1485          $fs = get_file_storage();
1486  
1487          $hintids = $DB->get_records_menu('question_hints',
1488                  array('questionid' => $questionid), 'id', 'id,1');
1489          foreach ($hintids as $hintid => $notused) {
1490              $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1491          }
1492      }
1493  
1494      /**
1495       * Delete all the files belonging to this question's answers.
1496       * @param int $questionid the question being deleted.
1497       * @param int $contextid the context the question is in.
1498       * @param bool $answerstoo whether there is an 'answer' question area,
1499       *      as well as an 'answerfeedback' one. Default false.
1500       */
1501      protected function delete_files_in_combined_feedback($questionid, $contextid) {
1502          global $DB;
1503          $fs = get_file_storage();
1504  
1505          $fs->delete_area_files($contextid,
1506                  'question', 'correctfeedback', $questionid);
1507          $fs->delete_area_files($contextid,
1508                  'question', 'partiallycorrectfeedback', $questionid);
1509          $fs->delete_area_files($contextid,
1510                  'question', 'incorrectfeedback', $questionid);
1511      }
1512  
1513      public function import_file($context, $component, $filearea, $itemid, $file) {
1514          $fs = get_file_storage();
1515          $record = new stdClass();
1516          if (is_object($context)) {
1517              $record->contextid = $context->id;
1518          } else {
1519              $record->contextid = $context;
1520          }
1521          $record->component = $component;
1522          $record->filearea  = $filearea;
1523          $record->itemid    = $itemid;
1524          $record->filename  = $file->name;
1525          $record->filepath  = '/';
1526          return $fs->create_file_from_string($record, $this->decode_file($file));
1527      }
1528  
1529      protected function decode_file($file) {
1530          switch ($file->encoding) {
1531              case 'base64':
1532              default:
1533                  return base64_decode($file->content);
1534          }
1535      }
1536  }
1537  
1538  
1539  /**
1540   * This class is used in the return value from
1541   * {@link question_type::get_possible_responses()}.
1542   *
1543   * @copyright  2010 The Open University
1544   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1545   */
1546  class question_possible_response {
1547      /**
1548       * @var string the classification of this response the student gave to this
1549       * part of the question. Must match one of the responseclasses returned by
1550       * {@link question_type::get_possible_responses()}.
1551       */
1552      public $responseclass;
1553  
1554      /** @var string the (partial) credit awarded for this responses. */
1555      public $fraction;
1556  
1557      /**
1558       * Constructor, just an easy way to set the fields.
1559       * @param string $responseclassid see the field descriptions above.
1560       * @param string $response see the field descriptions above.
1561       * @param number $fraction see the field descriptions above.
1562       */
1563      public function __construct($responseclass, $fraction) {
1564          $this->responseclass = $responseclass;
1565          $this->fraction = $fraction;
1566      }
1567  
1568      public static function no_response() {
1569          return new question_possible_response(get_string('noresponse', 'question'), 0);
1570      }
1571  }