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