Search moodle.org's
Developer Documentation

See Release Notes

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

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

   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   * Multiple choice question definition classes.
  19   *
  20   * @package    qtype
  21   * @subpackage multichoice
  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   * Base class for multiple choice questions. The parts that are common to
  33   * single select and multiple select.
  34   *
  35   * @copyright  2009 The Open University
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  abstract class qtype_multichoice_base extends question_graded_automatically {
  39      const LAYOUT_DROPDOWN = 0;
  40      const LAYOUT_VERTICAL = 1;
  41      const LAYOUT_HORIZONTAL = 2;
  42  
  43      public $answers;
  44  
  45      public $shuffleanswers;
  46      public $answernumbering;
  47      /**
  48       * @var int standard instruction to be displayed if enabled.
  49       */
  50      public $showstandardinstruction = 0;
  51      public $layout = self::LAYOUT_VERTICAL;
  52  
  53      public $correctfeedback;
  54      public $correctfeedbackformat;
  55      public $partiallycorrectfeedback;
  56      public $partiallycorrectfeedbackformat;
  57      public $incorrectfeedback;
  58      public $incorrectfeedbackformat;
  59  
  60      protected $order = null;
  61  
  62      public function start_attempt(question_attempt_step $step, $variant) {
  63          $this->order = array_keys($this->answers);
  64          if ($this->shuffleanswers) {
  65              shuffle($this->order);
  66          }
  67          $step->set_qt_var('_order', implode(',', $this->order));
  68      }
  69  
  70      public function apply_attempt_state(question_attempt_step $step) {
  71          $this->order = explode(',', $step->get_qt_var('_order'));
  72  
  73          // Add any missing answers. Sometimes people edit questions after they
  74          // have been attempted which breaks things.
  75          foreach ($this->order as $ansid) {
  76              if (isset($this->answers[$ansid])) {
  77                  continue;
  78              }
  79              $a = new stdClass();
  80              $a->id = 0;
  81              $a->answer = html_writer::span(get_string('deletedchoice', 'qtype_multichoice'),
  82                      'notifyproblem');
  83              $a->answerformat = FORMAT_HTML;
  84              $a->fraction = 0;
  85              $a->feedback = '';
  86              $a->feedbackformat = FORMAT_HTML;
  87              $this->answers[$ansid] = $this->qtype->make_answer($a);
  88              $this->answers[$ansid]->answerformat = FORMAT_HTML;
  89          }
  90      }
  91  
  92      public function validate_can_regrade_with_other_version(question_definition $otherversion): ?string {
  93          $basemessage = parent::validate_can_regrade_with_other_version($otherversion);
  94          if ($basemessage) {
  95              return $basemessage;
  96          }
  97  
  98          if (count($this->answers) != count($otherversion->answers)) {
  99              return get_string('regradeissuenumchoiceschanged', 'qtype_multichoice');
 100          }
 101  
 102          return null;
 103      }
 104  
 105      public function update_attempt_state_data_for_new_version(
 106              question_attempt_step $oldstep, question_definition $otherversion) {
 107          $startdata = parent::update_attempt_state_data_for_new_version($oldstep, $otherversion);
 108  
 109          $mapping = array_combine(array_keys($otherversion->answers), array_keys($this->answers));
 110  
 111          $oldorder = explode(',', $oldstep->get_qt_var('_order'));
 112          $neworder = [];
 113          foreach ($oldorder as $oldid) {
 114              $neworder[] = $mapping[$oldid] ?? $oldid;
 115          }
 116          $startdata['_order'] = implode(',', $neworder);
 117  
 118          return $startdata;
 119      }
 120  
 121      public function get_question_summary() {
 122          $question = $this->html_to_text($this->questiontext, $this->questiontextformat);
 123          $choices = array();
 124          foreach ($this->order as $ansid) {
 125              $choices[] = $this->html_to_text($this->answers[$ansid]->answer,
 126                      $this->answers[$ansid]->answerformat);
 127          }
 128          return $question . ': ' . implode('; ', $choices);
 129      }
 130  
 131      public function get_order(question_attempt $qa) {
 132          $this->init_order($qa);
 133          return $this->order;
 134      }
 135  
 136      protected function init_order(question_attempt $qa) {
 137          if (is_null($this->order)) {
 138              $this->order = explode(',', $qa->get_step(0)->get_qt_var('_order'));
 139          }
 140      }
 141  
 142      public abstract function get_response(question_attempt $qa);
 143  
 144      public abstract function is_choice_selected($response, $value);
 145  
 146      public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
 147          if ($component == 'question' && in_array($filearea,
 148                  array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'))) {
 149              return $this->check_combined_feedback_file_access($qa, $options, $filearea, $args);
 150  
 151          } else if ($component == 'question' && $filearea == 'answer') {
 152              $answerid = reset($args); // Itemid is answer id.
 153              return  in_array($answerid, $this->order);
 154  
 155          } else if ($component == 'question' && $filearea == 'answerfeedback') {
 156              $answerid = reset($args); // Itemid is answer id.
 157              $response = $this->get_response($qa);
 158              $isselected = false;
 159              foreach ($this->order as $value => $ansid) {
 160                  if ($ansid == $answerid) {
 161                      $isselected = $this->is_choice_selected($response, $value);
 162                      break;
 163                  }
 164              }
 165              // Param $options->suppresschoicefeedback is a hack specific to the
 166              // oumultiresponse question type. It would be good to refactor to
 167              // avoid refering to it here.
 168              return $options->feedback && empty($options->suppresschoicefeedback) &&
 169                      $isselected;
 170  
 171          } else if ($component == 'question' && $filearea == 'hint') {
 172              return $this->check_hint_file_access($qa, $options, $args);
 173  
 174          } else {
 175              return parent::check_file_access($qa, $options, $component, $filearea,
 176                      $args, $forcedownload);
 177          }
 178      }
 179  
 180      /**
 181       * Return the question settings that define this question as structured data.
 182       *
 183       * @param question_attempt $qa the current attempt for which we are exporting the settings.
 184       * @param question_display_options $options the question display options which say which aspects of the question
 185       * should be visible.
 186       * @return mixed structure representing the question settings. In web services, this will be JSON-encoded.
 187       */
 188      public function get_question_definition_for_external_rendering(question_attempt $qa, question_display_options $options) {
 189          // This is a partial implementation, returning only the most relevant question settings for now,
 190          // ideally, we should return as much as settings as possible (depending on the state and display options).
 191  
 192          return [
 193              'shuffleanswers' => $this->shuffleanswers,
 194              'answernumbering' => $this->answernumbering,
 195              'showstandardinstruction' => $this->showstandardinstruction,
 196              'layout' => $this->layout,
 197          ];
 198      }
 199  }
 200  
 201  
 202  /**
 203   * Represents a multiple choice question where only one choice should be selected.
 204   *
 205   * @copyright  2009 The Open University
 206   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 207   */
 208  class qtype_multichoice_single_question extends qtype_multichoice_base {
 209      public function get_renderer(moodle_page $page) {
 210          return $page->get_renderer('qtype_multichoice', 'single');
 211      }
 212  
 213      public function get_min_fraction() {
 214          $minfraction = 0;
 215          foreach ($this->answers as $ans) {
 216              $minfraction = min($minfraction, $ans->fraction);
 217          }
 218          return $minfraction;
 219      }
 220  
 221      /**
 222       * Return an array of the question type variables that could be submitted
 223       * as part of a question of this type, with their types, so they can be
 224       * properly cleaned.
 225       * @return array variable name => PARAM_... constant.
 226       */
 227      public function get_expected_data() {
 228          return array('answer' => PARAM_INT);
 229      }
 230  
 231      public function summarise_response(array $response) {
 232          if (!$this->is_complete_response($response)) {
 233              return null;
 234          }
 235          $answerid = $this->order[$response['answer']];
 236          return $this->html_to_text($this->answers[$answerid]->answer,
 237                  $this->answers[$answerid]->answerformat);
 238      }
 239  
 240      public function un_summarise_response(string $summary) {
 241          foreach ($this->order as $key => $answerid) {
 242              if ($summary === $this->html_to_text($this->answers[$answerid]->answer,
 243                      $this->answers[$answerid]->answerformat)) {
 244                  return ['answer' => $key];
 245              }
 246          }
 247          return [];
 248      }
 249  
 250      public function classify_response(array $response) {
 251          if (!$this->is_complete_response($response)) {
 252              return array($this->id => question_classified_response::no_response());
 253          }
 254          $choiceid = $this->order[$response['answer']];
 255          $ans = $this->answers[$choiceid];
 256          return array($this->id => new question_classified_response($choiceid,
 257                  $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction));
 258      }
 259  
 260      public function get_correct_response() {
 261          foreach ($this->order as $key => $answerid) {
 262              if (question_state::graded_state_for_fraction(
 263                      $this->answers[$answerid]->fraction)->is_correct()) {
 264                  return array('answer' => $key);
 265              }
 266          }
 267          return array();
 268      }
 269  
 270      public function prepare_simulated_post_data($simulatedresponse) {
 271          $ansid = 0;
 272          foreach ($this->answers as $answer) {
 273              if (clean_param($answer->answer, PARAM_NOTAGS) == $simulatedresponse['answer']) {
 274                  $ansid = $answer->id;
 275              }
 276          }
 277          if ($ansid) {
 278              return array('answer' => array_search($ansid, $this->order));
 279          } else {
 280              return array();
 281          }
 282      }
 283  
 284      public function get_student_response_values_for_simulation($postdata) {
 285          if (!isset($postdata['answer'])) {
 286              return array();
 287          } else {
 288              $answer = $this->answers[$this->order[$postdata['answer']]];
 289              return array('answer' => clean_param($answer->answer, PARAM_NOTAGS));
 290          }
 291      }
 292  
 293      public function is_same_response(array $prevresponse, array $newresponse) {
 294          if (!$this->is_complete_response($prevresponse)) {
 295              $prevresponse = [];
 296          }
 297          if (!$this->is_complete_response($newresponse)) {
 298              $newresponse = [];
 299          }
 300          return question_utils::arrays_same_at_key($prevresponse, $newresponse, 'answer');
 301      }
 302  
 303      public function is_complete_response(array $response) {
 304          return array_key_exists('answer', $response) && $response['answer'] !== ''
 305                  && (string) $response['answer'] !== '-1';
 306      }
 307  
 308      public function is_gradable_response(array $response) {
 309          return $this->is_complete_response($response);
 310      }
 311  
 312      public function grade_response(array $response) {
 313          if (array_key_exists('answer', $response) &&
 314                  array_key_exists($response['answer'], $this->order)) {
 315              $fraction = $this->answers[$this->order[$response['answer']]]->fraction;
 316          } else {
 317              $fraction = 0;
 318          }
 319          return array($fraction, question_state::graded_state_for_fraction($fraction));
 320      }
 321  
 322      public function get_validation_error(array $response) {
 323          if ($this->is_gradable_response($response)) {
 324              return '';
 325          }
 326          return get_string('pleaseselectananswer', 'qtype_multichoice');
 327      }
 328  
 329      public function get_response(question_attempt $qa) {
 330          return $qa->get_last_qt_var('answer', -1);
 331      }
 332  
 333      public function is_choice_selected($response, $value) {
 334          return (string) $response === (string) $value;
 335      }
 336  }
 337  
 338  
 339  /**
 340   * Represents a multiple choice question where multiple choices can be selected.
 341   *
 342   * @copyright  2009 The Open University
 343   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 344   */
 345  class qtype_multichoice_multi_question extends qtype_multichoice_base {
 346      public function get_renderer(moodle_page $page) {
 347          return $page->get_renderer('qtype_multichoice', 'multi');
 348      }
 349  
 350      public function get_min_fraction() {
 351          return 0;
 352      }
 353  
 354      public function clear_wrong_from_response(array $response) {
 355          foreach ($this->order as $key => $ans) {
 356              if (array_key_exists($this->field($key), $response) &&
 357                      question_state::graded_state_for_fraction(
 358                      $this->answers[$ans]->fraction)->is_incorrect()) {
 359                  $response[$this->field($key)] = 0;
 360              }
 361          }
 362          return $response;
 363      }
 364  
 365      public function get_num_parts_right(array $response) {
 366          $numright = 0;
 367          foreach ($this->order as $key => $ans) {
 368              $fieldname = $this->field($key);
 369              if (!array_key_exists($fieldname, $response) || !$response[$fieldname]) {
 370                  continue;
 371              }
 372  
 373              if (!question_state::graded_state_for_fraction(
 374                      $this->answers[$ans]->fraction)->is_incorrect()) {
 375                  $numright += 1;
 376              }
 377          }
 378          return array($numright, count($this->order));
 379      }
 380  
 381      /**
 382       * @param int $key choice number
 383       * @return string the question-type variable name.
 384       */
 385      protected function field($key) {
 386          return 'choice' . $key;
 387      }
 388  
 389      public function get_expected_data() {
 390          $expected = array();
 391          foreach ($this->order as $key => $notused) {
 392              $expected[$this->field($key)] = PARAM_BOOL;
 393          }
 394          return $expected;
 395      }
 396  
 397      public function summarise_response(array $response) {
 398          $selectedchoices = array();
 399          foreach ($this->order as $key => $ans) {
 400              $fieldname = $this->field($key);
 401              if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
 402                  $selectedchoices[] = $this->html_to_text($this->answers[$ans]->answer,
 403                          $this->answers[$ans]->answerformat);
 404              }
 405          }
 406          if (empty($selectedchoices)) {
 407              return null;
 408          }
 409          return implode('; ', $selectedchoices);
 410      }
 411  
 412      public function un_summarise_response(string $summary) {
 413          // This implementation is not perfect. It will fail if an answer contains '; ',
 414          // but this method is only for testing, so it is good enough.
 415          $selectedchoices = explode('; ', $summary);
 416          $response = [];
 417          foreach ($this->order as $key => $answerid) {
 418              if (in_array($this->html_to_text($this->answers[$answerid]->answer,
 419                      $this->answers[$answerid]->answerformat), $selectedchoices)) {
 420                  $response[$this->field($key)] = '1';
 421              }
 422          }
 423          return $response;
 424      }
 425  
 426      public function classify_response(array $response) {
 427          $selectedchoices = array();
 428          foreach ($this->order as $key => $ansid) {
 429              $fieldname = $this->field($key);
 430              if (array_key_exists($fieldname, $response) && $response[$fieldname]) {
 431                  $selectedchoices[$ansid] = 1;
 432              }
 433          }
 434          $choices = array();
 435          foreach ($this->answers as $ansid => $ans) {
 436              if (isset($selectedchoices[$ansid])) {
 437                  $choices[$ansid] = new question_classified_response($ansid,
 438                          $this->html_to_text($ans->answer, $ans->answerformat), $ans->fraction);
 439              }
 440          }
 441          return $choices;
 442      }
 443  
 444      public function get_correct_response() {
 445          $response = array();
 446          foreach ($this->order as $key => $ans) {
 447              if (!question_state::graded_state_for_fraction(
 448                      $this->answers[$ans]->fraction)->is_incorrect()) {
 449                  $response[$this->field($key)] = 1;
 450              }
 451          }
 452          return $response;
 453      }
 454  
 455      public function prepare_simulated_post_data($simulatedresponse) {
 456          $postdata = array();
 457          foreach ($simulatedresponse as $ans => $checked) {
 458              foreach ($this->answers as $ansid => $answer) {
 459                  if (clean_param($answer->answer, PARAM_NOTAGS) == $ans) {
 460                      $fieldno = array_search($ansid, $this->order);
 461                      $postdata[$this->field($fieldno)] = $checked;
 462                      break;
 463                  }
 464              }
 465          }
 466          return $postdata;
 467      }
 468  
 469      public function get_student_response_values_for_simulation($postdata) {
 470          $simulatedresponse = array();
 471          foreach ($this->order as $fieldno => $ansid) {
 472              if (isset($postdata[$this->field($fieldno)])) {
 473                  $checked = $postdata[$this->field($fieldno)];
 474                  $simulatedresponse[clean_param($this->answers[$ansid]->answer, PARAM_NOTAGS)] = $checked;
 475              }
 476          }
 477          ksort($simulatedresponse);
 478          return $simulatedresponse;
 479      }
 480  
 481      public function is_same_response(array $prevresponse, array $newresponse) {
 482          foreach ($this->order as $key => $notused) {
 483              $fieldname = $this->field($key);
 484              if (!question_utils::arrays_same_at_key_integer($prevresponse, $newresponse, $fieldname)) {
 485                  return false;
 486              }
 487          }
 488          return true;
 489      }
 490  
 491      public function is_complete_response(array $response) {
 492          foreach ($this->order as $key => $notused) {
 493              if (!empty($response[$this->field($key)])) {
 494                  return true;
 495              }
 496          }
 497          return false;
 498      }
 499  
 500      public function is_gradable_response(array $response) {
 501          return $this->is_complete_response($response);
 502      }
 503  
 504      /**
 505       * @param array $response responses, as returned by
 506       *      {@link question_attempt_step::get_qt_data()}.
 507       * @return int the number of choices that were selected. in this response.
 508       */
 509      public function get_num_selected_choices(array $response) {
 510          $numselected = 0;
 511          foreach ($response as $key => $value) {
 512              // Response keys starting with _ are internal values like _order, so ignore them.
 513              if (!empty($value) && $key[0] != '_') {
 514                  $numselected += 1;
 515              }
 516          }
 517          return $numselected;
 518      }
 519  
 520      /**
 521       * @return int the number of choices that are correct.
 522       */
 523      public function get_num_correct_choices() {
 524          $numcorrect = 0;
 525          foreach ($this->answers as $ans) {
 526              if (!question_state::graded_state_for_fraction($ans->fraction)->is_incorrect()) {
 527                  $numcorrect += 1;
 528              }
 529          }
 530          return $numcorrect;
 531      }
 532  
 533      public function grade_response(array $response) {
 534          $fraction = 0;
 535          foreach ($this->order as $key => $ansid) {
 536              if (!empty($response[$this->field($key)])) {
 537                  $fraction += $this->answers[$ansid]->fraction;
 538              }
 539          }
 540          $fraction = min(max(0, $fraction), 1.0);
 541          return array($fraction, question_state::graded_state_for_fraction($fraction));
 542      }
 543  
 544      public function get_validation_error(array $response) {
 545          if ($this->is_gradable_response($response)) {
 546              return '';
 547          }
 548          return get_string('pleaseselectatleastoneanswer', 'qtype_multichoice');
 549      }
 550  
 551      /**
 552       * Disable those hint settings that we don't want when the student has selected
 553       * more choices than the number of right choices. This avoids giving the game away.
 554       * @param question_hint_with_parts $hint a hint.
 555       */
 556      protected function disable_hint_settings_when_too_many_selected(
 557              question_hint_with_parts $hint) {
 558          $hint->clearwrong = false;
 559      }
 560  
 561      public function get_hint($hintnumber, question_attempt $qa) {
 562          $hint = parent::get_hint($hintnumber, $qa);
 563          if (is_null($hint)) {
 564              return $hint;
 565          }
 566  
 567          if ($this->get_num_selected_choices($qa->get_last_qt_data()) >
 568                  $this->get_num_correct_choices()) {
 569              $hint = clone($hint);
 570              $this->disable_hint_settings_when_too_many_selected($hint);
 571          }
 572          return $hint;
 573      }
 574  
 575      public function get_response(question_attempt $qa) {
 576          return $qa->get_last_qt_data();
 577      }
 578  
 579      public function is_choice_selected($response, $value) {
 580          return !empty($response['choice' . $value]);
 581      }
 582  }