Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * This file defines the class {@link question_definition} and its subclasses.
  19   *
  20   * The type hierarchy is quite complex. Here is a summary:
  21   * - question_definition
  22   *   - question_information_item
  23   *   - question_with_responses implements question_manually_gradable
  24   *     - question_graded_automatically implements question_automatically_gradable
  25   *       - question_graded_automatically_with_countback implements question_automatically_gradable_with_countback
  26   *       - question_graded_by_strategy
  27   *
  28   * Other classes:
  29   * - question_classified_response
  30   * - question_answer
  31   * - question_hint
  32   *   - question_hint_with_parts
  33   * - question_first_matching_answer_grading_strategy implements question_grading_strategy
  34   *
  35   * Other interfaces:
  36   * - question_response_answer_comparer
  37   *
  38   * @package    moodlecore
  39   * @subpackage questiontypes
  40   * @copyright  2009 The Open University
  41   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42   */
  43  
  44  
  45  defined('MOODLE_INTERNAL') || die();
  46  
  47  
  48  /**
  49   * The definition of a question of a particular type.
  50   *
  51   * This class is a close match to the question table in the database.
  52   * Definitions of question of a particular type normally subclass one of the
  53   * more specific classes {@link question_with_responses},
  54   * {@link question_graded_automatically} or {@link question_information_item}.
  55   *
  56   * @copyright  2009 The Open University
  57   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  58   */
  59  abstract class question_definition {
  60      /** @var integer id of the question in the datase, or null if this question
  61       * is not in the database. */
  62      public $id;
  63  
  64      /** @var integer question category id. */
  65      public $category;
  66  
  67      /** @var integer question context id. */
  68      public $contextid;
  69  
  70      /** @var integer parent question id. */
  71      public $parent = 0;
  72  
  73      /** @var question_type the question type this question is. */
  74      public $qtype;
  75  
  76      /** @var string question name. */
  77      public $name;
  78  
  79      /** @var string question text. */
  80      public $questiontext;
  81  
  82      /** @var integer question test format. */
  83      public $questiontextformat;
  84  
  85      /** @var string question general feedback. */
  86      public $generalfeedback;
  87  
  88      /** @var integer question test format. */
  89      public $generalfeedbackformat;
  90  
  91      /** @var number what this quetsion is marked out of, by default. */
  92      public $defaultmark = 1;
  93  
  94      /** @var integer How many question numbers this question consumes. */
  95      public $length = 1;
  96  
  97      /** @var number penalty factor of this question. */
  98      public $penalty = 0;
  99  
 100      /** @var string unique identifier of this question. */
 101      public $stamp;
 102  
 103      /** @var string unique identifier of this version of this question. */
 104      public $version;
 105  
 106      /** @var boolean whethre this question has been deleted/hidden in the question bank. */
 107      public $hidden = 0;
 108  
 109      /** @var string question idnumber. */
 110      public $idnumber;
 111  
 112      /** @var integer timestamp when this question was created. */
 113      public $timecreated;
 114  
 115      /** @var integer timestamp when this question was modified. */
 116      public $timemodified;
 117  
 118      /** @var integer userid of the use who created this question. */
 119      public $createdby;
 120  
 121      /** @var integer userid of the use who modified this question. */
 122      public $modifiedby;
 123  
 124      /** @var array of question_hints. */
 125      public $hints = array();
 126  
 127      /**
 128       * Constructor. Normally to get a question, you call
 129       * {@link question_bank::load_question()}, but questions can be created
 130       * directly, for example in unit test code.
 131       * @return unknown_type
 132       */
 133      public function __construct() {
 134      }
 135  
 136      /**
 137       * @return the name of the question type (for example multichoice) that this
 138       * question is.
 139       */
 140      public function get_type_name() {
 141          return $this->qtype->name();
 142      }
 143  
 144      /**
 145       * Creat the appropriate behaviour for an attempt at this quetsion,
 146       * given the desired (archetypal) behaviour.
 147       *
 148       * This default implementation will suit most normal graded questions.
 149       *
 150       * If your question is of a patricular type, then it may need to do something
 151       * different. For example, if your question can only be graded manually, then
 152       * it should probably return a manualgraded behaviour, irrespective of
 153       * what is asked for.
 154       *
 155       * If your question wants to do somthing especially complicated is some situations,
 156       * then you may wish to return a particular behaviour related to the
 157       * one asked for. For example, you migth want to return a
 158       * qbehaviour_interactive_adapted_for_myqtype.
 159       *
 160       * @param question_attempt $qa the attempt we are creating a behaviour for.
 161       * @param string $preferredbehaviour the requested type of behaviour.
 162       * @return question_behaviour the new behaviour object.
 163       */
 164      public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
 165          return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
 166      }
 167  
 168      /**
 169       * Start a new attempt at this question, storing any information that will
 170       * be needed later in the step.
 171       *
 172       * This is where the question can do any initialisation required on a
 173       * per-attempt basis. For example, this is where the multiple choice
 174       * question type randomly shuffles the choices (if that option is set).
 175       *
 176       * Any information about how the question has been set up for this attempt
 177       * should be stored in the $step, by calling $step->set_qt_var(...).
 178       *
 179       * @param question_attempt_step The first step of the {@link question_attempt}
 180       *      being started. Can be used to store state.
 181       * @param int $varant which variant of this question to start. Will be between
 182       *      1 and {@link get_num_variants()} inclusive.
 183       */
 184      public function start_attempt(question_attempt_step $step, $variant) {
 185      }
 186  
 187      /**
 188       * When an in-progress {@link question_attempt} is re-loaded from the
 189       * database, this method is called so that the question can re-initialise
 190       * its internal state as needed by this attempt.
 191       *
 192       * For example, the multiple choice question type needs to set the order
 193       * of the choices to the order that was set up when start_attempt was called
 194       * originally. All the information required to do this should be in the
 195       * $step object, which is the first step of the question_attempt being loaded.
 196       *
 197       * @param question_attempt_step The first step of the {@link question_attempt}
 198       *      being loaded.
 199       */
 200      public function apply_attempt_state(question_attempt_step $step) {
 201      }
 202  
 203      /**
 204       * Generate a brief, plain-text, summary of this question. This is used by
 205       * various reports. This should show the particular variant of the question
 206       * as presented to students. For example, the calculated quetsion type would
 207       * fill in the particular numbers that were presented to the student.
 208       * This method will return null if such a summary is not possible, or
 209       * inappropriate.
 210       * @return string|null a plain text summary of this question.
 211       */
 212      public function get_question_summary() {
 213          return $this->html_to_text($this->questiontext, $this->questiontextformat);
 214      }
 215  
 216      /**
 217       * @return int the number of vaiants that this question has.
 218       */
 219      public function get_num_variants() {
 220          return 1;
 221      }
 222  
 223      /**
 224       * @return string that can be used to seed the pseudo-random selection of a
 225       *      variant.
 226       */
 227      public function get_variants_selection_seed() {
 228          return $this->stamp;
 229      }
 230  
 231      /**
 232       * Some questions can return a negative mark if the student gets it wrong.
 233       *
 234       * This method returns the lowest mark the question can return, on the
 235       * fraction scale. that is, where the maximum possible mark is 1.0.
 236       *
 237       * @return float minimum fraction this question will ever return.
 238       */
 239      public function get_min_fraction() {
 240          return 0;
 241      }
 242  
 243      /**
 244       * Some questions can return a mark greater than the maximum.
 245       *
 246       * This method returns the lowest highest the question can return, on the
 247       * fraction scale. that is, where the nominal maximum mark is 1.0.
 248       *
 249       * @return float maximum fraction this question will ever return.
 250       */
 251      public function get_max_fraction() {
 252          return 1;
 253      }
 254  
 255      /**
 256       * Given a response, rest the parts that are wrong.
 257       * @param array $response a response
 258       * @return array a cleaned up response with the wrong bits reset.
 259       */
 260      public function clear_wrong_from_response(array $response) {
 261          return array();
 262      }
 263  
 264      /**
 265       * Return the number of subparts of this response that are right.
 266       * @param array $response a response
 267       * @return array with two elements, the number of correct subparts, and
 268       * the total number of subparts.
 269       */
 270      public function get_num_parts_right(array $response) {
 271          return array(null, null);
 272      }
 273  
 274      /**
 275       * @param moodle_page the page we are outputting to.
 276       * @return qtype_renderer the renderer to use for outputting this question.
 277       */
 278      public function get_renderer(moodle_page $page) {
 279          return $page->get_renderer($this->qtype->plugin_name());
 280      }
 281  
 282      /**
 283       * What data may be included in the form submission when a student submits
 284       * this question in its current state?
 285       *
 286       * This information is used in calls to optional_param. The parameter name
 287       * has {@link question_attempt::get_field_prefix()} automatically prepended.
 288       *
 289       * @return array|string variable name => PARAM_... constant, or, as a special case
 290       *      that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
 291       *      meaning take all the raw submitted data belonging to this question.
 292       */
 293      public abstract function get_expected_data();
 294  
 295      /**
 296       * What data would need to be submitted to get this question correct.
 297       * If there is more than one correct answer, this method should just
 298       * return one possibility. If it is not possible to compute a correct
 299       * response, this method should return null.
 300       *
 301       * @return array|null parameter name => value.
 302       */
 303      public abstract function get_correct_response();
 304  
 305  
 306      /**
 307       * Takes an array of values representing a student response represented in a way that is understandable by a human and
 308       * transforms that to the response as the POST values returned from the HTML form that takes the student response during a
 309       * student attempt. Primarily this is used when reading csv values from a file of student responses in order to be able to
 310       * simulate the student interaction with a quiz.
 311       *
 312       * In most cases the array will just be returned as is. Some question types will need to transform the keys of the array,
 313       * as the meaning of the keys in the html form is deliberately obfuscated so that someone looking at the html does not get an
 314       * advantage. The values that represent the response might also be changed in order to more meaningful to a human.
 315       *
 316       * See the examples of question types that have overridden this in core and also see the csv files of simulated student
 317       * responses used in unit tests in :
 318       * - mod/quiz/tests/fixtures/stepsXX.csv
 319       * - mod/quiz/report/responses/tests/fixtures/steps00.csv
 320       * - mod/quiz/report/statistics/tests/fixtures/stepsXX.csv
 321       *
 322       * Also see {@link https://github.com/jamiepratt/moodle-quiz_simulate}, a quiz report plug in for uploading and downloading
 323       * student responses as csv files.
 324       *
 325       * @param array $simulatedresponse an array of data representing a student response
 326       * @return array a response array as would be returned from the html form (but without prefixes)
 327       */
 328      public function prepare_simulated_post_data($simulatedresponse) {
 329          return $simulatedresponse;
 330      }
 331  
 332      /**
 333       * Does the opposite of {@link prepare_simulated_post_data}.
 334       *
 335       * This takes a student response (the POST values returned from the HTML form that takes the student response during a
 336       * student attempt) it then represents it in a way that is understandable by a human.
 337       *
 338       * Primarily this is used when creating a file of csv from real student responses in order later to be able to
 339       * simulate the same student interaction with a quiz later.
 340       *
 341       * @param string[] $realresponse the response array as was returned from the form during a student attempt (without prefixes).
 342       * @return string[] an array of data representing a student response.
 343       */
 344      public function get_student_response_values_for_simulation($realresponse) {
 345          return $realresponse;
 346      }
 347  
 348      /**
 349       * Apply {@link format_text()} to some content with appropriate settings for
 350       * this question.
 351       *
 352       * @param string $text some content that needs to be output.
 353       * @param int $format the FORMAT_... constant.
 354       * @param question_attempt $qa the question attempt.
 355       * @param string $component used for rewriting file area URLs.
 356       * @param string $filearea used for rewriting file area URLs.
 357       * @param bool $clean Whether the HTML needs to be cleaned. Generally,
 358       *      parts of the question do not need to be cleaned, and student input does.
 359       * @return string the text formatted for output by format_text.
 360       */
 361      public function format_text($text, $format, $qa, $component, $filearea, $itemid,
 362              $clean = false) {
 363          $formatoptions = new stdClass();
 364          $formatoptions->noclean = !$clean;
 365          $formatoptions->para = false;
 366          $text = $qa->rewrite_pluginfile_urls($text, $component, $filearea, $itemid);
 367          return format_text($text, $format, $formatoptions);
 368      }
 369  
 370      /**
 371       * Convert some part of the question text to plain text. This might be used,
 372       * for example, by get_response_summary().
 373       * @param string $text The HTML to reduce to plain text.
 374       * @param int $format the FORMAT_... constant.
 375       * @return string the equivalent plain text.
 376       */
 377      public function html_to_text($text, $format) {
 378          return question_utils::to_plain_text($text, $format);
 379      }
 380  
 381      /** @return the result of applying {@link format_text()} to the question text. */
 382      public function format_questiontext($qa) {
 383          return $this->format_text($this->questiontext, $this->questiontextformat,
 384                  $qa, 'question', 'questiontext', $this->id);
 385      }
 386  
 387      /** @return the result of applying {@link format_text()} to the general feedback. */
 388      public function format_generalfeedback($qa) {
 389          return $this->format_text($this->generalfeedback, $this->generalfeedbackformat,
 390                  $qa, 'question', 'generalfeedback', $this->id);
 391      }
 392  
 393      /**
 394       * Take some HTML that should probably already be a single line, like a
 395       * multiple choice choice, or the corresponding feedback, and make it so that
 396       * it is suitable to go in a place where the HTML must be inline, like inside a <p> tag.
 397       * @param string $html to HTML to fix up.
 398       * @return string the fixed HTML.
 399       */
 400      public function make_html_inline($html) {
 401          $html = preg_replace('~\s*<p>\s*~u', '', $html);
 402          $html = preg_replace('~\s*</p>\s*~u', '<br />', $html);
 403          $html = preg_replace('~(<br\s*/?>)+$~u', '', $html);
 404          return trim($html);
 405      }
 406  
 407      /**
 408       * Checks whether the users is allow to be served a particular file.
 409       * @param question_attempt $qa the question attempt being displayed.
 410       * @param question_display_options $options the options that control display of the question.
 411       * @param string $component the name of the component we are serving files for.
 412       * @param string $filearea the name of the file area.
 413       * @param array $args the remaining bits of the file path.
 414       * @param bool $forcedownload whether the user must be forced to download the file.
 415       * @return bool true if the user can access this file.
 416       */
 417      public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
 418          if ($component == 'question' && $filearea == 'questiontext') {
 419              // Question text always visible, but check it is the right question id.
 420              return $args[0] == $this->id;
 421  
 422          } else if ($component == 'question' && $filearea == 'generalfeedback') {
 423              return $options->generalfeedback && $args[0] == $this->id;
 424  
 425          } else {
 426              // Unrecognised component or filearea.
 427              return false;
 428          }
 429      }
 430  }
 431  
 432  
 433  /**
 434   * This class represents a 'question' that actually does not allow the student
 435   * to respond, like the description 'question' type.
 436   *
 437   * @copyright  2009 The Open University
 438   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 439   */
 440  class question_information_item extends question_definition {
 441      public function __construct() {
 442          parent::__construct();
 443          $this->defaultmark = 0;
 444          $this->penalty = 0;
 445          $this->length = 0;
 446      }
 447  
 448      public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
 449          return question_engine::make_behaviour('informationitem', $qa, $preferredbehaviour);
 450      }
 451  
 452      public function get_expected_data() {
 453          return array();
 454      }
 455  
 456      public function get_correct_response() {
 457          return array();
 458      }
 459  
 460      public function get_question_summary() {
 461          return null;
 462      }
 463  }
 464  
 465  
 466  /**
 467   * Interface that a {@link question_definition} must implement to be usable by
 468   * the manual graded behaviour.
 469   *
 470   * @copyright  2009 The Open University
 471   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 472   */
 473  interface question_manually_gradable {
 474      /**
 475       * Use by many of the behaviours to determine whether the student
 476       * has provided enough of an answer for the question to be graded automatically,
 477       * or whether it must be considered aborted.
 478       *
 479       * @param array $response responses, as returned by
 480       *      {@link question_attempt_step::get_qt_data()}.
 481       * @return bool whether this response can be graded.
 482       */
 483      public function is_gradable_response(array $response);
 484  
 485      /**
 486       * Used by many of the behaviours, to work out whether the student's
 487       * response to the question is complete. That is, whether the question attempt
 488       * should move to the COMPLETE or INCOMPLETE state.
 489       *
 490       * @param array $response responses, as returned by
 491       *      {@link question_attempt_step::get_qt_data()}.
 492       * @return bool whether this response is a complete answer to this question.
 493       */
 494      public function is_complete_response(array $response);
 495  
 496      /**
 497       * Use by many of the behaviours to determine whether the student's
 498       * response has changed. This is normally used to determine that a new set
 499       * of responses can safely be discarded.
 500       *
 501       * @param array $prevresponse the responses previously recorded for this question,
 502       *      as returned by {@link question_attempt_step::get_qt_data()}
 503       * @param array $newresponse the new responses, in the same format.
 504       * @return bool whether the two sets of responses are the same - that is
 505       *      whether the new set of responses can safely be discarded.
 506       */
 507      public function is_same_response(array $prevresponse, array $newresponse);
 508  
 509      /**
 510       * Produce a plain text summary of a response.
 511       * @param array $response a response, as might be passed to {@link grade_response()}.
 512       * @return string a plain text summary of that response, that could be used in reports.
 513       */
 514      public function summarise_response(array $response);
 515  
 516      /**
 517       * If possible, construct a response that could have lead to the given
 518       * response summary. This is basically the opposite of {@link summarise_response()}
 519       * but it is intended only to be used for testing.
 520       *
 521       * @param string $summary a string, which might have come from summarise_response
 522       * @return array a response that could have lead to that.
 523       */
 524      public function un_summarise_response(string $summary);
 525  
 526      /**
 527       * Categorise the student's response according to the categories defined by
 528       * get_possible_responses.
 529       * @param $response a response, as might be passed to {@link grade_response()}.
 530       * @return array subpartid => {@link question_classified_response} objects.
 531       *      returns an empty array if no analysis is possible.
 532       */
 533      public function classify_response(array $response);
 534  }
 535  
 536  
 537  /**
 538   * This class is used in the return value from
 539   * {@link question_manually_gradable::classify_response()}.
 540   *
 541   * @copyright  2010 The Open University
 542   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 543   */
 544  class question_classified_response {
 545      /**
 546       * @var string the classification of this response the student gave to this
 547       * part of the question. Must match one of the responseclasses returned by
 548       * {@link question_type::get_possible_responses()}.
 549       */
 550      public $responseclassid;
 551      /** @var string the actual response the student gave to this part. */
 552      public $response;
 553      /** @var number the fraction this part of the response earned. */
 554      public $fraction;
 555      /**
 556       * Constructor, just an easy way to set the fields.
 557       * @param string $responseclassid see the field descriptions above.
 558       * @param string $response see the field descriptions above.
 559       * @param number $fraction see the field descriptions above.
 560       */
 561      public function __construct($responseclassid, $response, $fraction) {
 562          $this->responseclassid = $responseclassid;
 563          $this->response = $response;
 564          $this->fraction = $fraction;
 565      }
 566  
 567      public static function no_response() {
 568          return new question_classified_response(null, get_string('noresponse', 'question'), null);
 569      }
 570  }
 571  
 572  
 573  /**
 574   * Interface that a {@link question_definition} must implement to be usable by
 575   * the various automatic grading behaviours.
 576   *
 577   * @copyright  2009 The Open University
 578   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 579   */
 580  interface question_automatically_gradable extends question_manually_gradable {
 581      /**
 582       * In situations where is_gradable_response() returns false, this method
 583       * should generate a description of what the problem is.
 584       * @return string the message.
 585       */
 586      public function get_validation_error(array $response);
 587  
 588      /**
 589       * Grade a response to the question, returning a fraction between
 590       * get_min_fraction() and get_max_fraction(), and the corresponding {@link question_state}
 591       * right, partial or wrong.
 592       * @param array $response responses, as returned by
 593       *      {@link question_attempt_step::get_qt_data()}.
 594       * @return array (float, integer) the fraction, and the state.
 595       */
 596      public function grade_response(array $response);
 597  
 598      /**
 599       * Get one of the question hints. The question_attempt is passed in case
 600       * the question type wants to do something complex. For example, the
 601       * multiple choice with multiple responses question type will turn off most
 602       * of the hint options if the student has selected too many opitions.
 603       * @param int $hintnumber Which hint to display. Indexed starting from 0
 604       * @param question_attempt $qa The question_attempt.
 605       */
 606      public function get_hint($hintnumber, question_attempt $qa);
 607  
 608      /**
 609       * Generate a brief, plain-text, summary of the correct answer to this question.
 610       * This is used by various reports, and can also be useful when testing.
 611       * This method will return null if such a summary is not possible, or
 612       * inappropriate.
 613       * @return string|null a plain text summary of the right answer to this question.
 614       */
 615      public function get_right_answer_summary();
 616  }
 617  
 618  
 619  /**
 620   * Interface that a {@link question_definition} must implement to be usable by
 621   * the interactivecountback behaviour.
 622   *
 623   * @copyright  2010 The Open University
 624   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 625   */
 626  interface question_automatically_gradable_with_countback extends question_automatically_gradable {
 627      /**
 628       * Work out a final grade for this attempt, taking into account all the
 629       * tries the student made.
 630       * @param array $responses the response for each try. Each element of this
 631       * array is a response array, as would be passed to {@link grade_response()}.
 632       * There may be between 1 and $totaltries responses.
 633       * @param int $totaltries The maximum number of tries allowed.
 634       * @return numeric the fraction that should be awarded for this
 635       * sequence of response.
 636       */
 637      public function compute_final_grade($responses, $totaltries);
 638  }
 639  
 640  
 641  /**
 642   * This class represents a real question. That is, one that is not a
 643   * {@link question_information_item}.
 644   *
 645   * @copyright  2009 The Open University
 646   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 647   */
 648  abstract class question_with_responses extends question_definition
 649          implements question_manually_gradable {
 650      public function classify_response(array $response) {
 651          return array();
 652      }
 653  
 654      public function is_gradable_response(array $response) {
 655          return $this->is_complete_response($response);
 656      }
 657  
 658      public function un_summarise_response(string $summary) {
 659          throw new coding_exception('This question type (' . get_class($this) .
 660                  ' does not implement the un_summarise_response testing method.');
 661      }
 662  }
 663  
 664  
 665  /**
 666   * This class represents a question that can be graded automatically.
 667   *
 668   * @copyright  2009 The Open University
 669   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 670   */
 671  abstract class question_graded_automatically extends question_with_responses
 672          implements question_automatically_gradable {
 673      /** @var Some question types have the option to show the number of sub-parts correct. */
 674      public $shownumcorrect = false;
 675  
 676      public function get_right_answer_summary() {
 677          $correctresponse = $this->get_correct_response();
 678          if (empty($correctresponse)) {
 679              return null;
 680          }
 681          return $this->summarise_response($correctresponse);
 682      }
 683  
 684      /**
 685       * Check a request for access to a file belonging to a combined feedback field.
 686       * @param question_attempt $qa the question attempt being displayed.
 687       * @param question_display_options $options the options that control display of the question.
 688       * @param string $filearea the name of the file area.
 689       * @param array $args the remaining bits of the file path.
 690       * @return bool whether access to the file should be allowed.
 691       */
 692      protected function check_combined_feedback_file_access($qa, $options, $filearea, $args = null) {
 693          $state = $qa->get_state();
 694  
 695          if ($args === null) {
 696              debugging('You must pass $args as the fourth argument to check_combined_feedback_file_access.',
 697                      DEBUG_DEVELOPER);
 698              $args = array($this->id); // Fake it for now, so the rest of this method works.
 699          }
 700  
 701          if (!$state->is_finished()) {
 702              $response = $qa->get_last_qt_data();
 703              if (!$this->is_gradable_response($response)) {
 704                  return false;
 705              }
 706              list($notused, $state) = $this->grade_response($response);
 707          }
 708  
 709          return $options->feedback && $state->get_feedback_class() . 'feedback' == $filearea &&
 710                  $args[0] == $this->id;
 711      }
 712  
 713      /**
 714       * Check a request for access to a file belonging to a hint.
 715       * @param question_attempt $qa the question attempt being displayed.
 716       * @param question_display_options $options the options that control display of the question.
 717       * @param array $args the remaining bits of the file path.
 718       * @return bool whether access to the file should be allowed.
 719       */
 720      protected function check_hint_file_access($qa, $options, $args) {
 721          if (!$options->feedback) {
 722              return false;
 723          }
 724          $hint = $qa->get_applicable_hint();
 725          $hintid = reset($args); // Itemid is hint id.
 726          return $hintid == $hint->id;
 727      }
 728  
 729      public function get_hint($hintnumber, question_attempt $qa) {
 730          if (!isset($this->hints[$hintnumber])) {
 731              return null;
 732          }
 733          return $this->hints[$hintnumber];
 734      }
 735  
 736      public function format_hint(question_hint $hint, question_attempt $qa) {
 737          return $this->format_text($hint->hint, $hint->hintformat, $qa,
 738                  'question', 'hint', $hint->id);
 739      }
 740  }
 741  
 742  
 743  /**
 744   * This class represents a question that can be graded automatically with
 745   * countback grading in interactive mode.
 746   *
 747   * @copyright  2010 The Open University
 748   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 749   */
 750  abstract class question_graded_automatically_with_countback
 751          extends question_graded_automatically
 752          implements question_automatically_gradable_with_countback {
 753  
 754      public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
 755          if ($preferredbehaviour == 'interactive') {
 756              return question_engine::make_behaviour('interactivecountback',
 757                      $qa, $preferredbehaviour);
 758          }
 759          return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
 760      }
 761  }
 762  
 763  
 764  /**
 765   * This class represents a question that can be graded automatically by using
 766   * a {@link question_grading_strategy}.
 767   *
 768   * @copyright  2009 The Open University
 769   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 770   */
 771  abstract class question_graded_by_strategy extends question_graded_automatically {
 772      /** @var question_grading_strategy the strategy to use for grading. */
 773      protected $gradingstrategy;
 774  
 775      /** @param question_grading_strategy  $strategy the strategy to use for grading. */
 776      public function __construct(question_grading_strategy $strategy) {
 777          parent::__construct();
 778          $this->gradingstrategy = $strategy;
 779      }
 780  
 781      public function get_correct_response() {
 782          $answer = $this->get_correct_answer();
 783          if (!$answer) {
 784              return array();
 785          }
 786  
 787          return array('answer' => $answer->answer);
 788      }
 789  
 790      /**
 791       * Get an answer that contains the feedback and fraction that should be
 792       * awarded for this resonse.
 793       * @param array $response a response.
 794       * @return question_answer the matching answer.
 795       */
 796      public function get_matching_answer(array $response) {
 797          return $this->gradingstrategy->grade($response);
 798      }
 799  
 800      /**
 801       * @return question_answer an answer that contains the a response that would
 802       *      get full marks.
 803       */
 804      public function get_correct_answer() {
 805          return $this->gradingstrategy->get_correct_answer();
 806      }
 807  
 808      public function grade_response(array $response) {
 809          $answer = $this->get_matching_answer($response);
 810          if ($answer) {
 811              return array($answer->fraction,
 812                      question_state::graded_state_for_fraction($answer->fraction));
 813          } else {
 814              return array(0, question_state::$gradedwrong);
 815          }
 816      }
 817  
 818      public function classify_response(array $response) {
 819          if (empty($response['answer'])) {
 820              return array($this->id => question_classified_response::no_response());
 821          }
 822  
 823          $ans = $this->get_matching_answer($response);
 824          if (!$ans) {
 825              return array($this->id => new question_classified_response(
 826                      0, $response['answer'], 0));
 827          }
 828  
 829          return array($this->id => new question_classified_response(
 830                  $ans->id, $response['answer'], $ans->fraction));
 831      }
 832  }
 833  
 834  
 835  /**
 836   * Class to represent a question answer, loaded from the question_answers table
 837   * in the database.
 838   *
 839   * @copyright  2009 The Open University
 840   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 841   */
 842  class question_answer {
 843      /** @var integer the answer id. */
 844      public $id;
 845  
 846      /** @var string the answer. */
 847      public $answer;
 848  
 849      /** @var integer one of the FORMAT_... constans. */
 850      public $answerformat = FORMAT_PLAIN;
 851  
 852      /** @var number the fraction this answer is worth. */
 853      public $fraction;
 854  
 855      /** @var string the feedback for this answer. */
 856      public $feedback;
 857  
 858      /** @var integer one of the FORMAT_... constans. */
 859      public $feedbackformat;
 860  
 861      /**
 862       * Constructor.
 863       * @param int $id the answer.
 864       * @param string $answer the answer.
 865       * @param number $fraction the fraction this answer is worth.
 866       * @param string $feedback the feedback for this answer.
 867       * @param int $feedbackformat the format of the feedback.
 868       */
 869      public function __construct($id, $answer, $fraction, $feedback, $feedbackformat) {
 870          $this->id = $id;
 871          $this->answer = $answer;
 872          $this->fraction = $fraction;
 873          $this->feedback = $feedback;
 874          $this->feedbackformat = $feedbackformat;
 875      }
 876  }
 877  
 878  
 879  /**
 880   * Class to represent a hint associated with a question.
 881   * Used by iteractive mode, etc. A question has an array of these.
 882   *
 883   * @copyright  2010 The Open University
 884   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 885   */
 886  class question_hint {
 887      /** @var integer The hint id. */
 888      public $id;
 889      /** @var string The feedback hint to be shown. */
 890      public $hint;
 891      /** @var integer The corresponding text FORMAT_... type. */
 892      public $hintformat;
 893  
 894      /**
 895       * Constructor.
 896       * @param int the hint id from the database.
 897       * @param string $hint The hint text
 898       * @param int the corresponding text FORMAT_... type.
 899       */
 900      public function __construct($id, $hint, $hintformat) {
 901          $this->id = $id;
 902          $this->hint = $hint;
 903          $this->hintformat = $hintformat;
 904      }
 905  
 906      /**
 907       * Create a basic hint from a row loaded from the question_hints table in the database.
 908       * @param object $row with $row->hint set.
 909       * @return question_hint
 910       */
 911      public static function load_from_record($row) {
 912          return new question_hint($row->id, $row->hint, $row->hintformat);
 913      }
 914  
 915      /**
 916       * Adjust this display options according to the hint settings.
 917       * @param question_display_options $options
 918       */
 919      public function adjust_display_options(question_display_options $options) {
 920          // Do nothing.
 921      }
 922  }
 923  
 924  
 925  /**
 926   * An extension of {@link question_hint} for questions like match and multiple
 927   * choice with multile answers, where there are options for whether to show the
 928   * number of parts right at each stage, and to reset the wrong parts.
 929   *
 930   * @copyright  2010 The Open University
 931   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 932   */
 933  class question_hint_with_parts extends question_hint {
 934      /** @var boolean option to show the number of sub-parts of the question that were right. */
 935      public $shownumcorrect;
 936  
 937      /** @var boolean option to clear the parts of the question that were wrong on retry. */
 938      public $clearwrong;
 939  
 940      /**
 941       * Constructor.
 942       * @param int the hint id from the database.
 943       * @param string $hint The hint text
 944       * @param int the corresponding text FORMAT_... type.
 945       * @param bool $shownumcorrect whether the number of right parts should be shown
 946       * @param bool $clearwrong whether the wrong parts should be reset.
 947       */
 948      public function __construct($id, $hint, $hintformat, $shownumcorrect, $clearwrong) {
 949          parent::__construct($id, $hint, $hintformat);
 950          $this->shownumcorrect = $shownumcorrect;
 951          $this->clearwrong = $clearwrong;
 952      }
 953  
 954      /**
 955       * Create a basic hint from a row loaded from the question_hints table in the database.
 956       * @param object $row with $row->hint, ->shownumcorrect and ->clearwrong set.
 957       * @return question_hint_with_parts
 958       */
 959      public static function load_from_record($row) {
 960          return new question_hint_with_parts($row->id, $row->hint, $row->hintformat,
 961                  $row->shownumcorrect, $row->clearwrong);
 962      }
 963  
 964      public function adjust_display_options(question_display_options $options) {
 965          parent::adjust_display_options($options);
 966          if ($this->clearwrong) {
 967              $options->clearwrong = true;
 968          }
 969          $options->numpartscorrect = $this->shownumcorrect;
 970      }
 971  }
 972  
 973  
 974  /**
 975   * This question_grading_strategy interface. Used to share grading code between
 976   * questions that that subclass {@link question_graded_by_strategy}.
 977   *
 978   * @copyright  2009 The Open University
 979   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 980   */
 981  interface question_grading_strategy {
 982      /**
 983       * Return a question answer that describes the outcome (fraction and feeback)
 984       * for a particular respons.
 985       * @param array $response the response.
 986       * @return question_answer the answer describing the outcome.
 987       */
 988      public function grade(array $response);
 989  
 990      /**
 991       * @return question_answer an answer that contains the a response that would
 992       *      get full marks.
 993       */
 994      public function get_correct_answer();
 995  }
 996  
 997  
 998  /**
 999   * This interface defines the methods that a {@link question_definition} must
1000   * implement if it is to be graded by the
1001   * {@link question_first_matching_answer_grading_strategy}.
1002   *
1003   * @copyright  2009 The Open University
1004   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1005   */
1006  interface question_response_answer_comparer {
1007      /** @return array of {@link question_answers}. */
1008      public function get_answers();
1009  
1010      /**
1011       * @param array $response the response.
1012       * @param question_answer $answer an answer.
1013       * @return bool whether the response matches the answer.
1014       */
1015      public function compare_response_with_answer(array $response, question_answer $answer);
1016  }
1017  
1018  
1019  /**
1020   * This grading strategy is used by question types like shortanswer an numerical.
1021   * It gets a list of possible answers from the question, and returns the first one
1022   * that matches the given response. It returns the first answer with fraction 1.0
1023   * when asked for the correct answer.
1024   *
1025   * @copyright  2009 The Open University
1026   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1027   */
1028  class question_first_matching_answer_grading_strategy implements question_grading_strategy {
1029      /**
1030       * @var question_response_answer_comparer (presumably also a
1031       * {@link question_definition}) the question we are doing the grading for.
1032       */
1033      protected $question;
1034  
1035      /**
1036       * @param question_response_answer_comparer $question (presumably also a
1037       * {@link question_definition}) the question we are doing the grading for.
1038       */
1039      public function __construct(question_response_answer_comparer $question) {
1040          $this->question = $question;
1041      }
1042  
1043      public function grade(array $response) {
1044          foreach ($this->question->get_answers() as $aid => $answer) {
1045              if ($this->question->compare_response_with_answer($response, $answer)) {
1046                  $answer->id = $aid;
1047                  return $answer;
1048              }
1049          }
1050          return null;
1051      }
1052  
1053      public function get_correct_answer() {
1054          foreach ($this->question->get_answers() as $answer) {
1055              $state = question_state::graded_state_for_fraction($answer->fraction);
1056              if ($state == question_state::$gradedright) {
1057                  return $answer;
1058              }
1059          }
1060          return null;
1061      }
1062  }