MDL-15204 Added new files
[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.
f34488b2 34 global $CFG, $DB;
35 if (!$question->options->answers = $DB->get_records_sql(
516cf3eb 36 "SELECT a.*, n.tolerance " .
f34488b2 37 "FROM {question_answers} a, " .
38 " {question_numerical} n " .
39 "WHERE a.question = ? " .
026bec73 40 " AND a.id = n.answer " .
f34488b2 41 "ORDER BY a.id ASC", array($question->id))) {
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) {
f34488b2 63 global $DB;
64 if ($units = $DB->get_records('question_numerical_units', array('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) {
f34488b2 91 global $DB;
516cf3eb 92 // Get old versions of the objects
f34488b2 93 if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) {
516cf3eb 94 $oldanswers = array();
95 }
96
f34488b2 97 if (!$oldoptions = $DB->get_records('question_numerical', array('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) {
f34488b2 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;
f34488b2 127 if (! $DB->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
f34488b2 132 if (! $answer->id = $DB->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 }
f34488b2 152
516cf3eb 153 // Save options
154 if (isset($options->id)) { // reusing existing record
f34488b2 155 if (! $DB->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
f34488b2 160 if (! $DB->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) {
f34488b2 170 $DB->delete_records('question_answers', array('id' => $oa->id));
1fe641f7 171 }
172 }
516cf3eb 173
1fe641f7 174 // delete old answer records
175 if (!empty($oldoptions)) {
176 foreach($oldoptions as $oo) {
f34488b2 177 $DB->delete_records('question_numerical', array('id' => $oo->id));
516cf3eb 178 }
179 }
1fe641f7 180
181 // Report any problems.
182 if (!empty($result->notice)) {
183 return $result;
184 }
f34488b2 185
1fe641f7 186 return true;
516cf3eb 187 }
188
189 function save_numerical_units($question) {
f34488b2 190 global $DB;
ed0ba6da 191 $result = new stdClass;
516cf3eb 192
ed0ba6da 193 // Delete the units previously saved for this question.
f34488b2 194 $DB->delete_records('question_numerical_units', array('question' => $question->id));
ed0ba6da 195
196 // Save the new units.
516cf3eb 197 $units = array();
ed0ba6da 198 foreach ($question->multiplier as $i => $multiplier) {
516cf3eb 199 // Discard any unit which doesn't specify the unit or the multiplier
200 if (!empty($question->multiplier[$i]) && !empty($question->unit[$i])) {
ed0ba6da 201 $units[$i] = new stdClass;
516cf3eb 202 $units[$i]->question = $question->id;
1fe641f7 203 $units[$i]->multiplier = $this->apply_unit($question->multiplier[$i], array());
516cf3eb 204 $units[$i]->unit = $question->unit[$i];
f34488b2 205 if (! $DB->insert_record('question_numerical_units', $units[$i])) {
ed0ba6da 206 $result->error = 'Unable to save unit ' . $units[$i]->unit . ' to the Databse';
207 return $result;
208 }
516cf3eb 209 }
210 }
211 unset($question->multiplier, $question->unit);
212
516cf3eb 213 $result->units = &$units;
214 return $result;
215 }
216
217 /**
1fe641f7 218 * Deletes question from the question-type specific tables
219 *
220 * @return boolean Success/Failure
221 * @param object $question The question being deleted
222 */
90c3f310 223 function delete_question($questionid) {
f34488b2 224 global $DB;
225 $DB->delete_records("question_numerical", array("question" => $questionid));
226 $DB->delete_records("question_numerical_units", array("question" => $questionid));
516cf3eb 227 return true;
228 }
229
5a14d563 230 function compare_responses(&$question, $state, $teststate) {
231 if (isset($state->responses['']) && isset($teststate->responses[''])) {
232 return $state->responses[''] == $teststate->responses[''];
233 }
234 return false;
516cf3eb 235 }
236
1fe641f7 237 /**
238 * Checks whether a response matches a given answer, taking the tolerance
239 * and units into account. Returns a true for if a response matches the
240 * answer, false if it doesn't.
241 */
516cf3eb 242 function test_response(&$question, &$state, $answer) {
55894a42 243 // Deal with the match anything answer.
244 if ($answer->answer == '*') {
245 return true;
516cf3eb 246 }
247
294ce987 248 $response = $this->apply_unit($state->responses[''], $question->options->units);
1fe641f7 249
250 if ($response === false) {
251 return false; // The student did not type a number.
516cf3eb 252 }
1fe641f7 253
254 // The student did type a number, so check it with tolerances.
255 $this->get_tolerance_interval($answer);
256 return ($answer->min <= $response && $response <= $answer->max);
516cf3eb 257 }
258
259 // ULPGC ecastro
260 function check_response(&$question, &$state){
261 $answers = &$question->options->answers;
262 foreach($answers as $aid => $answer) {
263 if($this->test_response($question, $state, $answer)) {
264 return $aid;
265 }
266 }
267 return false;
268 }
269
516cf3eb 270 function get_correct_responses(&$question, &$state) {
271 $correct = parent::get_correct_responses($question, $state);
c85aea03 272 $unit = $this->get_default_numerical_unit($question);
273 if (isset($correct['']) && $correct[''] != '*' && $unit) {
516cf3eb 274 $correct[''] .= ' '.$unit->unit;
275 }
276 return $correct;
277 }
278
279 // ULPGC ecastro
280 function get_all_responses(&$question, &$state) {
1fe641f7 281 $result = new stdClass;
282 $answers = array();
516cf3eb 283 $unit = $this->get_default_numerical_unit($question);
284 if (is_array($question->options->answers)) {
285 foreach ($question->options->answers as $aid=>$answer) {
1fe641f7 286 $r = new stdClass;
516cf3eb 287 $r->answer = $answer->answer;
288 $r->credit = $answer->fraction;
289 $this->get_tolerance_interval($answer);
55894a42 290 if ($r->answer != '*' && $unit) {
291 $r->answer .= ' ' . $unit->unit;
516cf3eb 292 }
293 if ($answer->max != $answer->min) {
294 $max = "$answer->max"; //format_float($answer->max, 2);
295 $min = "$answer->min"; //format_float($answer->max, 2);
296 $r->answer .= ' ('.$min.'..'.$max.')';
297 }
298 $answers[$aid] = $r;
299 }
516cf3eb 300 }
301 $result->id = $question->id;
302 $result->responses = $answers;
303 return $result;
304 }
305
306 function get_tolerance_interval(&$answer) {
307 // No tolerance
308 if (empty($answer->tolerance)) {
1fe641f7 309 $answer->tolerance = 0;
516cf3eb 310 }
311
312 // Calculate the interval of correct responses (min/max)
313 if (!isset($answer->tolerancetype)) {
314 $answer->tolerancetype = 2; // nominal
315 }
316
223ad0b9 317 // We need to add a tiny fraction depending on the set precision to make the
516cf3eb 318 // comparison work correctly. Otherwise seemingly equal values can yield
319 // false. (fixes bug #3225)
223ad0b9 320 $tolerance = (float)$answer->tolerance + ("1.0e-".ini_get('precision'));
516cf3eb 321 switch ($answer->tolerancetype) {
322 case '1': case 'relative':
323 /// Recalculate the tolerance and fall through
324 /// to the nominal case:
325 $tolerance = $answer->answer * $tolerance;
dcd4192a 326 // Do not fall through to the nominal case because the tiny fraction is a factor of the answer
327 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
328 $max = $answer->answer + $tolerance;
329 $min = $answer->answer - $tolerance;
330 break;
516cf3eb 331 case '2': case 'nominal':
332 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
dcd4192a 333 // $answer->tolerance 0 or something else
334 if ((float)$answer->tolerance == 0.0 && abs((float)$answer->answer) <= $tolerance ){
f34488b2 335 $tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction
dcd4192a 336 } else if ((float)$answer->tolerance != 0.0 && abs((float)$answer->tolerance) < abs((float)$answer->answer) && abs((float)$answer->answer) <= $tolerance){
f34488b2 337 $tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction
338 }
339
516cf3eb 340 $max = $answer->answer + $tolerance;
341 $min = $answer->answer - $tolerance;
342 break;
ed0ba6da 343 case '3': case 'geometric':
516cf3eb 344 $quotient = 1 + abs($tolerance);
345 $max = $answer->answer * $quotient;
346 $min = $answer->answer / $quotient;
347 break;
348 default:
0b4f4187 349 print_error('unknowntolerance', 'question', '', $answer->tolerancetype);
516cf3eb 350 }
351
352 $answer->min = $min;
353 $answer->max = $max;
354 return true;
355 }
356
357 /**
1fe641f7 358 * Checks if the $rawresponse has a unit and applys it if appropriate.
359 *
360 * @param string $rawresponse The response string to be converted to a float.
361 * @param array $units An array with the defined units, where the
362 * unit is the key and the multiplier the value.
363 * @return float The rawresponse with the unit taken into
364 * account as a float.
365 */
516cf3eb 366 function apply_unit($rawresponse, $units) {
367 // Make units more useful
368 $tmpunits = array();
369 foreach ($units as $unit) {
370 $tmpunits[$unit->unit] = $unit->multiplier;
371 }
1fe641f7 372 // remove spaces and normalise decimal places.
516cf3eb 373 $search = array(' ', ',');
374 $replace = array('', '.');
1fe641f7 375 $rawresponse = str_replace($search, $replace, trim($rawresponse));
f34488b2 376
1fe641f7 377 // Apply any unit that is present.
378 if (ereg('^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$',
379 $rawresponse, $responseparts)) {
f34488b2 380
1fe641f7 381 if (!empty($responseparts[5])) {
f34488b2 382
1fe641f7 383 if (isset($tmpunits[$responseparts[5]])) {
384 // Valid number with unit.
385 return (float)$responseparts[1] / $tmpunits[$responseparts[5]];
386 } else {
387 // Valid number with invalid unit. Must be wrong.
388 return false;
389 }
390
516cf3eb 391 } else {
1fe641f7 392 // Valid number without unit.
516cf3eb 393 return (float)$responseparts[1];
394 }
395 }
1fe641f7 396 // Invalid number. Must be wrong.
397 return false;
516cf3eb 398 }
f34488b2 399
1fe641f7 400 /// BACKUP FUNCTIONS ////////////////////////////
c5d94c41 401
1fe641f7 402 /**
c5d94c41 403 * Backup the data in the question
404 *
405 * This is used in question/backuplib.php
406 */
407 function backup($bf,$preferences,$question,$level=6) {
f34488b2 408 global $DB;
c5d94c41 409
410 $status = true;
411
f34488b2 412 $numericals = $DB->get_records('question_numerical', array('question' => $question), 'id ASC');
c5d94c41 413 //If there are numericals
414 if ($numericals) {
415 //Iterate over each numerical
416 foreach ($numericals as $numerical) {
417 $status = fwrite ($bf,start_tag("NUMERICAL",$level,true));
418 //Print numerical contents
419 fwrite ($bf,full_tag("ANSWER",$level+1,false,$numerical->answer));
420 fwrite ($bf,full_tag("TOLERANCE",$level+1,false,$numerical->tolerance));
421 //Now backup numerical_units
422 $status = question_backup_numerical_units($bf,$preferences,$question,7);
423 $status = fwrite ($bf,end_tag("NUMERICAL",$level,true));
424 }
425 //Now print question_answers
426 $status = question_backup_answers($bf,$preferences,$question);
427 }
428 return $status;
429 }
430
1fe641f7 431 /// RESTORE FUNCTIONS /////////////////
315559d3 432
1fe641f7 433 /**
315559d3 434 * Restores the data in the question
435 *
436 * This is used in question/restorelib.php
437 */
438 function restore($old_question_id,$new_question_id,$info,$restore) {
9db7dab2 439 global $DB;
315559d3 440
441 $status = true;
442
443 //Get the numerical array
27cabbe6 444 if (isset($info['#']['NUMERICAL'])) {
445 $numericals = $info['#']['NUMERICAL'];
446 } else {
447 $numericals = array();
448 }
315559d3 449
450 //Iterate over numericals
451 for($i = 0; $i < sizeof($numericals); $i++) {
452 $num_info = $numericals[$i];
453
454 //Now, build the question_numerical record structure
1fe641f7 455 $numerical = new stdClass;
315559d3 456 $numerical->question = $new_question_id;
457 $numerical->answer = backup_todb($num_info['#']['ANSWER']['0']['#']);
458 $numerical->tolerance = backup_todb($num_info['#']['TOLERANCE']['0']['#']);
459
55894a42 460 //We have to recode the answer field
315559d3 461 $answer = backup_getid($restore->backup_unique_code,"question_answers",$numerical->answer);
462 if ($answer) {
463 $numerical->answer = $answer->new_id;
464 }
465
466 //The structure is equal to the db, so insert the question_numerical
9db7dab2 467 $newid = $DB->insert_record ("question_numerical", $numerical);
315559d3 468
469 //Do some output
470 if (($i+1) % 50 == 0) {
471 if (!defined('RESTORE_SILENTLY')) {
472 echo ".";
473 if (($i+1) % 1000 == 0) {
474 echo "<br />";
475 }
476 }
477 backup_flush(300);
478 }
479
480 //Now restore numerical_units
481 $status = question_restore_numerical_units ($old_question_id,$new_question_id,$num_info,$restore);
482
483 if (!$newid) {
484 $status = false;
485 }
486 }
487
488 return $status;
489 }
490
516cf3eb 491}
516cf3eb 492
1fe641f7 493// INITIATION - Without this line the question type is not in use.
a2156789 494question_register_questiontype(new question_numerical_qtype());
516cf3eb 495?>