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] [Versions 400 and 402] [Versions 401 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   * Defines the editing form for calculated multiple-choice questions.
  19   *
  20   * @package    qtype
  21   * @subpackage calculatedmulti
  22   * @copyright  2007 Jamie Pratt me@jamiep.org
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  
  30  /**
  31   * Calculated multiple-choice question editing form.
  32   *
  33   * @copyright  2007 Jamie Pratt me@jamiep.org
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class qtype_calculatedmulti_edit_form extends question_edit_form {
  37      /**
  38       * Handle to the question type for this question.
  39       *
  40       * @var question_calculatedmulti_qtype
  41       */
  42      public $qtypeobj;
  43      public $questiondisplay;
  44      public $initialname = '';
  45      public $reload = false;
  46  
  47      public function __construct($submiturl, $question, $category,
  48              $contexts, $formeditable = true) {
  49          $this->question = $question;
  50          $this->qtypeobj = question_bank::get_qtype('calculatedmulti');
  51          $this->reload = optional_param('reload', false, PARAM_BOOL);
  52          if (!$this->reload) {
  53              // Use database data as this is first pass.
  54              if (isset($this->question->id)) {
  55                  // Remove prefix #{..}# if exists.
  56                  $this->initialname = $question->name;
  57                  $question->name = question_bank::get_qtype('calculated')
  58                          ->clean_technical_prefix_from_question_name($question->name);
  59              }
  60          }
  61          parent::__construct($submiturl, $question, $category, $contexts, $formeditable);
  62      }
  63  
  64      protected function can_preview() {
  65          return false; // Generally not possible for calculated multi-choice questions on this page.
  66      }
  67  
  68      public function get_per_answer_fields($mform, $label, $gradeoptions,
  69              &$repeatedoptions, &$answersoption) {
  70          $repeated = array();
  71          $answeroptions = array();
  72          $answeroptions[] = $mform->createElement('text', 'answer',
  73                  $label, array('size' => 50));
  74          $answeroptions[] = $mform->createElement('select', 'fraction',
  75                  get_string('gradenoun'), $gradeoptions);
  76          $repeated[] = $mform->createElement('group', 'answeroptions',
  77                   $label, $answeroptions, null, false);
  78  
  79          // Added answeroptions help button in definition_inner() after called to add_per_answer_fields.
  80  
  81          $repeatedoptions['answer']['type'] = PARAM_RAW;
  82          $repeatedoptions['fraction']['default'] = 0;
  83          $answersoption = 'answers';
  84  
  85          $mform->setType('answer', PARAM_NOTAGS);
  86  
  87          $repeated[] = $mform->createElement('hidden', 'tolerance');
  88          $repeated[] = $mform->createElement('hidden', 'tolerancetype', 1);
  89          $repeatedoptions['tolerance']['type'] = PARAM_FLOAT;
  90          $repeatedoptions['tolerance']['default'] = 0.01;
  91          $repeatedoptions['tolerancetype']['type'] = PARAM_INT;
  92  
  93          // Create display group.
  94          $answerdisplay = array();
  95          $answerdisplay[] =  $mform->createElement('select', 'correctanswerlength',
  96                  get_string('answerdisplay', 'qtype_calculated'), range(0, 9));
  97          $repeatedoptions['correctanswerlength']['default'] = 2;
  98  
  99          $answerlengthformats = array(
 100              '1' => get_string('decimalformat', 'qtype_numerical'),
 101              '2' => get_string('significantfiguresformat', 'qtype_calculated')
 102          );
 103          $answerdisplay[] = $mform->createElement('select', 'correctanswerformat',
 104                  get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
 105          $repeated[] = $mform->createElement('group', 'answerdisplay',
 106                   get_string('answerdisplay', 'qtype_calculated'), $answerdisplay, null, false);
 107  
 108          // Add feedback.
 109          $repeated[] = $mform->createElement('editor', 'feedback',
 110                  get_string('feedback', 'question'), null, $this->editoroptions);
 111  
 112          return $repeated;
 113      }
 114  
 115      protected function definition_inner($mform) {
 116  
 117          $label = get_string('sharedwildcards', 'qtype_calculated');
 118          $mform->addElement('hidden', 'initialcategory', 1);
 119          $mform->addElement('hidden', 'reload', 1);
 120          $mform->setType('initialcategory', PARAM_INT);
 121          $mform->setType('reload', PARAM_BOOL);
 122  
 123          $html2 = '';
 124          $mform->insertElementBefore(
 125                  $mform->createElement('static', 'listcategory', $label, $html2), 'name');
 126          if (isset($this->question->id)) {
 127              $mform->insertElementBefore($mform->createElement('static', 'initialname',
 128                      get_string('questionstoredname', 'qtype_calculated'),
 129                      format_string($this->initialname)), 'name');
 130          };
 131          $addfieldsname = 'updatecategory';
 132          $addstring = get_string('updatecategory', 'qtype_calculated');
 133          $mform->registerNoSubmitButton($addfieldsname);
 134  
 135          $mform->insertElementBefore(
 136                  $mform->createElement('submit', $addfieldsname, $addstring), 'listcategory');
 137          $mform->registerNoSubmitButton('createoptionbutton');
 138          $mform->addElement('hidden', 'multichoice', 1);
 139          $mform->setType('multichoice', PARAM_INT);
 140  
 141          $menu = array(get_string('answersingleno', 'qtype_multichoice'),
 142                  get_string('answersingleyes', 'qtype_multichoice'));
 143          $mform->addElement('select', 'single',
 144                  get_string('answerhowmany', 'qtype_multichoice'), $menu);
 145          $mform->setDefault('single', 1);
 146  
 147          $mform->addElement('advcheckbox', 'shuffleanswers',
 148                  get_string('shuffleanswers', 'qtype_multichoice'), null, null, array(0, 1));
 149          $mform->addHelpButton('shuffleanswers', 'shuffleanswers', 'qtype_multichoice');
 150          $mform->setDefault('shuffleanswers', 1);
 151  
 152          $numberingoptions = question_bank::get_qtype('multichoice')->get_numbering_styles();
 153          $mform->addElement('select', 'answernumbering',
 154                  get_string('answernumbering', 'qtype_multichoice'), $numberingoptions);
 155          $mform->setDefault('answernumbering', 'abc');
 156  
 157          $this->add_per_answer_fields($mform, get_string('choiceno', 'qtype_multichoice', '{no}'),
 158                  question_bank::fraction_options_full(), max(5, QUESTION_NUMANS_START));
 159          $mform->addHelpButton('answeroptions[0]', 'answeroptions', 'qtype_calculatedmulti');
 160  
 161          $repeated = array();
 162          $nounits = optional_param('nounits', 1, PARAM_INT);
 163          $mform->addElement('hidden', 'nounits', $nounits);
 164          $mform->setType('nounits', PARAM_INT);
 165          $mform->setConstants(array('nounits'=>$nounits));
 166          for ($i = 0; $i < $nounits; $i++) {
 167              $mform->addElement('hidden', 'unit'."[{$i}]",
 168                      optional_param("unit[{$i}]", '', PARAM_NOTAGS));
 169              $mform->setType('unit'."[{$i}]", PARAM_NOTAGS);
 170              $mform->addElement('hidden', 'multiplier'."[{$i}]",
 171                      optional_param("multiplier[{$i}]", '', PARAM_FLOAT));
 172              $mform->setType("multiplier[{$i}]", PARAM_FLOAT);
 173          }
 174  
 175          $this->add_combined_feedback_fields(true);
 176          $mform->disabledIf('shownumcorrect', 'single', 'eq', 1);
 177  
 178          $this->add_interactive_settings(true, true);
 179  
 180          // Hidden elements.
 181          $mform->addElement('hidden', 'synchronize', '');
 182          $mform->setType('synchronize', PARAM_INT);
 183          if (isset($this->question->options) && isset($this->question->options->synchronize)) {
 184              $mform->setDefault('synchronize', $this->question->options->synchronize);
 185          } else {
 186              $mform->setDefault('synchronize', 0);
 187          }
 188          $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
 189          $mform->setType('wizard', PARAM_ALPHA);
 190      }
 191  
 192      public function data_preprocessing($question) {
 193          $question = parent::data_preprocessing($question);
 194          $question = $this->data_preprocessing_answers($question, false);
 195          $question = $this->data_preprocessing_combined_feedback($question, true);
 196          $question = $this->data_preprocessing_hints($question, true, true);
 197  
 198          if (isset($question->options)) {
 199              $question->synchronize     = $question->options->synchronize;
 200              $question->single          = $question->options->single;
 201              $question->answernumbering = $question->options->answernumbering;
 202              $question->shuffleanswers  = $question->options->shuffleanswers;
 203          }
 204  
 205          return $question;
 206      }
 207  
 208      protected function data_preprocessing_answers($question, $withanswerfiles = false) {
 209          $question = parent::data_preprocessing_answers($question, $withanswerfiles);
 210          if (empty($question->options->answers)) {
 211              return $question;
 212          }
 213  
 214          $key = 0;
 215          foreach ($question->options->answers as $answer) {
 216              // See comment in the parent method about this hack.
 217              unset($this->_form->_defaultValues["tolerance[{$key}]"]);
 218              unset($this->_form->_defaultValues["tolerancetype[{$key}]"]);
 219              unset($this->_form->_defaultValues["correctanswerlength[{$key}]"]);
 220              unset($this->_form->_defaultValues["correctanswerformat[{$key}]"]);
 221  
 222              $question->tolerance[$key]           = $answer->tolerance;
 223              $question->tolerancetype[$key]       = $answer->tolerancetype;
 224              $question->correctanswerlength[$key] = $answer->correctanswerlength;
 225              $question->correctanswerformat[$key] = $answer->correctanswerformat;
 226              $key++;
 227          }
 228  
 229          return $question;
 230      }
 231  
 232      /**
 233       * Validate the equations in the some question content.
 234       * @param array $errors where errors are being accumulated.
 235       * @param string $field the field being validated.
 236       * @param string $text the content of that field.
 237       * @return array the updated $errors array.
 238       */
 239      protected function validate_text($errors, $field, $text) {
 240          $problems = qtype_calculated_find_formula_errors_in_text($text);
 241          if ($problems) {
 242              $errors[$field] = $problems;
 243          }
 244          return $errors;
 245      }
 246  
 247      public function validation($data, $files) {
 248          $errors = parent::validation($data, $files);
 249  
 250          // Verifying for errors in {=...} in question text.
 251          $errors = $this->validate_text($errors, 'questiontext', $data['questiontext']['text']);
 252          $errors = $this->validate_text($errors, 'generalfeedback', $data['generalfeedback']['text']);
 253          $errors = $this->validate_text($errors, 'correctfeedback', $data['correctfeedback']['text']);
 254          $errors = $this->validate_text($errors, 'partiallycorrectfeedback', $data['partiallycorrectfeedback']['text']);
 255          $errors = $this->validate_text($errors, 'incorrectfeedback', $data['incorrectfeedback']['text']);
 256  
 257          $answers = $data['answer'];
 258          $answercount = 0;
 259          $maxgrade = false;
 260          $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
 261          $mandatorydatasets = array();
 262          foreach ($answers as $key => $answer) {
 263              $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
 264          }
 265          if (count($mandatorydatasets) == 0) {
 266              foreach ($answers as $key => $answer) {
 267                  $errors['answeroptions['.$key.']'] =
 268                          get_string('atleastonewildcard', 'qtype_calculated');
 269              }
 270          }
 271  
 272          $totalfraction = 0;
 273          $maxfraction = -1;
 274          foreach ($answers as $key => $answer) {
 275              $trimmedanswer = trim($answer);
 276              $fraction = (float) $data['fraction'][$key];
 277              if (empty($trimmedanswer) && $trimmedanswer != '0' && empty($fraction)) {
 278                  continue;
 279              }
 280              if (empty($trimmedanswer)) {
 281                  $errors['answeroptions['.$key.']'] = get_string('errgradesetanswerblank', 'qtype_multichoice');
 282              }
 283              if ($trimmedanswer != '' || $answercount == 0) {
 284                  // Verifying for errors in {=...} in answer text.
 285                  $errors = $this->validate_text($errors, 'answeroptions[' . $key . ']', $answer);
 286                  $errors = $this->validate_text($errors, 'feedback[' . $key . ']',
 287                          $data['feedback'][$key]['text']);
 288              }
 289  
 290              if ($trimmedanswer != '') {
 291                  if ('2' == $data['correctanswerformat'][$key] &&
 292                          '0' == $data['correctanswerlength'][$key]) {
 293                      $errors['correctanswerlength['.$key.']'] =
 294                              get_string('zerosignificantfiguresnotallowed', 'qtype_calculated');
 295                  }
 296                  if (!is_numeric($data['tolerance'][$key])) {
 297                      $errors['tolerance['.$key.']'] =
 298                              get_string('xmustbenumeric', 'qtype_numerical',
 299                                  get_string('acceptederror', 'qtype_numerical'));
 300                  }
 301                  if ($data['fraction'][$key] > 0) {
 302                      $totalfraction += $data['fraction'][$key];
 303                  }
 304                  if ($data['fraction'][$key] > $maxfraction) {
 305                      $maxfraction = $data['fraction'][$key];
 306                  }
 307  
 308                  $answercount++;
 309              }
 310          }
 311          if ($answercount == 0) {
 312              $errors['answeroptions[0]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
 313              $errors['answeroptions[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
 314          } else if ($answercount == 1) {
 315              $errors['answeroptions[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
 316  
 317          }
 318          // Perform sanity checks on fractional grades.
 319          if ($data['single']== 1 ) {
 320              if ($maxfraction != 1) {
 321                  $errors['answeroptions[0]'] = get_string('errfractionsnomax', 'qtype_multichoice',
 322                          $maxfraction * 100);
 323              }
 324          } else {
 325              $totalfraction = round($totalfraction, 2);
 326              if ($totalfraction != 1) {
 327                  $totalfraction = $totalfraction * 100;
 328                  $errors['answeroptions[0]'] =
 329                          get_string('errfractionsaddwrong', 'qtype_multichoice', $totalfraction);
 330              }
 331          }
 332          return $errors;
 333      }
 334  
 335      public function qtype() {
 336          return 'calculatedmulti';
 337      }
 338  }