Merge branch 'MDL-38792' of https://github.com/ppichet/moodle
[moodle.git] / question / type / calculated / edit_calculated_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 calculated question type.
19  *
20  * @package    qtype
21  * @subpackage calculated
22  * @copyright  2007 Jamie Pratt me@jamiep.org
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/question/type/numerical/edit_numerical_form.php');
32 /**
33  * Calculated question type editing form definition.
34  *
35  * @copyright  2007 Jamie Pratt me@jamiep.org
36  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37  */
38 class qtype_calculated_edit_form extends qtype_numerical_edit_form {
39     /**
40      * Handle to the question type for this question.
41      *
42      * @var qtype_calculated
43      */
44     public $qtypeobj;
45     public $questiondisplay;
46     public $activecategory;
47     public $categorychanged = false;
48     public $initialname = '';
49     public $reload = false;
51     public function __construct($submiturl, $question, $category, $contexts,
52             $formeditable = true) {
53         global $CFG, $DB;
54         $this->question = $question;
55         $this->reload = optional_param('reload', false, PARAM_BOOL);
57         if (!$this->reload) { // Use database data as this is first pass.
58             if (isset($this->question->id)) {
59                 // Remove prefix #{..}# if exists.
60                 $this->initialname = $question->name;
61                 $regs= array();
62                 if (preg_match('~#\{([^[:space:]]*)#~', $question->name , $regs)) {
63                     $question->name = str_replace($regs[0], '', $question->name);
64                 };
65             }
66         }
67         parent::__construct($submiturl, $question, $category, $contexts, $formeditable);
68     }
70     public function get_per_answer_fields($mform, $label, $gradeoptions,
71             &$repeatedoptions, &$answersoption) {
72         $repeated = parent::get_per_answer_fields($mform, $label, $gradeoptions,
73                 $repeatedoptions, $answersoption);
75         // Reorganise answer options group. 0 is the answer. 1 is tolerance. 2 is Grade.
76         $answeroptions = $repeated[0]->getElements();
77         // Tolerance field will be part of its own group.
78         $tolerance = $answeroptions[1];
80         // Update Answer options group to contain only answer and grade fields.
81         $answeroptions = array($answeroptions[0], $answeroptions[2]);
82         $repeated[0]->setElements($answeroptions);
84         // Update answer field and group label.
85         $repeated[0]->setLabel(get_string('answerformula', 'qtype_calculated', '{no}') . ' =');
86         $answeroptions[0]->setLabel(get_string('answerformula', 'qtype_calculated', '{no}') . ' =');
88         // Get feedback field to re append later.
89         $feedback = array_pop($repeated);
91         // Create tolerance group.
92         $answertolerance = array();
93         $tolerance->setLabel(get_string('tolerance', 'qtype_calculated') . '=');
94         $answertolerance[] = $tolerance;
95         $answertolerance[] = $mform->createElement('select', 'tolerancetype',
96                 get_string('tolerancetype', 'qtype_calculated'), $this->qtypeobj->tolerance_types());
97         $repeated[] = $mform->createElement('group', 'answertolerance',
98                  get_string('tolerance', 'qtype_calculated'), $answertolerance, null, false);
99         $repeatedoptions['tolerance']['default'] = 0.01;
101         // Create display group.
102         $answerdisplay = array();
103         $answerdisplay[] = $mform->createElement('select', 'correctanswerlength',
104                 get_string('answerdisplay', 'qtype_calculated'), range(0, 9));
105         $repeatedoptions['correctanswerlength']['default'] = 2;
107         $answerlengthformats = array(
108             '1' => get_string('decimalformat', 'qtype_numerical'),
109             '2' => get_string('significantfiguresformat', 'qtype_calculated')
110         );
111         $answerdisplay[] = $mform->createElement('select', 'correctanswerformat',
112                 get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
113         $repeated[] = $mform->createElement('group', 'answerdisplay',
114                  get_string('answerdisplay', 'qtype_calculated'), $answerdisplay, null, false);
116         // Add feedback.
117         $repeated[] = $feedback;
119         return $repeated;
120     }
122     /**
123      * Add question-type specific form fields.
124      *
125      * @param MoodleQuickForm $mform the form being built.
126      */
127     protected function definition_inner($mform) {
128         $this->qtypeobj = question_bank::get_qtype($this->qtype());
129         $label = get_string('sharedwildcards', 'qtype_calculated');
130         $mform->addElement('hidden', 'initialcategory', 1);
131         $mform->addElement('hidden', 'reload', 1);
132         $mform->setType('initialcategory', PARAM_INT);
133         $mform->setType('reload', PARAM_BOOL);
134         $html2 = $this->qtypeobj->print_dataset_definitions_category($this->question);
135         $mform->insertElementBefore(
136                 $mform->createElement('static', 'listcategory', $label, $html2), 'name');
137         if (isset($this->question->id)) {
138             $mform->insertElementBefore($mform->createElement('static', 'initialname',
139                     get_string('questionstoredname', 'qtype_calculated'),
140                     $this->initialname), 'name');
141         };
142         $addfieldsname = 'updatecategory';
143         $addstring = get_string('updatecategory', 'qtype_calculated');
144         $mform->registerNoSubmitButton($addfieldsname);
146         $mform->insertElementBefore(
147                 $mform->createElement('submit', $addfieldsname, $addstring), 'listcategory');
148         $mform->registerNoSubmitButton('createoptionbutton');
150         // Editing as regular question.
151         $mform->setType('single', PARAM_INT);
153         $mform->addElement('hidden', 'shuffleanswers', '1');
154         $mform->setType('shuffleanswers', PARAM_INT);
155         $mform->addElement('hidden', 'answernumbering', 'abc');
156         $mform->setType('answernumbering', PARAM_SAFEDIR);
158         $this->add_per_answer_fields($mform, get_string('answerhdr', 'qtype_calculated', '{no}'),
159                 question_bank::fraction_options(), 1, 1);
161         $repeated = array();
163         $this->add_unit_options($mform, $this);
164         $this->add_unit_fields($mform, $this);
165         $this->add_interactive_settings();
167         // Hidden elements.
168         $mform->addElement('hidden', 'synchronize', '');
169         $mform->setType('synchronize', PARAM_INT);
170         $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
171         $mform->setType('wizard', PARAM_ALPHA);
172     }
174     public function data_preprocessing($question) {
175         $question = parent::data_preprocessing($question);
176         $question = $this->data_preprocessing_answers($question);
177         $question = $this->data_preprocessing_hints($question);
178         $question = $this->data_preprocessing_units($question);
179         $question = $this->data_preprocessing_unit_options($question);
181         if (isset($question->options->synchronize)) {
182             $question->synchronize = $question->options->synchronize;
183         }
185         return $question;
186     }
188     protected function data_preprocessing_answers($question, $withanswerfiles = false) {
189         $question = parent::data_preprocessing_answers($question, $withanswerfiles);
190         if (empty($question->options->answers)) {
191             return $question;
192         }
194         $key = 0;
195         foreach ($question->options->answers as $answer) {
196             // See comment in the parent method about this hack.
197             unset($this->_form->_defaultValues["tolerancetype[$key]"]);
198             unset($this->_form->_defaultValues["correctanswerlength[$key]"]);
199             unset($this->_form->_defaultValues["correctanswerformat[$key]"]);
201             $question->tolerancetype[$key]       = $answer->tolerancetype;
202             $question->correctanswerlength[$key] = $answer->correctanswerlength;
203             $question->correctanswerformat[$key] = $answer->correctanswerformat;
204             $key++;
205         }
207         return $question;
208     }
210     public function qtype() {
211         return 'calculated';
212     }
214     public function validation($data, $files) {
216         // Verifying for errors in {=...} in question text.
217         $qtext = "";
218         $qtextremaining = $data['questiontext']['text'];
219         $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
220         foreach ($possibledatasets as $name => $value) {
221             $qtextremaining = str_replace('{'.$name.'}', '1', $qtextremaining);
222         }
223         while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
224             $qtextsplits = explode($regs1[0], $qtextremaining, 2);
225             $qtext = $qtext.$qtextsplits[0];
226             $qtextremaining = $qtextsplits[1];
227             if (!empty($regs1[1]) && $formulaerrors =
228                     qtype_calculated_find_formula_errors($regs1[1])) {
229                 if (!isset($errors['questiontext'])) {
230                     $errors['questiontext'] = $formulaerrors.':'.$regs1[1];
231                 } else {
232                     $errors['questiontext'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
233                 }
234             }
235         }
237         $errors = parent::validation($data, $files);
239         // Check that the answers use datasets.
240         $answers = $data['answer'];
241         $mandatorydatasets = array();
242         foreach ($answers as $key => $answer) {
243             $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
244         }
245         if (empty($mandatorydatasets)) {
246             foreach ($answers as $key => $answer) {
247                 $errors['answeroptions['.$key.']'] =
248                         get_string('atleastonewildcard', 'qtype_calculated');
249             }
250         }
252         // Validate the answer format.
253         foreach ($answers as $key => $answer) {
254             $trimmedanswer = trim($answer);
255             if (trim($answer)) {
256                 if ($data['correctanswerformat'][$key] == 2 &&
257                         $data['correctanswerlength'][$key] == '0') {
258                     $errors['answerdisplay['.$key.']'] =
259                             get_string('zerosignificantfiguresnotallowed', 'qtype_calculated');
260                 }
261             }
262         }
264         return $errors;
265     }
267     protected function is_valid_answer($answer, $data) {
268         return !qtype_calculated_find_formula_errors($answer);
269     }
271     protected function valid_answer_message($answer) {
272         if (!$answer) {
273             return get_string('mustenteraformulaorstar', 'qtype_numerical');
274         } else {
275             return qtype_calculated_find_formula_errors($answer);
276         }
277     }