MDL-15094 fixed stats
[moodle.git] / question / type / numerical / questiontype.php
CommitLineData
1fe641f7 1<?php
2/**
3 * @version $Id$
4 * @author Martin Dougiamas and many others. Tim Hunt.
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
1976496e 6 * @package questionbank
7 * @subpackage questiontypes
1fe641f7 8 *//** */
516cf3eb 9
aaae75b0 10require_once("$CFG->dirroot/question/type/shortanswer/questiontype.php");
516cf3eb 11
1fe641f7 12/**
13 * NUMERICAL QUESTION TYPE CLASS
14 *
15 * This class contains some special features in order to make the
16 * question type embeddable within a multianswer (cloze) question
17 *
18 * This question type behaves like shortanswer in most cases.
19 * Therefore, it extends the shortanswer question type...
1976496e 20 * @package questionbank
21 * @subpackage questiontypes
1fe641f7 22 */
32a189d6 23class question_numerical_qtype extends question_shortanswer_qtype {
516cf3eb 24
25 function name() {
26 return 'numerical';
27 }
28
29 function get_question_options(&$question) {
30 // Get the question answers and their respective tolerances
32a189d6 31 // Note: question_numerical is an extension of the answer table rather than
4f48fb42 32 // the question table as is usually the case for qtype
516cf3eb 33 // specific tables.
34 global $CFG;
35 if (!$question->options->answers = get_records_sql(
36 "SELECT a.*, n.tolerance " .
dc1f00de 37 "FROM {$CFG->prefix}question_answers a, " .
32a189d6 38 " {$CFG->prefix}question_numerical n " .
516cf3eb 39 "WHERE a.question = $question->id " .
026bec73 40 " AND a.id = n.answer " .
41 "ORDER BY a.id ASC")) {
df06c4bb 42 notify('Error: Missing question answer for numerical question ' . $question->id . '!');
516cf3eb 43 return false;
44 }
45 $this->get_numerical_units($question);
46
5a14d563 47 // If units are defined we strip off the default unit from the answer, if
516cf3eb 48 // it is present. (Required for compatibility with the old code and DB).
49 if ($defaultunit = $this->get_default_numerical_unit($question)) {
50 foreach($question->options->answers as $key => $val) {
51 $answer = trim($val->answer);
52 $length = strlen($defaultunit->unit);
1fe641f7 53 if ($length && substr($answer, -$length) == $defaultunit->unit) {
516cf3eb 54 $question->options->answers[$key]->answer =
1fe641f7 55 substr($answer, 0, strlen($answer)-$length);
516cf3eb 56 }
57 }
58 }
59 return true;
60 }
61
62 function get_numerical_units(&$question) {
b4d7d27c 63 if ($units = get_records('question_numerical_units',
516cf3eb 64 'question', $question->id, 'id ASC')) {
3a513ba4 65 $units = array_values($units);
516cf3eb 66 } else {
b4d7d27c 67 $units = array();
516cf3eb 68 }
b4d7d27c 69 foreach ($units as $key => $unit) {
70 $units[$key]->multiplier = clean_param($unit->multiplier, PARAM_NUMBER);
71 }
72 $question->options->units = $units;
516cf3eb 73 return true;
74 }
75
76 function get_default_numerical_unit(&$question) {
ed0ba6da 77 if (isset($question->options->units[0])) {
78 foreach ($question->options->units as $unit) {
79 if (abs($unit->multiplier - 1.0) < '1.0e-' . ini_get('precision')) {
80 return $unit;
516cf3eb 81 }
82 }
83 }
ed0ba6da 84 return false;
516cf3eb 85 }
86
1fe641f7 87 /**
88 * Save the units and the answers associated with this question.
89 */
516cf3eb 90 function save_question_options($question) {
1fe641f7 91
516cf3eb 92 // Get old versions of the objects
a4d79b0e 93 if (!$oldanswers = get_records('question_answers', 'question', $question->id, 'id ASC')) {
516cf3eb 94 $oldanswers = array();
95 }
96
a4d79b0e 97 if (!$oldoptions = get_records('question_numerical', 'question', $question->id, 'answer ASC')) {
516cf3eb 98 $oldoptions = array();
99 }
100
1fe641f7 101 // Save the units.
516cf3eb 102 $result = $this->save_numerical_units($question);
103 if (isset($result->error)) {
104 return $result;
105 } else {
106 $units = &$result->units;
107 }
108
109 // Insert all the new answers
110 foreach ($question->answer as $key => $dataanswer) {
fe881bec 111 if (!isset( $question->deleteanswer[$key] ) && !( trim($dataanswer) == 0 && $question->fraction[$key]== 0 &&trim($question->feedback[$key])=='')) {
516cf3eb 112 $answer = new stdClass;
113 $answer->question = $question->id;
55894a42 114 if (trim($dataanswer) == '*') {
115 $answer->answer = '*';
1fe641f7 116 } else {
117 $answer->answer = $this->apply_unit($dataanswer, $units);
118 if ($answer->answer === false) {
119 $result->notice = get_string('invalidnumericanswer', 'quiz');
120 }
121 }
516cf3eb 122 $answer->fraction = $question->fraction[$key];
123 $answer->feedback = trim($question->feedback[$key]);
124
125 if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it
126 $answer->id = $oldanswer->id;
dc1f00de 127 if (! update_record("question_answers", $answer)) {
516cf3eb 128 $result->error = "Could not update quiz answer! (id=$answer->id)";
129 return $result;
130 }
1fe641f7 131 } else { // This is a completely new answer
dc1f00de 132 if (! $answer->id = insert_record("question_answers", $answer)) {
516cf3eb 133 $result->error = "Could not insert quiz answer!";
134 return $result;
135 }
136 }
137
138 // Set up the options object
139 if (!$options = array_shift($oldoptions)) {
140 $options = new stdClass;
141 }
142 $options->question = $question->id;
143 $options->answer = $answer->id;
1fe641f7 144 if (trim($question->tolerance[$key]) == '') {
145 $options->tolerance = '';
146 } else {
147 $options->tolerance = $this->apply_unit($question->tolerance[$key], $units);
148 if ($options->tolerance === false) {
149 $result->notice = get_string('invalidnumerictolerance', 'quiz');
150 }
151 }
152
516cf3eb 153 // Save options
154 if (isset($options->id)) { // reusing existing record
32a189d6 155 if (! update_record('question_numerical', $options)) {
516cf3eb 156 $result->error = "Could not update quiz numerical options! (id=$options->id)";
157 return $result;
158 }
159 } else { // new options
32a189d6 160 if (! insert_record('question_numerical', $options)) {
516cf3eb 161 $result->error = "Could not insert quiz numerical options!";
162 return $result;
163 }
164 }
1fe641f7 165 }
166 }
167 // delete old answer records
168 if (!empty($oldanswers)) {
169 foreach($oldanswers as $oa) {
170 delete_records('question_answers', 'id', $oa->id);
171 }
172 }
516cf3eb 173
1fe641f7 174 // delete old answer records
175 if (!empty($oldoptions)) {
176 foreach($oldoptions as $oo) {
177 delete_records('question_numerical', 'id', $oo->id);
516cf3eb 178 }
179 }
1fe641f7 180
181 // Report any problems.
182 if (!empty($result->notice)) {
183 return $result;
184 }
185
186 return true;
516cf3eb 187 }
188
189 function save_numerical_units($question) {
ed0ba6da 190 $result = new stdClass;
516cf3eb 191
ed0ba6da 192 // Delete the units previously saved for this question.
193 delete_records('question_numerical_units', 'question', $question->id);
194
195 // Save the new units.
516cf3eb 196 $units = array();
ed0ba6da 197 foreach ($question->multiplier as $i => $multiplier) {
516cf3eb 198 // Discard any unit which doesn't specify the unit or the multiplier
199 if (!empty($question->multiplier[$i]) && !empty($question->unit[$i])) {
ed0ba6da 200 $units[$i] = new stdClass;
516cf3eb 201 $units[$i]->question = $question->id;
1fe641f7 202 $units[$i]->multiplier = $this->apply_unit($question->multiplier[$i], array());
516cf3eb 203 $units[$i]->unit = $question->unit[$i];
ed0ba6da 204 if (! insert_record('question_numerical_units', $units[$i])) {
205 $result->error = 'Unable to save unit ' . $units[$i]->unit . ' to the Databse';
206 return $result;
207 }
516cf3eb 208 }
209 }
210 unset($question->multiplier, $question->unit);
211
516cf3eb 212 $result->units = &$units;
213 return $result;
214 }
215
216 /**
1fe641f7 217 * Deletes question from the question-type specific tables
218 *
219 * @return boolean Success/Failure
220 * @param object $question The question being deleted
221 */
90c3f310 222 function delete_question($questionid) {
223 delete_records("question_numerical", "question", $questionid);
224 delete_records("question_numerical_units", "question", $questionid);
516cf3eb 225 return true;
226 }
227
5a14d563 228 function compare_responses(&$question, $state, $teststate) {
229 if (isset($state->responses['']) && isset($teststate->responses[''])) {
230 return $state->responses[''] == $teststate->responses[''];
231 }
232 return false;
516cf3eb 233 }
234
1fe641f7 235 /**
236 * Checks whether a response matches a given answer, taking the tolerance
237 * and units into account. Returns a true for if a response matches the
238 * answer, false if it doesn't.
239 */
516cf3eb 240 function test_response(&$question, &$state, $answer) {
55894a42 241 // Deal with the match anything answer.
242 if ($answer->answer == '*') {
243 return true;
516cf3eb 244 }
245
1fe641f7 246 $response = $this->apply_unit(stripslashes($state->responses['']), $question->options->units);
247
248 if ($response === false) {
249 return false; // The student did not type a number.
516cf3eb 250 }
1fe641f7 251
252 // The student did type a number, so check it with tolerances.
253 $this->get_tolerance_interval($answer);
254 return ($answer->min <= $response && $response <= $answer->max);
516cf3eb 255 }
256
257 // ULPGC ecastro
258 function check_response(&$question, &$state){
259 $answers = &$question->options->answers;
260 foreach($answers as $aid => $answer) {
261 if($this->test_response($question, $state, $answer)) {
262 return $aid;
263 }
264 }
265 return false;
266 }
267
516cf3eb 268 function get_correct_responses(&$question, &$state) {
269 $correct = parent::get_correct_responses($question, $state);
c85aea03 270 $unit = $this->get_default_numerical_unit($question);
271 if (isset($correct['']) && $correct[''] != '*' && $unit) {
516cf3eb 272 $correct[''] .= ' '.$unit->unit;
273 }
274 return $correct;
275 }
276
277 // ULPGC ecastro
278 function get_all_responses(&$question, &$state) {
1fe641f7 279 $result = new stdClass;
280 $answers = array();
516cf3eb 281 $unit = $this->get_default_numerical_unit($question);
282 if (is_array($question->options->answers)) {
283 foreach ($question->options->answers as $aid=>$answer) {
1fe641f7 284 $r = new stdClass;
516cf3eb 285 $r->answer = $answer->answer;
286 $r->credit = $answer->fraction;
287 $this->get_tolerance_interval($answer);
55894a42 288 if ($r->answer != '*' && $unit) {
289 $r->answer .= ' ' . $unit->unit;
516cf3eb 290 }
291 if ($answer->max != $answer->min) {
292 $max = "$answer->max"; //format_float($answer->max, 2);
293 $min = "$answer->min"; //format_float($answer->max, 2);
294 $r->answer .= ' ('.$min.'..'.$max.')';
295 }
296 $answers[$aid] = $r;
297 }
516cf3eb 298 }
299 $result->id = $question->id;
300 $result->responses = $answers;
301 return $result;
302 }
303
304 function get_tolerance_interval(&$answer) {
305 // No tolerance
306 if (empty($answer->tolerance)) {
1fe641f7 307 $answer->tolerance = 0;
516cf3eb 308 }
309
310 // Calculate the interval of correct responses (min/max)
311 if (!isset($answer->tolerancetype)) {
312 $answer->tolerancetype = 2; // nominal
313 }
314
223ad0b9 315 // We need to add a tiny fraction depending on the set precision to make the
516cf3eb 316 // comparison work correctly. Otherwise seemingly equal values can yield
317 // false. (fixes bug #3225)
223ad0b9 318 $tolerance = (float)$answer->tolerance + ("1.0e-".ini_get('precision'));
516cf3eb 319 switch ($answer->tolerancetype) {
320 case '1': case 'relative':
321 /// Recalculate the tolerance and fall through
322 /// to the nominal case:
323 $tolerance = $answer->answer * $tolerance;
dcd4192a 324 // Do not fall through to the nominal case because the tiny fraction is a factor of the answer
325 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
326 $max = $answer->answer + $tolerance;
327 $min = $answer->answer - $tolerance;
328 break;
516cf3eb 329 case '2': case 'nominal':
330 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
dcd4192a 331 // $answer->tolerance 0 or something else
332 if ((float)$answer->tolerance == 0.0 && abs((float)$answer->answer) <= $tolerance ){
333 $tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction
334 } else if ((float)$answer->tolerance != 0.0 && abs((float)$answer->tolerance) < abs((float)$answer->answer) && abs((float)$answer->answer) <= $tolerance){
335 $tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction
336 }
337
516cf3eb 338 $max = $answer->answer + $tolerance;
339 $min = $answer->answer - $tolerance;
340 break;
ed0ba6da 341 case '3': case 'geometric':
516cf3eb 342 $quotient = 1 + abs($tolerance);
343 $max = $answer->answer * $quotient;
344 $min = $answer->answer / $quotient;
345 break;
346 default:
0b4f4187 347 print_error('unknowntolerance', 'question', '', $answer->tolerancetype);
516cf3eb 348 }
349
350 $answer->min = $min;
351 $answer->max = $max;
352 return true;
353 }
354
355 /**
1fe641f7 356 * Checks if the $rawresponse has a unit and applys it if appropriate.
357 *
358 * @param string $rawresponse The response string to be converted to a float.
359 * @param array $units An array with the defined units, where the
360 * unit is the key and the multiplier the value.
361 * @return float The rawresponse with the unit taken into
362 * account as a float.
363 */
516cf3eb 364 function apply_unit($rawresponse, $units) {
365 // Make units more useful
366 $tmpunits = array();
367 foreach ($units as $unit) {
368 $tmpunits[$unit->unit] = $unit->multiplier;
369 }
1fe641f7 370 // remove spaces and normalise decimal places.
516cf3eb 371 $search = array(' ', ',');
372 $replace = array('', '.');
1fe641f7 373 $rawresponse = str_replace($search, $replace, trim($rawresponse));
374
375 // Apply any unit that is present.
376 if (ereg('^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$',
377 $rawresponse, $responseparts)) {
378
379 if (!empty($responseparts[5])) {
380
381 if (isset($tmpunits[$responseparts[5]])) {
382 // Valid number with unit.
383 return (float)$responseparts[1] / $tmpunits[$responseparts[5]];
384 } else {
385 // Valid number with invalid unit. Must be wrong.
386 return false;
387 }
388
516cf3eb 389 } else {
1fe641f7 390 // Valid number without unit.
516cf3eb 391 return (float)$responseparts[1];
392 }
393 }
1fe641f7 394 // Invalid number. Must be wrong.
395 return false;
516cf3eb 396 }
c5d94c41 397
1fe641f7 398 /// BACKUP FUNCTIONS ////////////////////////////
c5d94c41 399
1fe641f7 400 /**
c5d94c41 401 * Backup the data in the question
402 *
403 * This is used in question/backuplib.php
404 */
405 function backup($bf,$preferences,$question,$level=6) {
406
407 $status = true;
408
a4d79b0e 409 $numericals = get_records('question_numerical', 'question', $question, 'id ASC');
c5d94c41 410 //If there are numericals
411 if ($numericals) {
412 //Iterate over each numerical
413 foreach ($numericals as $numerical) {
414 $status = fwrite ($bf,start_tag("NUMERICAL",$level,true));
415 //Print numerical contents
416 fwrite ($bf,full_tag("ANSWER",$level+1,false,$numerical->answer));
417 fwrite ($bf,full_tag("TOLERANCE",$level+1,false,$numerical->tolerance));
418 //Now backup numerical_units
419 $status = question_backup_numerical_units($bf,$preferences,$question,7);
420 $status = fwrite ($bf,end_tag("NUMERICAL",$level,true));
421 }
422 //Now print question_answers
423 $status = question_backup_answers($bf,$preferences,$question);
424 }
425 return $status;
426 }
427
1fe641f7 428 /// RESTORE FUNCTIONS /////////////////
315559d3 429
1fe641f7 430 /**
315559d3 431 * Restores the data in the question
432 *
433 * This is used in question/restorelib.php
434 */
435 function restore($old_question_id,$new_question_id,$info,$restore) {
9db7dab2 436 global $DB;
315559d3 437
438 $status = true;
439
440 //Get the numerical array
27cabbe6 441 if (isset($info['#']['NUMERICAL'])) {
442 $numericals = $info['#']['NUMERICAL'];
443 } else {
444 $numericals = array();
445 }
315559d3 446
447 //Iterate over numericals
448 for($i = 0; $i < sizeof($numericals); $i++) {
449 $num_info = $numericals[$i];
450
451 //Now, build the question_numerical record structure
1fe641f7 452 $numerical = new stdClass;
315559d3 453 $numerical->question = $new_question_id;
454 $numerical->answer = backup_todb($num_info['#']['ANSWER']['0']['#']);
455 $numerical->tolerance = backup_todb($num_info['#']['TOLERANCE']['0']['#']);
456
55894a42 457 //We have to recode the answer field
315559d3 458 $answer = backup_getid($restore->backup_unique_code,"question_answers",$numerical->answer);
459 if ($answer) {
460 $numerical->answer = $answer->new_id;
461 }
462
463 //The structure is equal to the db, so insert the question_numerical
9db7dab2 464 $newid = $DB->insert_record ("question_numerical", $numerical);
315559d3 465
466 //Do some output
467 if (($i+1) % 50 == 0) {
468 if (!defined('RESTORE_SILENTLY')) {
469 echo ".";
470 if (($i+1) % 1000 == 0) {
471 echo "<br />";
472 }
473 }
474 backup_flush(300);
475 }
476
477 //Now restore numerical_units
478 $status = question_restore_numerical_units ($old_question_id,$new_question_id,$num_info,$restore);
479
480 if (!$newid) {
481 $status = false;
482 }
483 }
484
485 return $status;
486 }
487
516cf3eb 488}
516cf3eb 489
1fe641f7 490// INITIATION - Without this line the question type is not in use.
a2156789 491question_register_questiontype(new question_numerical_qtype());
516cf3eb 492?>