Typos in comments
[moodle.git] / question / type / calculatedmulti / questiontype.php
CommitLineData
2d279432
PP
1<?php
2
3/////////////////
4// CALCULATED ///
5/////////////////
6
7/// QUESTION TYPE CLASS //////////////////
8
9
10
11class question_calculatedmulti_qtype extends question_calculated_qtype {
12
13 // Used by the function custom_generator_tools:
14 var $calcgenerateidhasbeenadded = false;
15 public $virtualqtype = false;
16
17 function name() {
18 return 'calculatedmulti';
19 }
20
21 function has_wildcards_in_responses($question, $subqid) {
22 return true;
23 }
24
25 function requires_qtypes() {
26 return array('multichoice');
27 }
2d279432 28
2d279432
PP
29
30 function save_question_options($question) {
31 //$options = $question->subtypeoptions;
32 // Get old answers:
33 global $CFG, $DB, $QTYPES ;
34 if (isset($question->answer) && !isset($question->answers)) {
35 $question->answers = $question->answer;
36 }
37 // calculated options
38 $update = true ;
39 $options = $DB->get_record("question_calculated_options", array("question" => $question->id));
40 if (!$options) {
41 $update = false;
42 $options = new stdClass;
43 $options->question = $question->id;
44 }
45 $options->synchronize = $question->synchronize;
2d279432
PP
46 $options->single = $question->single;
47 $options->answernumbering = $question->answernumbering;
48 $options->shuffleanswers = $question->shuffleanswers;
49 $options->correctfeedback = trim($question->correctfeedback);
50 $options->partiallycorrectfeedback = trim($question->partiallycorrectfeedback);
51 $options->incorrectfeedback = trim($question->incorrectfeedback);
52 if ($update) {
53 if (!$DB->update_record("question_calculated_options", $options)) {
54 $result->error = "Could not update calculated question options! (id=$options->id)";
55 return $result;
56 }
57 } else {
58 if (!$DB->insert_record("question_calculated_options", $options)) {
59 $result->error = "Could not insert calculated question options!";
60 return $result;
61 }
62 }
63
64 // Get old versions of the objects
65 if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) {
66 $oldanswers = array();
67 }
68
69 if (!$oldoptions = $DB->get_records('question_calculated', array('question' => $question->id), 'answer ASC')) {
70 $oldoptions = array();
71 }
72
73 // Save the units.
74 $virtualqtype = $this->get_virtual_qtype( $question);
75 // $result = $virtualqtype->save_numerical_units($question);
76 if (isset($result->error)) {
77 return $result;
78 } else {
79 $units = &$result->units;
80 }
81 // Insert all the new answers
82 if (isset($question->answer) && !isset($question->answers)) {
83 $question->answers=$question->answer;
84 }
85 foreach ($question->answers as $key => $dataanswer) {
86 if ( trim($dataanswer) != '' ) {
87 $answer = new stdClass;
88 $answer->question = $question->id;
89 $answer->answer = trim($dataanswer);
90 $answer->fraction = $question->fraction[$key];
91 $answer->feedback = trim($question->feedback[$key]);
92
93 if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it
94 $answer->id = $oldanswer->id;
95 $DB->update_record("question_answers", $answer);
96 } else { // This is a completely new answer
97 $answer->id = $DB->insert_record("question_answers", $answer);
98 }
99
100 // Set up the options object
101 if (!$options = array_shift($oldoptions)) {
102 $options = new stdClass;
103 }
104 $options->question = $question->id;
105 $options->answer = $answer->id;
106 $options->tolerance = trim($question->tolerance[$key]);
107 $options->tolerancetype = trim($question->tolerancetype[$key]);
108 $options->correctanswerlength = trim($question->correctanswerlength[$key]);
109 $options->correctanswerformat = trim($question->correctanswerformat[$key]);
110
111 // Save options
112 if (isset($options->id)) { // reusing existing record
113 $DB->update_record('question_calculated', $options);
114 } else { // new options
115 $DB->insert_record('question_calculated', $options);
116 }
117 }
118 }
119 // delete old answer records
120 if (!empty($oldanswers)) {
121 foreach($oldanswers as $oa) {
122 $DB->delete_records('question_answers', array('id' => $oa->id));
123 }
124 }
125
126 // delete old answer records
127 if (!empty($oldoptions)) {
128 foreach($oldoptions as $oo) {
129 $DB->delete_records('question_calculated', array('id' => $oo->id));
130 }
131 }
132 // $result = $QTYPES['numerical']->save_numerical_options($question);
133 // if (isset($result->error)) {
134 // return $result;
135 // }
136
137
138 if( isset($question->import_process)&&$question->import_process){
139 $this->import_datasets($question);
140 }
141 // Report any problems.
142 if (!empty($result->notice)) {
143 return $result;
144 }
145 return true;
146 }
147
148 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
149 // Find out how many datasets are available
150 global $CFG, $DB, $QTYPES;
151 if(!$maxnumber = (int)$DB->get_field_sql(
152 "SELECT MIN(a.itemcount)
153 FROM {question_dataset_definitions} a,
154 {question_datasets} b
155 WHERE b.question = ?
156 AND a.id = b.datasetdefinition", array($question->id))) {
157 print_error('cannotgetdsforquestion', 'question', '', $question->id);
158 }
159 $sql = "SELECT i.*
160 FROM {question_datasets} d,
161 {question_dataset_definitions} i
162 WHERE d.question = ?
163 AND d.datasetdefinition = i.id
164 AND i.category != 0
165 ";
166 if (!$question->options->synchronize || !$records = $DB->get_records_sql($sql, array($question->id))) {
167 $synchronize_calculated = false ;
168 }else {
169 $synchronize_calculated = true ;
170 }
171
172 // Choose a random dataset
173 if ( $synchronize_calculated === false ) {
174 $state->options->datasetitem = rand(1, $maxnumber);
175 }else{
176 $state->options->datasetitem = intval( $maxnumber * substr($attempt->timestart,-2) /100 ) ;
177 if ($state->options->datasetitem < 1) {
178 $state->options->datasetitem =1 ;
179 } else if ($state->options->datasetitem > $maxnumber){
180 $state->options->datasetitem = $maxnumber ;
181 }
182
183 };
184 $state->options->dataset =
185 $this->pick_question_dataset($question,$state->options->datasetitem);
186 // create an array of answerids ??? why so complicated ???
187 $answerids = array_values(array_map(create_function('$val',
188 'return $val->id;'), $question->options->answers));
189 // Shuffle the answers if required
190 if (!empty($cmoptions->shuffleanswers) and !empty($question->options->shuffleanswers)) {
191 $answerids = swapshuffle($answerids);
192 }
193 $state->options->order = $answerids;
194 // Create empty responses
195 if ($question->options->single) {
196 $state->responses = array('' => '');
197 } else {
198 $state->responses = array();
199 }
200 return true;
201
202 }
203
204 function save_session_and_responses(&$question, &$state) {
205 global $DB;
206 $responses = 'dataset'.$state->options->datasetitem.'-' ;
207 $responses .= implode(',', $state->options->order) . ':';
208 $responses .= implode(',', $state->responses);
209
210 // Set the legacy answer field
211 if (!$DB->set_field('question_states', 'answer', $responses, array('id'=> $state->id))) {
212 return false;
213 }
214 return true;
215 }
216
217 function create_runtime_question($question, $form) {
78a6d0ba 218 $question = default_questiontype::create_runtime_question($question, $form);
2d279432
PP
219 $question->options->answers = array();
220 foreach ($form->answers as $key => $answer) {
221 $a->answer = trim($form->answer[$key]);
222 $a->fraction = $form->fraction[$key];//new
223 $a->tolerance = $form->tolerance[$key];
224 $a->tolerancetype = $form->tolerancetype[$key];
225 $a->correctanswerlength = $form->correctanswerlength[$key];
226 $a->correctanswerformat = $form->correctanswerformat[$key];
227 $question->options->answers[] = clone($a);
228 }
229
230 return $question;
231 }
232
2d279432 233
2d279432 234
2d279432
PP
235
236
2d279432
PP
237 function convert_answers (&$question, &$state){
238 foreach ($question->options->answers as $key => $answer) {
239 $answer->answer = $this->substitute_variables($answer->answer, $state->options->dataset);
240 //evaluate the equations i.e {=5+4)
241 $qtext = "";
242 $qtextremaining = $answer->answer ;
243 // while (preg_match('~\{(=)|%[[:digit]]\.=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
244 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
245
246 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
247 $qtext =$qtext.$qtextsplits[0];
248 $qtextremaining = $qtextsplits[1];
249 if (empty($regs1[1])) {
250 $str = '';
251 } else {
252 if( $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])){
253 $str=$formulaerrors ;
254 }else {
255 eval('$str = '.$regs1[1].';');
256 $texteval= qtype_calculated_calculate_answer(
257 $str, $state->options->dataset, $answer->tolerance,
258 $answer->tolerancetype, $answer->correctanswerlength,
259 $answer->correctanswerformat, '');
260 $str = $texteval->answer;
261 }
262 }
34e24cd3 263 $qtext = $qtext.$str ;
2d279432
PP
264 }
265 $answer->answer = $qtext.$qtextremaining ; ;
266 }
267 }
268
269 function get_default_numerical_unit($question,$virtualqtype){
270 $unit = '';
271 return $unit ;
272 }
273 function grade_responses(&$question, &$state, $cmoptions) {
274 // Forward the grading to the virtual qtype
275 // We modify the question to look like a multichoice question
276 // for grading nothing to do
277/* $numericalquestion = fullclone($question);
278 foreach ($numericalquestion->options->answers as $key => $answer) {
279 $answer = $numericalquestion->options->answers[$key]->answer; // for PHP 4.x
280 $numericalquestion->options->answers[$key]->answer = $this->substitute_variables_and_eval($answer,
281 $state->options->dataset);
282 }*/
283 $virtualqtype = $this->get_virtual_qtype( $question);
284 return $virtualqtype->grade_responses($question, $state, $cmoptions) ;
285 }
286
2d279432 287
2d279432
PP
288
289 // ULPGC ecastro
290 function get_actual_response(&$question, &$state) {
291 // Substitute variables in questiontext before giving the data to the
292 // virtual type
293 $virtualqtype = $this->get_virtual_qtype( $question);
294 $unit = '' ;//$virtualqtype->get_default_numerical_unit($question);
295
296 // We modify the question to look like a multichoice question
297 $numericalquestion = clone($question);
298 $this->convert_answers ($numericalquestion, $state);
299 $this->convert_questiontext ($numericalquestion, $state);
300 /* $numericalquestion->questiontext = $this->substitute_variables_and_eval(
301 $numericalquestion->questiontext, $state->options->dataset);*/
302 $responses = $virtualqtype->get_all_responses($numericalquestion, $state);
303 $response = reset($responses->responses);
304 $correct = $response->answer.' : ';
305
306 $responses = $virtualqtype->get_actual_response($numericalquestion, $state);
307
308 foreach ($responses as $key=>$response){
309 $responses[$key] = $correct.$response;
310 }
311
312 return $responses;
313 }
314
315 function create_virtual_qtype() {
316 global $CFG;
317 require_once("$CFG->dirroot/question/type/multichoice/questiontype.php");
318 return new question_multichoice_qtype();
319 }
320
321
322 function comment_header($question) {
323 //$this->get_question_options($question);
324 $strheader = '';
325 $delimiter = '';
326
327 $answers = $question->options->answers;
328
329 foreach ($answers as $key => $answer) {
330 if (is_string($answer)) {
331 $strheader .= $delimiter.$answer;
332 } else {
333 $strheader .= $delimiter.$answer->answer;
334 }
335 $delimiter = '<br/>';
336 }
337 return $strheader;
338 }
339
340 function comment_on_datasetitems($qtypeobj,$questionid,$questiontext, $answers,$data, $number) { //multichoice_
341 global $DB;
342 $comment = new stdClass;
343 $comment->stranswers = array();
344 $comment->outsidelimit = false ;
345 $comment->answers = array();
346 /// Find a default unit:
347 /* if (!empty($questionid) && $unit = $DB->get_record('question_numerical_units', array('question'=> $questionid, 'multiplier' => 1.0))) {
348 $unit = $unit->unit;
349 } else {
350 $unit = '';
351 }*/
352
353 $answers = fullclone($answers);
354 $strmin = get_string('min', 'quiz');
355 $strmax = get_string('max', 'quiz');
356 $errors = '';
357 $delimiter = ': ';
358 foreach ($answers as $key => $answer) {
359 $answer->answer = $this->substitute_variables($answer->answer, $data);
360 //evaluate the equations i.e {=5+4)
361 $qtext = "";
362 $qtextremaining = $answer->answer ;
363 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
364 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
365 $qtext =$qtext.$qtextsplits[0];
366 $qtextremaining = $qtextsplits[1];
367 if (empty($regs1[1])) {
368 $str = '';
369 } else {
370 if( $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])){
371 $str=$formulaerrors ;
372 }else {
373 eval('$str = '.$regs1[1].';');
374 }
375 }
376 $qtext = $qtext.$str ;
377 }
378 $answer->answer = $qtext.$qtextremaining ; ;
379 $comment->stranswers[$key]= $answer->answer ;
380
381
382 /* $formula = $this->substitute_variables($answer->answer,$data);
383 $formattedanswer = qtype_calculated_calculate_answer(
384 $answer->answer, $data, $answer->tolerance,
385 $answer->tolerancetype, $answer->correctanswerlength,
386 $answer->correctanswerformat, $unit);
387 if ( $formula === '*'){
388 $answer->min = ' ';
389 $formattedanswer->answer = $answer->answer ;
390 }else {
391 eval('$answer->answer = '.$formula.';') ;
392 $virtualqtype->get_tolerance_interval($answer);
393 }
394 if ($answer->min === '') {
395 // This should mean that something is wrong
396 $comment->stranswers[$key] = " $formattedanswer->answer".'<br/><br/>';
397 } else if ($formula === '*'){
398 $comment->stranswers[$key] = $formula.' = '.get_string('anyvalue','qtype_calculated').'<br/><br/><br/>';
399 }else{
400 $comment->stranswers[$key]= $formula.' = '.$formattedanswer->answer.'<br/>' ;
401 $comment->stranswers[$key] .= $strmin. $delimiter.$answer->min.'---';
402 $comment->stranswers[$key] .= $strmax.$delimiter.$answer->max;
403 $comment->stranswers[$key] .='<br/>';
404 $correcttrue->correct = $formattedanswer->answer ;
405 $correcttrue->true = $answer->answer ;
406 if ($formattedanswer->answer < $answer->min || $formattedanswer->answer > $answer->max){
407 $comment->outsidelimit = true ;
408 $comment->answers[$key] = $key;
409 $comment->stranswers[$key] .=get_string('trueansweroutsidelimits','qtype_calculated',$correcttrue);//<span class="error">ERROR True answer '..' outside limits</span>';
410 }else {
411 $comment->stranswers[$key] .=get_string('trueanswerinsidelimits','qtype_calculated',$correcttrue);//' True answer :'.$calculated->trueanswer.' inside limits';
412 }
413 $comment->stranswers[$key] .='';
414 }*/
415 }
416 return fullclone($comment);
417 }
418
419
420
421
422
423 function get_correct_responses1(&$question, &$state) {
424 $virtualqtype = $this->get_virtual_qtype( $question);
425 /* if ($question->options->multichoice != 1 ) {
426 if($unit = $virtualqtype->get_default_numerical_unit($question)){
427 $unit = $unit->unit;
428 } else {
429 $unit = '';
430 }
431 foreach ($question->options->answers as $answer) {
432 if (((int) $answer->fraction) === 1) {
433 $answernumerical = qtype_calculated_calculate_answer(
434 $answer->answer, $state->options->dataset, $answer->tolerance,
435 $answer->tolerancetype, $answer->correctanswerlength,
436 $answer->correctanswerformat, ''); // remove unit
437 $correct = array('' => $answernumerical->answer);
438 $correct['answer']= $correct[''];
439 if (isset($correct['']) && $correct[''] != '*' && $unit ) {
440 $correct[''] .= ' '.$unit;
441 $correct['unit']= $unit;
442 }
443 return $correct;
444 }
445 }
446 }else{**/
447 return $virtualqtype->get_correct_responses($question, $state) ;
448 // }
449 return null;
450 }
451
2d279432
PP
452 function get_virtual_qtype() {
453 global $QTYPES;
454 // if ( isset($question->options->multichoice) && $question->options->multichoice == '1'){
455 $this->virtualqtype =& $QTYPES['multichoice'];
456 // }else {
457 // $this->virtualqtype =& $QTYPES['numerical'];
458 // }
459 return $this->virtualqtype;
460 }
461
462
2d279432
PP
463 /**
464 * Runs all the code required to set up and save an essay question for testing purposes.
465 * Alternate DB table prefix may be used to facilitate data deletion.
466 */
467 function generate_test($name, $courseid = null) {
468 global $DB;
469 list($form, $question) = parent::generate_test($name, $courseid);
470 $form->feedback = 1;
471 $form->multiplier = array(1, 1);
472 $form->shuffleanswers = 1;
473 $form->noanswers = 1;
474 $form->qtype ='calculatedmulti';
475 $question->qtype ='calculatedmulti';
476 $form->answers = array('{a} + {b}');
477 $form->fraction = array(1);
478 $form->tolerance = array(0.01);
479 $form->tolerancetype = array(1);
480 $form->correctanswerlength = array(2);
481 $form->correctanswerformat = array(1);
482 $form->questiontext = "What is {a} + {b}?";
483
484 if ($courseid) {
485 $course = $DB->get_record('course', array('id'=> $courseid));
486 }
487
488 $new_question = $this->save_question($question, $form, $course);
489
490 $dataset_form = new stdClass();
491 $dataset_form->nextpageparam["forceregeneration"]= 1;
492 $dataset_form->calcmin = array(1 => 1.0, 2 => 1.0);
493 $dataset_form->calcmax = array(1 => 10.0, 2 => 10.0);
494 $dataset_form->calclength = array(1 => 1, 2 => 1);
495 $dataset_form->number = array(1 => 5.4 , 2 => 4.9);
496 $dataset_form->itemid = array(1 => '' , 2 => '');
497 $dataset_form->calcdistribution = array(1 => 'uniform', 2 => 'uniform');
498 $dataset_form->definition = array(1 => "1-0-a",
499 2 => "1-0-b");
500 $dataset_form->nextpageparam = array('forceregeneration' => false);
501 $dataset_form->addbutton = 1;
502 $dataset_form->selectadd = 1;
503 $dataset_form->courseid = $courseid;
504 $dataset_form->cmid = 0;
505 $dataset_form->id = $new_question->id;
506 $this->save_dataset_items($new_question, $dataset_form);
507
508 return $new_question;
509 }
510}
511//// END OF CLASS ////
512
513//////////////////////////////////////////////////////////////////////////
514//// INITIATION - Without this line the question type is not in use... ///
515//////////////////////////////////////////////////////////////////////////
516question_register_questiontype(new question_calculatedmulti_qtype());
34e24cd3
PP
517
518if ( ! defined ("CALCULATEDMULTI")) {
519 define("CALCULATEDMULTI", "calculatedmulti");
520}