MDL-29691 Improve numerical format in multianswer
[moodle.git] / question / type / multianswer / edit_multianswer_form.php
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/>.
17 /**
18  * Defines the editing form for the multi-answer question type.
19  *
20  * @package    qtype
21  * @subpackage multianswer
22  * @copyright  2007 Jamie Pratt me@jamiep.org
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License
24  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/question/type/numerical/questiontype.php');
32 /**
33  * Form for editing multi-answer questions.
34  *
35  * @copyright  2007 Jamie Pratt me@jamiep.org
36  * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License
37  */
38 class qtype_multianswer_edit_form extends question_edit_form {
40     // The variable $questiondisplay will contain the qtype_multianswer_extract_question from
41     // the questiontext.
42     public $questiondisplay;
43     // The variable $savedquestiondisplay will contain the qtype_multianswer_extract_question
44     // from the questiontext in database.
45     public $savedquestion;
46     public $savedquestiondisplay;
47     public $used_in_quiz = false;
48     public $qtype_change = false;
49     public $negative_diff = 0;
50     public $nb_of_quiz = 0;
51     public $nb_of_attempts = 0;
52     public $confirm = 0;
53     public $reload = false;
54     /** @var qtype_numerical_answer_processor used when validating numerical answers. */
55     protected $ap = null;
58     public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) {
59         global $SESSION, $CFG, $DB;
60         $this->regenerate = true;
61         $this->reload = optional_param('reload', false, PARAM_BOOL);
63         $this->used_in_quiz = false;
65         if (isset($question->id) && $question->id != 0) {
66             $this->savedquestiondisplay = fullclone($question);
67             if ($list = $DB->get_records('quiz_question_instances',
68                     array('question' => $question->id))) {
69                 foreach ($list as $key => $li) {
70                     $this->nb_of_quiz ++;
71                     if ($att = $DB->get_records('quiz_attempts',
72                             array('quiz' => $li->quiz, 'preview' => '0'))) {
73                         $this->nb_of_attempts += count($att);
74                         $this->used_in_quiz = true;
75                     }
76                 }
77             }
78         }
80         parent::__construct($submiturl, $question, $category, $contexts, $formeditable);
81     }
83     protected function definition_inner($mform) {
84         $mform->addElement('hidden', 'reload', 1);
85         $mform->setType('reload', PARAM_INT);
87         // Remove meaningless defaultmark field.
88         $mform->removeElement('defaultmark');
89         $this->confirm = optional_param('confirm', false, PARAM_BOOL);
91         // Make questiontext a required field for this question type.
92         $mform->addRule('questiontext', null, 'required', null, 'client');
94         // Display the questions from questiontext.
95         if ($questiontext = optional_param_array('questiontext', false, PARAM_RAW)) {
96             $this->questiondisplay = fullclone(qtype_multianswer_extract_question($questiontext));
98         } else {
99             if (!$this->reload && !empty($this->savedquestiondisplay->id)) {
100                 // Use database data as this is first pass
101                 // question->id == 0 so no stored datasets.
102                 $this->questiondisplay = fullclone($this->savedquestiondisplay);
103                 foreach ($this->questiondisplay->options->questions as $subquestion) {
104                     if (!empty($subquestion)) {
105                         $subquestion->answer = array('');
106                         foreach ($subquestion->options->answers as $ans) {
107                             $subquestion->answer[] = $ans->answer;
108                         }
109                     }
110                 }
111             } else {
112                 $this->questiondisplay = "";
113             }
114         }
116         if (isset($this->savedquestiondisplay->options->questions) &&
117                 is_array($this->savedquestiondisplay->options->questions)) {
118             $countsavedsubquestions = 0;
119             foreach ($this->savedquestiondisplay->options->questions as $subquestion) {
120                 if (!empty($subquestion)) {
121                     $countsavedsubquestions++;
122                 }
123             }
124         } else {
125             $countsavedsubquestions = 0;
126         }
127         if ($this->reload) {
128             if (isset($this->questiondisplay->options->questions) &&
129                     is_array($this->questiondisplay->options->questions)) {
130                 $countsubquestions = 0;
131                 foreach ($this->questiondisplay->options->questions as $subquestion) {
132                     if (!empty($subquestion)) {
133                         $countsubquestions++;
134                     }
135                 }
136             } else {
137                 $countsubquestions = 0;
138             }
139         } else {
140             $countsubquestions = $countsavedsubquestions;
141         }
143         $mform->addElement('submit', 'analyzequestion',
144                 get_string('decodeverifyquestiontext', 'qtype_multianswer'));
145         $mform->registerNoSubmitButton('analyzequestion');
146         if ($this->reload) {
147             for ($sub = 1; $sub <= $countsubquestions; $sub++) {
149                 if (isset($this->questiondisplay->options->questions[$sub]->qtype)) {
150                     $this->editas[$sub] = $this->questiondisplay->options->questions[$sub]->qtype;
151                 } else {
152                     $this->editas[$sub] = optional_param('sub_'.$sub.'_qtype', 'unknown type', PARAM_PLUGIN);
153                 }
155                 $storemess = '';
156                 if (isset($this->savedquestiondisplay->options->questions[$sub]->qtype) &&
157                         $this->savedquestiondisplay->options->questions[$sub]->qtype !=
158                                 $this->questiondisplay->options->questions[$sub]->qtype) {
159                     $this->qtype_change = true;
160                     $storemess = ' ' . html_writer::tag('span', get_string(
161                             'storedqtype', 'qtype_multianswer', question_bank::get_qtype_name(
162                                     $this->savedquestiondisplay->options->questions[$sub]->qtype)),
163                             array('class' => 'error'));
164                 }
166                 $mform->addElement('header', 'subhdr'.$sub, get_string('questionno', 'question',
167                        '{#'.$sub.'}').'&nbsp;'.question_bank::get_qtype_name(
168                         $this->questiondisplay->options->questions[$sub]->qtype).$storemess);
170                 $mform->addElement('static', 'sub_'.$sub.'_questiontext',
171                         get_string('questiondefinition', 'qtype_multianswer'));
173                 if (isset ($this->questiondisplay->options->questions[$sub]->questiontext)) {
174                     $mform->setDefault('sub_'.$sub.'_questiontext',
175                             $this->questiondisplay->options->questions[$sub]->questiontext['text']);
176                 }
178                 $mform->addElement('static', 'sub_'.$sub.'_defaultmark',
179                         get_string('defaultmark', 'question'));
180                 $mform->setDefault('sub_'.$sub.'_defaultmark',
181                         $this->questiondisplay->options->questions[$sub]->defaultmark);
183                 if ($this->questiondisplay->options->questions[$sub]->qtype == 'shortanswer') {
184                     $mform->addElement('static', 'sub_'.$sub.'_usecase',
185                             get_string('casesensitive', 'qtype_shortanswer'));
186                 }
188                 if ($this->questiondisplay->options->questions[$sub]->qtype == 'multichoice') {
189                     $mform->addElement('static', 'sub_'.$sub.'_layout',
190                             get_string('layout', 'qtype_multianswer'));
191                 }
193                 foreach ($this->questiondisplay->options->questions[$sub]->answer as $key => $ans) {
194                     $mform->addElement('static', 'sub_'.$sub.'_answer['.$key.']',
195                             get_string('answer', 'question'));
197                     if ($this->questiondisplay->options->questions[$sub]->qtype == 'numerical' &&
198                             $key == 0) {
199                         $mform->addElement('static', 'sub_'.$sub.'_tolerance['.$key.']',
200                                 get_string('acceptederror', 'qtype_numerical'));
201                     }
203                     $mform->addElement('static', 'sub_'.$sub.'_fraction['.$key.']',
204                             get_string('grade'));
206                     $mform->addElement('static', 'sub_'.$sub.'_feedback['.$key.']',
207                             get_string('feedback', 'question'));
208                 }
209             }
211             $this->negative_diff = $countsavedsubquestions - $countsubquestions;
212             if (($this->negative_diff > 0) ||$this->qtype_change ||
213                     ($this->used_in_quiz && $this->negative_diff != 0)) {
214                 $mform->addElement('header', 'additemhdr',
215                         get_string('warningquestionmodified', 'qtype_multianswer'));
216             }
217             if ($this->negative_diff > 0) {
218                 $mform->addElement('static', 'alert1', "<strong>".
219                         get_string('questiondeleted', 'qtype_multianswer')."</strong>",
220                         get_string('questionsless', 'qtype_multianswer', $this->negative_diff));
221             }
222             if ($this->qtype_change) {
223                 $mform->addElement('static', 'alert1', "<strong>".
224                         get_string('questiontypechanged', 'qtype_multianswer')."</strong>",
225                         get_string('questiontypechangedcomment', 'qtype_multianswer'));
226             }
227         }
228         if ($this->used_in_quiz) {
229             if ($this->negative_diff < 0) {
230                 $diff = $countsubquestions - $countsavedsubquestions;
231                 $mform->addElement('static', 'alert1', "<strong>".
232                         get_string('questionsadded', 'qtype_multianswer')."</strong>",
233                         "<strong>".get_string('questionsmore', 'qtype_multianswer', $diff).
234                         "</strong>");
235             }
236             $a = new stdClass();
237             $a->nb_of_quiz = $this->nb_of_quiz;
238             $a->nb_of_attempts = $this->nb_of_attempts;
239             $mform->addElement('header', 'additemhdr2',
240                     get_string('questionusedinquiz', 'qtype_multianswer', $a));
241             $mform->addElement('static', 'alertas',
242                     get_string('youshouldnot', 'qtype_multianswer'));
243         }
244         if (($this->negative_diff > 0 || $this->used_in_quiz &&
245                 ($this->negative_diff > 0 || $this->negative_diff < 0 || $this->qtype_change)) &&
246                         $this->reload) {
247             $mform->addElement('header', 'additemhdr',
248                     get_string('questionsaveasedited', 'qtype_multianswer'));
249             $mform->addElement('checkbox', 'confirm', '',
250                     get_string('confirmquestionsaveasedited', 'qtype_multianswer'));
251             $mform->setDefault('confirm', 0);
252         } else {
253             $mform->addElement('hidden', 'confirm', 0);
254         }
256         $this->add_interactive_settings();
257     }
260     public function set_data($question) {
261         global $DB;
262         $default_values = array();
263         if (isset($question->id) and $question->id and $question->qtype &&
264                 $question->questiontext) {
266             foreach ($question->options->questions as $key => $wrapped) {
267                 if (!empty($wrapped)) {
268                     // The old way of restoring the definitions is kept to gradually
269                     // update all multianswer questions.
270                     if (empty($wrapped->questiontext)) {
271                         $parsableanswerdef = '{' . $wrapped->defaultmark . ':';
272                         switch ($wrapped->qtype) {
273                             case 'multichoice':
274                                 $parsableanswerdef .= 'MULTICHOICE:';
275                                 break;
276                             case 'shortanswer':
277                                 $parsableanswerdef .= 'SHORTANSWER:';
278                                 break;
279                             case 'numerical':
280                                 $parsableanswerdef .= 'NUMERICAL:';
281                                 break;
282                             default:
283                                 print_error('unknownquestiontype', 'question', '',
284                                         $wrapped->qtype);
285                         }
286                         $separator = '';
287                         foreach ($wrapped->options->answers as $subanswer) {
288                             $parsableanswerdef .= $separator
289                                 . '%' . round(100*$subanswer->fraction) . '%';
290                             if (is_array($subanswer->answer)) {
291                                 $parsableanswerdef .= $subanswer->answer['text'];
292                             } else {
293                                 $parsableanswerdef .= $subanswer->answer;
294                             }
295                             if (!empty($wrapped->options->tolerance)) {
296                                 // Special for numerical answers.
297                                 $parsableanswerdef .= ":{$wrapped->options->tolerance}";
298                                 // We only want tolerance for the first alternative, it will
299                                 // be applied to all of the alternatives.
300                                 unset($wrapped->options->tolerance);
301                             }
302                             if ($subanswer->feedback) {
303                                 $parsableanswerdef .= "#$subanswer->feedback";
304                             }
305                             $separator = '~';
306                         }
307                         $parsableanswerdef .= '}';
308                         // Fix the questiontext fields of old questions.
309                         $DB->set_field('question', 'questiontext', $parsableanswerdef,
310                                 array('id' => $wrapped->id));
311                     } else {
312                         $parsableanswerdef = str_replace('&#', '&\#', $wrapped->questiontext);
313                     }
314                     $question->questiontext = str_replace("{#$key}", $parsableanswerdef,
315                             $question->questiontext);
316                 }
317             }
318         }
320         // Set default to $questiondisplay questions elements.
321         if ($this->reload) {
322             if (isset($this->questiondisplay->options->questions)) {
323                 $subquestions = fullclone($this->questiondisplay->options->questions);
324                 if (count($subquestions)) {
325                     $sub = 1;
326                     foreach ($subquestions as $subquestion) {
327                         $prefix = 'sub_'.$sub.'_';
329                         // Validate parameters.
330                         $answercount = 0;
331                         $maxgrade = false;
332                         $maxfraction = -1;
333                         if ($subquestion->qtype == 'shortanswer') {
334                             switch ($subquestion->usecase) {
335                                 case '1':
336                                     $default_values[$prefix.'usecase'] =
337                                             get_string('caseyes', 'qtype_shortanswer');
338                                     break;
339                                 case '0':
340                                 default :
341                                     $default_values[$prefix.'usecase'] =
342                                             get_string('caseno', 'qtype_shortanswer');
343                             }
344                         }
346                         if ($subquestion->qtype == 'multichoice') {
347                             $default_values[$prefix.'layout'] = $subquestion->layout;
348                             switch ($subquestion->layout) {
349                                 case '0':
350                                     $default_values[$prefix.'layout'] =
351                                             get_string('layoutselectinline', 'qtype_multianswer');
352                                     break;
353                                 case '1':
354                                     $default_values[$prefix.'layout'] =
355                                             get_string('layoutvertical', 'qtype_multianswer');
356                                     break;
357                                 case '2':
358                                     $default_values[$prefix.'layout'] =
359                                             get_string('layouthorizontal', 'qtype_multianswer');
360                                     break;
361                                 default:
362                                     $default_values[$prefix.'layout'] =
363                                             get_string('layoutundefined', 'qtype_multianswer');
364                             }
365                         }
366                         foreach ($subquestion->answer as $key => $answer) {
367                             if ($subquestion->qtype == 'numerical' && $key == 0) {
368                                 $default_values[$prefix.'tolerance['.$key.']'] =
369                                         $subquestion->tolerance[0];
370                             }
371                             if (is_array($answer)) {
372                                 $answer = $answer['text'];
373                             }
374                             $trimmedanswer = trim($answer);
375                             if ($trimmedanswer !== '') {
376                                 $answercount++;
377                                 if ($subquestion->qtype == 'numerical' &&
378                                         !($this->is_valid_number($trimmedanswer) || $trimmedanswer == '*')) {
379                                     $this->_form->setElementError($prefix.'answer['.$key.']',
380                                             get_string('answermustbenumberorstar',
381                                                     'qtype_numerical'));
382                                 }
383                                 if ($subquestion->fraction[$key] == 1) {
384                                     $maxgrade = true;
385                                 }
386                                 if ($subquestion->fraction[$key] > $maxfraction) {
387                                     $maxfraction = $subquestion->fraction[$key];
388                                 }
389                             }
391                             $default_values[$prefix.'answer['.$key.']'] =
392                                     htmlspecialchars($answer);
393                         }
394                         if ($answercount == 0) {
395                             if ($subquestion->qtype == 'multichoice') {
396                                 $this->_form->setElementError($prefix.'answer[0]',
397                                         get_string('notenoughanswers', 'qtype_multichoice', 2));
398                             } else {
399                                 $this->_form->setElementError($prefix.'answer[0]',
400                                         get_string('notenoughanswers', 'question', 1));
401                             }
402                         }
403                         if ($maxgrade == false) {
404                             $this->_form->setElementError($prefix.'fraction[0]',
405                                     get_string('fractionsnomax', 'question'));
406                         }
407                         foreach ($subquestion->feedback as $key => $answer) {
409                             $default_values[$prefix.'feedback['.$key.']'] =
410                                     htmlspecialchars ($answer['text']);
411                         }
412                         foreach ($subquestion->fraction as $key => $answer) {
413                             $default_values[$prefix.'fraction['.$key.']'] = $answer;
414                         }
416                         $sub++;
417                     }
418                 }
419             }
420         }
421         $default_values['alertas']= "<strong>".get_string('questioninquiz', 'qtype_multianswer').
422                 "</strong>";
424         if ($default_values != "") {
425             $question = (object)((array)$question + $default_values);
426         }
427         $question = $this->data_preprocessing_hints($question);
428         parent::set_data($question);
429     }
431     /**
432      * Validate that a string is a nubmer formatted correctly for the current locale.
433      * @param string $x a string
434      * @return bool whether $x is a number that the numerical question type can interpret.
435      */
436     protected function is_valid_number($x) {
437         if (is_null($this->ap)) {
438             $this->ap = new qtype_numerical_answer_processor(array());
439         }
441         list($value, $unit) = $this->ap->apply_units($x);
443         return !is_null($value) && !$unit;
444     }
447     public function validation($data, $files) {
448         $errors = parent::validation($data, $files);
450         $questiondisplay = qtype_multianswer_extract_question($data['questiontext']);
452         if (isset($questiondisplay->options->questions)) {
453             $subquestions = fullclone($questiondisplay->options->questions);
454             if (count($subquestions)) {
455                 $sub = 1;
456                 foreach ($subquestions as $subquestion) {
457                     $prefix = 'sub_'.$sub.'_';
458                     $answercount = 0;
459                     $maxgrade = false;
460                     $maxfraction = -1;
461                     if (isset($this->savedquestiondisplay->options->questions[$sub]->qtype) &&
462                             $this->savedquestiondisplay->options->questions[$sub]->qtype !=
463                                     $questiondisplay->options->questions[$sub]->qtype) {
464                         $storemess = " STORED QTYPE ".question_bank::get_qtype_name(
465                                 $this->savedquestiondisplay->options->questions[$sub]->qtype);
466                     }
467                     foreach ($subquestion->answer as $key => $answer) {
468                         if (is_array($answer)) {
469                             $answer = $answer['text'];
470                         }
471                         $trimmedanswer = trim($answer);
472                         if ($trimmedanswer !== '') {
473                             $answercount++;
474                             if ($subquestion->qtype == 'numerical' &&
475                                     !($this->is_valid_number($trimmedanswer) || $trimmedanswer == '*')) {
476                                 $errors[$prefix.'answer['.$key.']'] =
477                                         get_string('answermustbenumberorstar', 'qtype_numerical');
478                             }
479                             if ($subquestion->fraction[$key] == 1) {
480                                 $maxgrade = true;
481                             }
482                             if ($subquestion->fraction[$key] > $maxfraction) {
483                                 $maxfraction = $subquestion->fraction[$key];
484                             }
485                         }
486                     }
487                     if ($answercount == 0) {
488                         if ($subquestion->qtype == 'multichoice') {
489                             $errors[$prefix.'answer[0]'] =
490                                     get_string('notenoughanswers', 'qtype_multichoice', 2);
491                         } else {
492                             $errors[$prefix.'answer[0]'] =
493                                     get_string('notenoughanswers', 'question', 1);
494                         }
495                     }
496                     if ($maxgrade == false) {
497                         $errors[$prefix.'fraction[0]'] =
498                                 get_string('fractionsnomax', 'question');
499                     }
500                     $sub++;
501                 }
502             } else {
503                 $errors['questiontext'] = get_string('questionsmissing', 'qtype_multianswer');
504             }
505         }
507         if (($this->negative_diff > 0 || $this->used_in_quiz &&
508                 ($this->negative_diff > 0 || $this->negative_diff < 0 ||
509                         $this->qtype_change)) && !$this->confirm) {
510             $errors['confirm'] =
511                     get_string('confirmsave', 'qtype_multianswer', $this->negative_diff);
512         }
514         return $errors;
515     }
517     public function qtype() {
518         return 'multianswer';
519     }