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   * Numerical question definition class.
  19   *
  20   * @package    qtype
  21   * @subpackage numerical
  22   * @copyright  2009 The Open University
  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/type/questionbase.php');
  30  
  31  /**
  32   * Represents a numerical question.
  33   *
  34   * @copyright  2009 The Open University
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class qtype_numerical_question extends question_graded_automatically {
  38      /** @var array of question_answer. */
  39      public $answers = array();
  40  
  41      /** @var int one of the constants UNITNONE, UNITRADIO, UNITSELECT or UNITINPUT. */
  42      public $unitdisplay;
  43      /** @var int one of the constants UNITGRADEDOUTOFMARK or UNITGRADEDOUTOFMAX. */
  44      public $unitgradingtype;
  45      /** @var number the penalty for a missing or unrecognised unit. */
  46      public $unitpenalty;
  47      /** @var boolean whether the units come before or after the number */
  48      public $unitsleft;
  49      /** @var qtype_numerical_answer_processor */
  50      public $ap;
  51  
  52      public function get_expected_data() {
  53          $expected = array('answer' => PARAM_RAW_TRIMMED);
  54          if ($this->has_separate_unit_field()) {
  55              $expected['unit'] = PARAM_RAW_TRIMMED;
  56          }
  57          return $expected;
  58      }
  59  
  60      public function has_separate_unit_field() {
  61          return $this->unitdisplay == qtype_numerical::UNITRADIO ||
  62                  $this->unitdisplay == qtype_numerical::UNITSELECT;
  63      }
  64  
  65      public function start_attempt(question_attempt_step $step, $variant) {
  66          $step->set_qt_var('_separators',
  67                  $this->ap->get_point() . '$' . $this->ap->get_separator());
  68      }
  69  
  70      public function apply_attempt_state(question_attempt_step $step) {
  71          list($point, $separator) = explode('$', $step->get_qt_var('_separators'));
  72                  $this->ap->set_characters($point, $separator);
  73      }
  74  
  75      public function summarise_response(array $response) {
  76          if (isset($response['answer'])) {
  77              $resp = $response['answer'];
  78          } else {
  79              $resp = null;
  80          }
  81  
  82          if ($this->has_separate_unit_field() && !empty($response['unit'])) {
  83              $resp = $this->ap->add_unit($resp, $response['unit']);
  84          }
  85  
  86          return $resp;
  87      }
  88  
  89      public function un_summarise_response(string $summary) {
  90          if ($this->has_separate_unit_field()) {
  91              throw new coding_exception('Sorry, but at the moment un_summarise_response cannot handle the
  92                  has_separate_unit_field case for numerical questions.
  93                      If you need this, you will have to implement it yourself.');
  94          }
  95  
  96          if (!empty($summary)) {
  97              return ['answer' => $summary];
  98          } else {
  99              return [];
 100          }
 101      }
 102  
 103      public function is_gradable_response(array $response) {
 104          return array_key_exists('answer', $response) &&
 105                  ($response['answer'] || $response['answer'] === '0' || $response['answer'] === 0);
 106      }
 107  
 108      public function is_complete_response(array $response) {
 109          if (!$this->is_gradable_response($response)) {
 110              return false;
 111          }
 112  
 113          list($value, $unit) = $this->ap->apply_units($response['answer']);
 114          if (is_null($value)) {
 115              return false;
 116          }
 117  
 118          if ($this->unitdisplay != qtype_numerical::UNITINPUT && $unit) {
 119              return false;
 120          }
 121  
 122          if ($this->has_separate_unit_field() && empty($response['unit'])) {
 123              return false;
 124          }
 125  
 126          if ($this->ap->contains_thousands_seaparator($response['answer'])) {
 127              return false;
 128          }
 129  
 130          return true;
 131      }
 132  
 133      public function get_validation_error(array $response) {
 134          if (!$this->is_gradable_response($response)) {
 135              return get_string('pleaseenterananswer', 'qtype_numerical');
 136          }
 137  
 138          list($value, $unit) = $this->ap->apply_units($response['answer']);
 139          if (is_null($value)) {
 140              return get_string('invalidnumber', 'qtype_numerical');
 141          }
 142  
 143          if ($this->unitdisplay != qtype_numerical::UNITINPUT && $unit) {
 144              return get_string('invalidnumbernounit', 'qtype_numerical');
 145          }
 146  
 147          if ($this->has_separate_unit_field() && empty($response['unit'])) {
 148              return get_string('unitnotselected', 'qtype_numerical');
 149          }
 150  
 151          if ($this->ap->contains_thousands_seaparator($response['answer'])) {
 152              return get_string('pleaseenteranswerwithoutthousandssep', 'qtype_numerical',
 153                      $this->ap->get_separator());
 154          }
 155  
 156          return '';
 157      }
 158  
 159      public function is_same_response(array $prevresponse, array $newresponse) {
 160          if (!question_utils::arrays_same_at_key_missing_is_blank(
 161                  $prevresponse, $newresponse, 'answer')) {
 162              return false;
 163          }
 164  
 165          if ($this->has_separate_unit_field()) {
 166              return question_utils::arrays_same_at_key_missing_is_blank(
 167                  $prevresponse, $newresponse, 'unit');
 168          }
 169  
 170          return true;
 171      }
 172  
 173      public function get_correct_response() {
 174          $answer = $this->get_correct_answer();
 175          if (!$answer) {
 176              return array();
 177          }
 178  
 179          $response = array('answer' => str_replace('.', $this->ap->get_point(), $answer->answer));
 180  
 181          if ($this->has_separate_unit_field()) {
 182              $response['unit'] = $this->ap->get_default_unit();
 183          } else if ($this->unitdisplay == qtype_numerical::UNITINPUT) {
 184              $response['answer'] = $this->ap->add_unit($answer->answer);
 185          }
 186  
 187          return $response;
 188      }
 189  
 190      /**
 191       * Get an answer that contains the feedback and fraction that should be
 192       * awarded for this response.
 193       * @param number $value the numerical value of a response.
 194       * @param number $multiplier for the unit the student gave, if any. When no
 195       *      unit was given, or an unrecognised unit was given, $multiplier will be null.
 196       * @return question_answer the matching answer.
 197       */
 198      public function get_matching_answer($value, $multiplier) {
 199          if (is_null($value) || $value === '') {
 200              return null;
 201          }
 202  
 203          if (!is_null($multiplier)) {
 204              $scaledvalue = $value * $multiplier;
 205          } else {
 206              $scaledvalue = $value;
 207          }
 208          foreach ($this->answers as $answer) {
 209              if ($answer->within_tolerance($scaledvalue)) {
 210                  $answer->unitisright = !is_null($multiplier);
 211                  return $answer;
 212              } else if ($answer->within_tolerance($value)) {
 213                  $answer->unitisright = false;
 214                  return $answer;
 215              }
 216          }
 217  
 218          return null;
 219      }
 220  
 221      public function get_correct_answer() {
 222          foreach ($this->answers as $answer) {
 223              $state = question_state::graded_state_for_fraction($answer->fraction);
 224              if ($state == question_state::$gradedright) {
 225                  return $answer;
 226              }
 227          }
 228          return null;
 229      }
 230  
 231      /**
 232       * Adjust the fraction based on whether the unit was correct.
 233       * @param number $fraction
 234       * @param bool $unitisright
 235       * @return number
 236       */
 237      public function apply_unit_penalty($fraction, $unitisright) {
 238          if ($unitisright) {
 239              return $fraction;
 240          }
 241  
 242          if ($this->unitgradingtype == qtype_numerical::UNITGRADEDOUTOFMARK) {
 243              $fraction -= $this->unitpenalty * $fraction;
 244          } else if ($this->unitgradingtype == qtype_numerical::UNITGRADEDOUTOFMAX) {
 245              $fraction -= $this->unitpenalty;
 246          }
 247          return max($fraction, 0);
 248      }
 249  
 250      public function grade_response(array $response) {
 251          if ($this->has_separate_unit_field()) {
 252              $selectedunit = $response['unit'];
 253          } else {
 254              $selectedunit = null;
 255          }
 256          list($value, $unit, $multiplier) = $this->ap->apply_units(
 257                  $response['answer'], $selectedunit);
 258  
 259          $answer = $this->get_matching_answer($value, $multiplier);
 260          if (!$answer) {
 261              return array(0, question_state::$gradedwrong);
 262          }
 263  
 264          $fraction = $this->apply_unit_penalty($answer->fraction, $answer->unitisright);
 265          return array($fraction, question_state::graded_state_for_fraction($fraction));
 266      }
 267  
 268      public function classify_response(array $response) {
 269          if (!$this->is_gradable_response($response)) {
 270              return array($this->id => question_classified_response::no_response());
 271          }
 272  
 273          if ($this->has_separate_unit_field()) {
 274              $selectedunit = $response['unit'];
 275          } else {
 276              $selectedunit = null;
 277          }
 278          list($value, $unit, $multiplier) = $this->ap->apply_units($response['answer'], $selectedunit);
 279          $ans = $this->get_matching_answer($value, $multiplier);
 280  
 281          $resp = $response['answer'];
 282          if ($this->has_separate_unit_field()) {
 283              $resp = $this->ap->add_unit($resp, $unit);
 284          }
 285  
 286          if ($value === null) {
 287              // Invalid response shown as no response (but show actual response).
 288              return array($this->id => new question_classified_response(null, $resp, 0));
 289          } else if (!$ans) {
 290              // Does not match any answer.
 291              return array($this->id => new question_classified_response(0, $resp, 0));
 292          }
 293  
 294          return array($this->id => new question_classified_response($ans->id,
 295                  $resp,
 296                  $this->apply_unit_penalty($ans->fraction, $ans->unitisright)));
 297      }
 298  
 299      public function check_file_access($qa, $options, $component, $filearea, $args,
 300              $forcedownload) {
 301          if ($component == 'question' && $filearea == 'answerfeedback') {
 302              $currentanswer = $qa->get_last_qt_var('answer');
 303              if ($this->has_separate_unit_field()) {
 304                  $selectedunit = $qa->get_last_qt_var('unit');
 305              } else {
 306                  $selectedunit = null;
 307              }
 308              list($value, $unit, $multiplier) = $this->ap->apply_units(
 309                      $currentanswer, $selectedunit);
 310              $answer = $this->get_matching_answer($value, $multiplier);
 311              $answerid = reset($args); // Itemid is answer id.
 312              return $options->feedback && $answer && $answerid == $answer->id;
 313  
 314          } else if ($component == 'question' && $filearea == 'hint') {
 315              return $this->check_hint_file_access($qa, $options, $args);
 316  
 317          } else {
 318              return parent::check_file_access($qa, $options, $component, $filearea,
 319                      $args, $forcedownload);
 320          }
 321      }
 322  
 323      /**
 324       * Return the question settings that define this question as structured data.
 325       *
 326       * @param question_attempt $qa the current attempt for which we are exporting the settings.
 327       * @param question_display_options $options the question display options which say which aspects of the question
 328       * should be visible.
 329       * @return mixed structure representing the question settings. In web services, this will be JSON-encoded.
 330       */
 331      public function get_question_definition_for_external_rendering(question_attempt $qa, question_display_options $options) {
 332          // This is a partial implementation, returning only the most relevant question settings for now,
 333          // ideally, we should return as much as settings as possible (depending on the state and display options).
 334  
 335          return [
 336              'unitgradingtype' => $this->unitgradingtype,
 337              'unitpenalty' => $this->unitpenalty,
 338              'unitdisplay' => $this->unitdisplay,
 339              'unitsleft' => $this->unitsleft,
 340          ];
 341      }
 342  }
 343  
 344  
 345  /**
 346   * Subclass of {@link question_answer} with the extra information required by
 347   * the numerical question type.
 348   *
 349   * @copyright  2009 The Open University
 350   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 351   */
 352  class qtype_numerical_answer extends question_answer {
 353      /** @var float allowable margin of error. */
 354      public $tolerance;
 355      /** @var integer|string see {@link get_tolerance_interval()} for the meaning of this value. */
 356      public $tolerancetype = 2;
 357  
 358      public function __construct($id, $answer, $fraction, $feedback, $feedbackformat, $tolerance) {
 359          parent::__construct($id, $answer, $fraction, $feedback, $feedbackformat);
 360          $this->tolerance = abs((float)$tolerance);
 361      }
 362  
 363      public function get_tolerance_interval() {
 364          if ($this->answer === '*') {
 365              throw new coding_exception('Cannot work out tolerance interval for answer *.');
 366          }
 367  
 368          // Smallest number that, when added to 1, is different from 1.
 369          $epsilon = pow(10, -1 * ini_get('precision'));
 370  
 371          // We need to add a tiny fraction depending on the set precision to make
 372          // the comparison work correctly, otherwise seemingly equal values can
 373          // yield false. See MDL-3225.
 374          $tolerance = abs($this->tolerance) + $epsilon;
 375  
 376          switch ($this->tolerancetype) {
 377              case 1: case 'relative':
 378                  $range = abs($this->answer) * $tolerance;
 379                  return array($this->answer - $range, $this->answer + $range);
 380  
 381              case 2: case 'nominal':
 382                  $tolerance = $this->tolerance + $epsilon * max(abs($this->tolerance), abs($this->answer), $epsilon);
 383                  return array($this->answer - $tolerance, $this->answer + $tolerance);
 384  
 385              case 3: case 'geometric':
 386                  $quotient = 1 + abs($tolerance);
 387                  return array($this->answer / $quotient, $this->answer * $quotient);
 388  
 389              default:
 390                  throw new coding_exception('Unknown tolerance type ' . $this->tolerancetype);
 391          }
 392      }
 393  
 394      public function within_tolerance($value) {
 395          if ($this->answer === '*') {
 396              return true;
 397          }
 398          list($min, $max) = $this->get_tolerance_interval();
 399          return $min <= $value && $value <= $max;
 400      }
 401  }