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  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Numerical
  20   *
  21   * @package mod_lesson
  22   * @copyright  2009 Sam Hemelryk
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   **/
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  /** Numerical question type */
  29  define("LESSON_PAGE_NUMERICAL",     "8");
  30  
  31  use mod_lesson\local\numeric\helper;
  32  
  33  class lesson_page_type_numerical extends lesson_page {
  34  
  35      protected $type = lesson_page::TYPE_QUESTION;
  36      protected $typeidstring = 'numerical';
  37      protected $typeid = LESSON_PAGE_NUMERICAL;
  38      protected $string = null;
  39  
  40      public function get_typeid() {
  41          return $this->typeid;
  42      }
  43      public function get_typestring() {
  44          if ($this->string===null) {
  45              $this->string = get_string($this->typeidstring, 'lesson');
  46          }
  47          return $this->string;
  48      }
  49      public function get_idstring() {
  50          return $this->typeidstring;
  51      }
  52      public function display($renderer, $attempt) {
  53          global $USER, $PAGE;
  54          $mform = new lesson_display_answer_form_numerical(new moodle_url('/mod/lesson/continue.php'),
  55              array('contents' => $this->get_contents(), 'lessonid' => $this->lesson->id));
  56          $data = new stdClass;
  57          $data->id = $PAGE->cm->id;
  58          $data->pageid = $this->properties->id;
  59          if (isset($USER->modattempts[$this->lesson->id])) {
  60              $data->answer = s($attempt->useranswer);
  61          }
  62          $mform->set_data($data);
  63  
  64          // Trigger an event question viewed.
  65          $eventparams = array(
  66              'context' => context_module::instance($PAGE->cm->id),
  67              'objectid' => $this->properties->id,
  68              'other' => array(
  69                      'pagetype' => $this->get_typestring()
  70                  )
  71              );
  72  
  73          $event = \mod_lesson\event\question_viewed::create($eventparams);
  74          $event->trigger();
  75          return $mform->display();
  76      }
  77  
  78      /**
  79       * Creates answers for this page type.
  80       *
  81       * @param  object $properties The answer properties.
  82       */
  83      public function create_answers($properties) {
  84          if (isset($properties->enableotheranswers) && $properties->enableotheranswers) {
  85              $properties->response_editor = array_values($properties->response_editor);
  86              $properties->jumpto = array_values($properties->jumpto);
  87              $properties->score = array_values($properties->score);
  88              $wrongresponse = end($properties->response_editor);
  89              $wrongkey = key($properties->response_editor);
  90              $properties->answer_editor[$wrongkey] = LESSON_OTHER_ANSWERS;
  91          }
  92          parent::create_answers($properties);
  93      }
  94  
  95      /**
  96       * Update the answers for this page type.
  97       *
  98       * @param  object $properties The answer properties.
  99       * @param  context $context The context for this module.
 100       * @param  int $maxbytes The maximum bytes for any uploades.
 101       */
 102      public function update($properties, $context = null, $maxbytes = null) {
 103          if ($properties->enableotheranswers) {
 104              $properties->response_editor = array_values($properties->response_editor);
 105              $properties->jumpto = array_values($properties->jumpto);
 106              $properties->score = array_values($properties->score);
 107              $wrongresponse = end($properties->response_editor);
 108              $wrongkey = key($properties->response_editor);
 109              $properties->answer_editor[$wrongkey] = LESSON_OTHER_ANSWERS;
 110          }
 111          parent::update($properties, $context, $maxbytes);
 112      }
 113  
 114      public function check_answer() {
 115          $result = parent::check_answer();
 116  
 117          $mform = new lesson_display_answer_form_numerical(new moodle_url('/mod/lesson/continue.php'),
 118              array('contents' => $this->get_contents()));
 119          $data = $mform->get_data();
 120          require_sesskey();
 121  
 122          $formattextdefoptions = new stdClass();
 123          $formattextdefoptions->noclean = true;
 124          $formattextdefoptions->para = false;
 125  
 126          // set defaults
 127          $result->response = '';
 128          $result->newpageid = 0;
 129  
 130          if (!isset($data->answer)) {
 131              $result->noanswer = true;
 132              return $result;
 133          } else {
 134              $result->useranswer = $data->answer;
 135          }
 136          $result->studentanswer = $result->userresponse = $result->useranswer;
 137          $answers = $this->get_answers();
 138          foreach ($answers as $answer) {
 139              $answer = parent::rewrite_answers_urls($answer);
 140              if (strpos($answer->answer, ':')) {
 141                  // there's a pairs of values
 142                  list($min, $max) = explode(':', $answer->answer);
 143                  $minimum = (float) $min;
 144                  $maximum = (float) $max;
 145              } else {
 146                  // there's only one value
 147                  $minimum = (float) $answer->answer;
 148                  $maximum = $minimum;
 149              }
 150              if (($result->useranswer >= $minimum) && ($result->useranswer <= $maximum)) {
 151                  $result->newpageid = $answer->jumpto;
 152                  $result->response = format_text($answer->response, $answer->responseformat, $formattextdefoptions);
 153                  if ($this->lesson->jumpto_is_correct($this->properties->id, $result->newpageid)) {
 154                      $result->correctanswer = true;
 155                  }
 156                  if ($this->lesson->custom) {
 157                      if ($answer->score > 0) {
 158                          $result->correctanswer = true;
 159                      } else {
 160                          $result->correctanswer = false;
 161                      }
 162                  }
 163                  $result->answerid = $answer->id;
 164                  return $result;
 165              }
 166          }
 167          // We could check here to see if we have a wrong answer jump to use.
 168          if ($result->answerid == 0) {
 169              // Use the all other answers jump details if it is set up.
 170              $lastanswer = end($answers);
 171              // Double check that this is the @#wronganswer#@ answer.
 172              if (strpos($lastanswer->answer, LESSON_OTHER_ANSWERS) !== false) {
 173                  $otheranswers = end($answers);
 174                  $result->newpageid = $otheranswers->jumpto;
 175                  $result->response = format_text($otheranswers->response, $otheranswers->responseformat, $formattextdefoptions);
 176                  // Does this also need to do the jumpto_is_correct?
 177                  if ($this->lesson->custom) {
 178                      $result->correctanswer = ($otheranswers->score > 0);
 179                  }
 180                  $result->answerid = $otheranswers->id;
 181              }
 182          }
 183          return $result;
 184      }
 185  
 186      public function display_answers(html_table $table) {
 187          $answers = $this->get_answers();
 188          $options = new stdClass;
 189          $options->noclean = true;
 190          $options->para = false;
 191          $i = 1;
 192          foreach ($answers as $answer) {
 193              $answer = parent::rewrite_answers_urls($answer, false);
 194              $cells = array();
 195              if ($this->lesson->custom && $answer->score > 0) {
 196                  // if the score is > 0, then it is correct
 197                  $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
 198              } else if ($this->lesson->custom) {
 199                  $cells[] = '<label>' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
 200              } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
 201                  // underline correct answers
 202                  $cells[] = '<span class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</span>:' . "\n";
 203              } else {
 204                  $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
 205              }
 206              $formattedanswer = helper::lesson_format_numeric_value($answer->answer);
 207              $cells[] = format_text($formattedanswer, $answer->answerformat, $options);
 208              $table->data[] = new html_table_row($cells);
 209  
 210              $cells = array();
 211              $cells[] = '<label>' . get_string('response', 'lesson') . ' ' . $i . '</label>:';
 212              $cells[] = format_text($answer->response, $answer->responseformat, $options);
 213              $table->data[] = new html_table_row($cells);
 214  
 215              $cells = array();
 216              $cells[] = '<label>' . get_string('score', 'lesson') . '</label>:';
 217              $cells[] = $answer->score;
 218              $table->data[] = new html_table_row($cells);
 219  
 220              $cells = array();
 221              $cells[] = '<label>' . get_string('jump', 'lesson') . '</label>:';
 222              $cells[] = $this->get_jump_name($answer->jumpto);
 223              $table->data[] = new html_table_row($cells);
 224              if ($i === 1){
 225                  $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
 226              }
 227              $i++;
 228          }
 229          return $table;
 230      }
 231      public function stats(array &$pagestats, $tries) {
 232          if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
 233              $temp = $tries[$this->lesson->maxattempts - 1];
 234          } else {
 235              // else, user attempted the question less than the max, so grab the last one
 236              $temp = end($tries);
 237          }
 238          if (isset($pagestats[$temp->pageid][$temp->useranswer])) {
 239              $pagestats[$temp->pageid][$temp->useranswer]++;
 240          } else {
 241              $pagestats[$temp->pageid][$temp->useranswer] = 1;
 242          }
 243          if (isset($pagestats[$temp->pageid]["total"])) {
 244              $pagestats[$temp->pageid]["total"]++;
 245          } else {
 246              $pagestats[$temp->pageid]["total"] = 1;
 247          }
 248          return true;
 249      }
 250  
 251      public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
 252          $answers = $this->get_answers();
 253          $formattextdefoptions = new stdClass;
 254          $formattextdefoptions->para = false;  //I'll use it widely in this page
 255          foreach ($answers as $answer) {
 256              if ($useranswer == null && $i == 0) {
 257                  // I have the $i == 0 because it is easier to blast through it all at once.
 258                  if (isset($pagestats[$this->properties->id])) {
 259                      $stats = $pagestats[$this->properties->id];
 260                      $total = $stats["total"];
 261                      unset($stats["total"]);
 262                      foreach ($stats as $valentered => $ntimes) {
 263                          $data = '<input class="form-control" type="text" size="50" ' .
 264                                  'disabled="disabled" readonly="readonly" value="'.
 265                                  s(format_float($valentered, strlen($valentered), true, true)).'" />';
 266                          $percent = $ntimes / $total * 100;
 267                          $percent = round($percent, 2);
 268                          $percent .= "% ".get_string("enteredthis", "lesson");
 269                          $answerdata->answers[] = array($data, $percent);
 270                      }
 271                  } else {
 272                      $answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " ");
 273                  }
 274                  $i++;
 275              } else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) &&
 276                      empty($answerdata->answers)))) {
 277                  // Get in here when the user answered or for the last answer.
 278                  $data = '<input class="form-control" type="text" size="50" ' .
 279                          'disabled="disabled" readonly="readonly" value="'.
 280                          s(format_float($useranswer->useranswer, strlen($useranswer->useranswer), true, true)).'">';
 281                  if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) {
 282                      $percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100;
 283                      $percent = round($percent, 2);
 284                      $percent .= "% ".get_string("enteredthis", "lesson");
 285                  } else {
 286                      $percent = get_string("nooneenteredthis", "lesson");
 287                  }
 288                  $answerdata->answers[] = array($data, $percent);
 289  
 290                  if ($answer->id == $useranswer->answerid) {
 291                      if ($answer->response == null) {
 292                          if ($useranswer->correct) {
 293                              $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
 294                          } else {
 295                              $answerdata->response = get_string("thatsthewronganswer", "lesson");
 296                          }
 297                      } else {
 298                          $answerdata->response = $answer->response;
 299                      }
 300                      if ($this->lesson->custom) {
 301                          $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
 302                      } elseif ($useranswer->correct) {
 303                          $answerdata->score = get_string("receivedcredit", "lesson");
 304                      } else {
 305                          $answerdata->score = get_string("didnotreceivecredit", "lesson");
 306                      }
 307                  } else {
 308                      $answerdata->response = get_string("thatsthewronganswer", "lesson");
 309                      if ($this->lesson->custom) {
 310                          $answerdata->score = get_string("pointsearned", "lesson").": 0";
 311                      } else {
 312                          $answerdata->score = get_string("didnotreceivecredit", "lesson");
 313                      }
 314                  }
 315              }
 316              $answerpage->answerdata = $answerdata;
 317          }
 318          return $answerpage;
 319      }
 320  
 321      /**
 322       * Make updates to the form data if required. In this case to put the all other answer data into the write section of the form.
 323       *
 324       * @param stdClass $data The form data to update.
 325       * @return stdClass The updated fom data.
 326       */
 327      public function update_form_data(stdClass $data) : stdClass {
 328          $answercount = count($this->get_answers());
 329  
 330          // If no answers provided, then we don't need to check anything.
 331          if (!$answercount) {
 332              return $data;
 333          }
 334  
 335          // Check for other answer entry.
 336          $lastanswer = $data->{'answer_editor[' . ($answercount - 1) . ']'};
 337          if (strpos($lastanswer, LESSON_OTHER_ANSWERS) !== false) {
 338              $data->{'answer_editor[' . ($this->lesson->maxanswers + 1) . ']'} =
 339                      $data->{'answer_editor[' . ($answercount - 1) . ']'};
 340              $data->{'response_editor[' . ($this->lesson->maxanswers + 1) . ']'} =
 341                      $data->{'response_editor[' . ($answercount - 1) . ']'};
 342              $data->{'jumpto[' . ($this->lesson->maxanswers + 1) . ']'} = $data->{'jumpto[' . ($answercount - 1) . ']'};
 343              $data->{'score[' . ($this->lesson->maxanswers + 1) . ']'} = $data->{'score[' . ($answercount - 1) . ']'};
 344              $data->enableotheranswers = true;
 345  
 346              // Unset the old values.
 347              unset($data->{'answer_editor[' . ($answercount - 1) . ']'});
 348              unset($data->{'response_editor[' . ($answercount - 1) . ']'});
 349              unset($data->{'jumpto['. ($answercount - 1) . ']'});
 350              unset($data->{'score[' . ($answercount - 1) . ']'});
 351          }
 352  
 353          return $data;
 354      }
 355  }
 356  
 357  class lesson_add_page_form_numerical extends lesson_add_page_form_base {
 358  
 359      public $qtype = 'numerical';
 360      public $qtypestring = 'numerical';
 361      protected $answerformat = '';
 362      protected $responseformat = LESSON_ANSWER_HTML;
 363  
 364      public function custom_definition() {
 365          $answercount = $this->_customdata['lesson']->maxanswers;
 366          for ($i = 0; $i < $answercount; $i++) {
 367              $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1));
 368              $this->add_answer($i, null, ($i < 1), '', [
 369                      'identifier' => 'numericanswer',
 370                      'component' => 'mod_lesson'
 371              ]);
 372              $this->add_response($i);
 373              $this->add_jumpto($i, null, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE));
 374              $this->add_score($i, null, ($i===0)?1:0);
 375          }
 376          // Wrong answer jump.
 377          $this->_form->addElement('header', 'wronganswer', get_string('allotheranswers', 'lesson'));
 378          $newcount = $answercount + 1;
 379          $this->_form->addElement('advcheckbox', 'enableotheranswers', get_string('enabled', 'lesson'));
 380          $this->add_response($newcount);
 381          $this->add_jumpto($newcount, get_string('allotheranswersjump', 'lesson'), LESSON_NEXTPAGE);
 382          $this->add_score($newcount, get_string('allotheranswersscore', 'lesson'), 0);
 383      }
 384  
 385      /**
 386       * We call get data when storing the data into the db. Override to format the floats properly
 387       *
 388       * @return object|void
 389       */
 390      public function get_data() : ?stdClass {
 391          $data = parent::get_data();
 392  
 393          if (!empty($data->answer_editor)) {
 394              foreach ($data->answer_editor as $key => $answer) {
 395                  $data->answer_editor[$key] = helper::lesson_unformat_numeric_value($answer);
 396              }
 397          }
 398  
 399          return $data;
 400      }
 401  
 402      /**
 403       * Return submitted data if properly submitted or returns NULL if validation fails or
 404       * if there is no submitted data with formatted numbers
 405       *
 406       * @return object submitted data; NULL if not valid or not submitted or cancelled
 407       */
 408      public function get_submitted_data() : ?stdClass {
 409          $data = parent::get_submitted_data();
 410  
 411          if (!empty($data->answer_editor)) {
 412              foreach ($data->answer_editor as $key => $answer) {
 413                  $data->answer_editor[$key] = helper::lesson_unformat_numeric_value($answer);
 414              }
 415          }
 416  
 417          return $data;
 418      }
 419  
 420      /**
 421       * Load in existing data as form defaults. Usually new entry defaults are stored directly in
 422       * form definition (new entry form); this function is used to load in data where values
 423       * already exist and data is being edited (edit entry form) after formatting numbers
 424       *
 425       *
 426       * @param stdClass|array $defaults object or array of default values
 427       */
 428      public function set_data($defaults) {
 429          if (is_object($defaults)) {
 430              $defaults = (array) $defaults;
 431          }
 432  
 433          $editor = 'answer_editor';
 434          foreach ($defaults as $key => $answer) {
 435              if (substr($key, 0, strlen($editor)) == $editor) {
 436                  $defaults[$key] = helper::lesson_format_numeric_value($answer);
 437              }
 438          }
 439  
 440          parent::set_data($defaults);
 441      }
 442  }
 443  
 444  class lesson_display_answer_form_numerical extends moodleform {
 445  
 446      public function definition() {
 447          global $USER, $OUTPUT;
 448          $mform = $this->_form;
 449          $contents = $this->_customdata['contents'];
 450  
 451          // Disable shortforms.
 452          $mform->setDisableShortforms();
 453  
 454          $mform->addElement('header', 'pageheader');
 455  
 456          $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
 457  
 458          $hasattempt = false;
 459          $attrs = array('size'=>'50', 'maxlength'=>'200');
 460          if (isset($this->_customdata['lessonid'])) {
 461              $lessonid = $this->_customdata['lessonid'];
 462              if (isset($USER->modattempts[$lessonid]->useranswer)) {
 463                  $attrs['readonly'] = 'readonly';
 464                  $hasattempt = true;
 465              }
 466          }
 467          $options = new stdClass;
 468          $options->para = false;
 469          $options->noclean = true;
 470  
 471          $mform->addElement('hidden', 'id');
 472          $mform->setType('id', PARAM_INT);
 473  
 474          $mform->addElement('hidden', 'pageid');
 475          $mform->setType('pageid', PARAM_INT);
 476  
 477          $mform->addElement('float', 'answer', get_string('youranswer', 'lesson'), $attrs);
 478  
 479          if ($hasattempt) {
 480              $this->add_action_buttons(null, get_string("nextpage", "lesson"));
 481          } else {
 482              $this->add_action_buttons(null, get_string("submit", "lesson"));
 483          }
 484      }
 485  }