3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @author Martin Dougiamas and many others. Tim Hunt.
20 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
21 * @package questionbank
22 * @subpackage questiontypes
25 require_once("$CFG->dirroot/question/type/shortanswer/questiontype.php");
28 * NUMERICAL QUESTION TYPE CLASS
30 * This class contains some special features in order to make the
31 * question type embeddable within a multianswer (cloze) question
33 * This question type behaves like shortanswer in most cases.
34 * Therefore, it extends the shortanswer question type...
35 * @package questionbank
36 * @subpackage questiontypes
39 class question_numerical_qtype extends question_shortanswer_qtype {
41 public $virtualqtype = false;
46 function has_wildcards_in_responses() {
50 function requires_qtypes() {
51 return array('shortanswer');
54 function get_question_options(&$question) {
55 // Get the question answers and their respective tolerances
56 // Note: question_numerical is an extension of the answer table rather than
57 // the question table as is usually the case for qtype
59 global $CFG, $DB, $OUTPUT;
60 if (!$question->options->answers = $DB->get_records_sql(
61 "SELECT a.*, n.tolerance " .
62 "FROM {question_answers} a, " .
63 " {question_numerical} n " .
64 "WHERE a.question = ? " .
65 " AND a.id = n.answer " .
66 "ORDER BY a.id ASC", array($question->id))) {
67 echo $OUTPUT->notification('Error: Missing question answer for numerical question ' . $question->id . '!');
70 $this->get_numerical_units($question);
71 //get_numerical_options() need to know if there are units
72 // to set correctly default values
73 $this->get_numerical_options($question);
75 // If units are defined we strip off the default unit from the answer, if
76 // it is present. (Required for compatibility with the old code and DB).
77 if ($defaultunit = $this->get_default_numerical_unit($question)) {
78 foreach($question->options->answers as $key => $val) {
79 $answer = trim($val->answer);
80 $length = strlen($defaultunit->unit);
81 if ($length && substr($answer, -$length) == $defaultunit->unit) {
82 $question->options->answers[$key]->answer =
83 substr($answer, 0, strlen($answer)-$length);
90 function get_numerical_units(&$question) {
92 if ($units = $DB->get_records('question_numerical_units', array('question' => $question->id), 'id ASC')) {
93 $units = array_values($units);
97 foreach ($units as $key => $unit) {
98 $units[$key]->multiplier = clean_param($unit->multiplier, PARAM_NUMBER);
100 $question->options->units = $units;
104 function get_default_numerical_unit(&$question) {
105 if (isset($question->options->units[0])) {
106 foreach ($question->options->units as $unit) {
107 if (abs($unit->multiplier - 1.0) < '1.0e-' . ini_get('precision')) {
115 function get_numerical_options(&$question) {
117 if (!$options = $DB->get_record('question_numerical_options', array('question' => $question->id))) {
118 $question->options->unitgradingtype = 0; // total grade
119 $question->options->unitpenalty = 0.1; // default for old questions
121 if ($defaultunit = $this->get_default_numerical_unit($question)) {
122 // so units can be graded
123 $question->options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
125 // only numerical will be graded
126 $question->options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
128 $question->options->unitsleft = 0 ;
129 $question->options->instructions = '';
130 $question->options->instructionsformat = editors_get_preferred_format();
132 $question->options->unitgradingtype = $options->unitgradingtype;
133 $question->options->unitpenalty = $options->unitpenalty;
134 $question->options->showunits = $options->showunits;
135 $question->options->unitsleft = $options->unitsleft;
136 $question->options->instructions = $options->instructions;
137 $question->options->instructionsformat = $options->instructionsformat;
145 * Save the units and the answers associated with this question.
147 function save_question_options($question) {
149 $context = $question->context;
151 // Get old versions of the objects
152 if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) {
153 $oldanswers = array();
156 if (!$oldoptions = $DB->get_records('question_numerical', array('question' => $question->id), 'answer ASC')) {
157 $oldoptions = array();
161 $result = $this->save_numerical_units($question);
162 if (isset($result->error)) {
165 $units = &$result->units;
168 // Insert all the new answers
169 foreach ($question->answer as $key => $dataanswer) {
170 // Check for, and ingore, completely blank answer from the form.
171 if (trim($dataanswer) == '' && $question->fraction[$key] == 0 &&
172 html_is_blank($question->feedback[$key]['text'])) {
176 $answer = new stdClass;
177 $answer->question = $question->id;
178 if (trim($dataanswer) === '*') {
179 $answer->answer = '*';
181 $answer->answer = $this->apply_unit($dataanswer, $units);
182 if ($answer->answer === false) {
183 $result->notice = get_string('invalidnumericanswer', 'quiz');
186 $answer->fraction = $question->fraction[$key];
188 $feedbacktext = trim($question->feedback[$key]['text']);
189 $draftid = $question->feedback[$key]['itemid'];
192 $answer->feedbackformat = $question->feedback[$key]['format'];
194 if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it
195 $feedbacktext = file_save_draft_area_files($draftid, $context->id, 'question', 'answerfeedback', $oldanswer->id, self::$fileoptions, $feedbacktext);
196 $answer->feedback = $feedbacktext;
197 $answer->id = $oldanswer->id;
198 $DB->update_record("question_answers", $answer);
199 } else { // This is a completely new answer
200 $answer->feedback = $feedbacktext;
201 $answer->id = $DB->insert_record("question_answers", $answer);
202 $feedbacktext = file_save_draft_area_files($draftid, $context->id, 'question', 'answerfeedback', $answer->id, self::$fileoptions, $feedbacktext);
203 $DB->set_field('question_answers', 'feedback', $feedbacktext, array('id'=>$answer->id));
206 // Set up the options object
207 if (!$options = array_shift($oldoptions)) {
208 $options = new stdClass;
210 $options->question = $question->id;
211 $options->answer = $answer->id;
212 if (trim($question->tolerance[$key]) == '') {
213 $options->tolerance = '';
215 $options->tolerance = $this->apply_unit($question->tolerance[$key], $units);
216 if ($options->tolerance === false) {
217 $result->notice = get_string('invalidnumerictolerance', 'quiz');
222 if (isset($options->id)) { // reusing existing record
223 $DB->update_record('question_numerical', $options);
224 } else { // new options
225 $DB->insert_record('question_numerical', $options);
228 // delete old answer records
229 if (!empty($oldanswers)) {
230 foreach($oldanswers as $oa) {
231 $DB->delete_records('question_answers', array('id' => $oa->id));
235 // delete old answer records
236 if (!empty($oldoptions)) {
237 foreach($oldoptions as $oo) {
238 $DB->delete_records('question_numerical', array('id' => $oo->id));
241 $result = $this->save_numerical_options($question);
242 if (isset($result->error)) {
245 // Report any problems.
246 if (!empty($result->notice)) {
253 * The numerical options control the display and the grading of the unit
254 * part of the numerical question and related types (calculateds)
255 * Questions previous to 2,0 do not have this table as multianswer questions
256 * in all versions including 2,0. The default values are set to give the same grade
260 function save_numerical_options(&$question) {
262 // echo"<p> ".$question->id."question<pre>";print_r($question) ;echo"</pre></p>";
264 $result = new stdClass;
267 $options = $DB->get_record('question_numerical_options', array('question' => $question->id));
270 $options = new stdClass;
271 $options->question = $question->id;
273 if(isset($question->options->unitgradingtype)){
274 $options->unitgradingtype = $question->options->unitgradingtype;
276 $options->unitgradingtype = 0 ;
278 if(isset($question->unitpenalty)){
279 $options->unitpenalty = $question->unitpenalty;
280 }else { //so this is either an old question or a close question type
281 $options->unitpenalty = 1 ;
283 // if we came from the form then 'unitrole' exists
284 if(isset($question->unitrole)){
285 switch ($question->unitrole){
286 case '0' : $options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
288 case '1' : $options->showunits = NUMERICALQUESTIONUNITTEXTDISPLAY ;
290 case '2' : $options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
291 $options->unitgradingtype = 0 ;
293 case '3' : $options->showunits = $question->multichoicedisplay ;
294 $options->unitgradingtype = $question->unitgradingtypes ;
298 if(isset($question->showunits)){
299 $options->showunits = $question->showunits;
301 if ($defaultunit = $this->get_default_numerical_unit($question)) {
302 // so units can be used
303 $options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
305 // only numerical will be graded
306 $options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
310 if(isset($question->unitsleft)){
311 $options->unitsleft = $question->unitsleft;
313 $options->unitsleft = 0 ;
315 $options->instructionsformat = $question->instructions['format'];
316 if(isset($question->instructions)){
317 $options->instructions = trim($question->instructions['text']);
319 $options->instructions = '' ;
321 $component = 'qtype_' . $question->qtype;
322 $options->instructions = file_save_draft_area_files($question->instructions['itemid'],
323 $question->context->id, // context
324 $component, // component
325 'instruction', // filearea
326 $question->id, // itemid
327 self::$fileoptions, // options
328 $question->instructions['text'] // text
331 $DB->update_record("question_numerical_options", $options);
333 $id = $DB->insert_record("question_numerical_options", $options);
339 function save_numerical_units($question) {
341 $result = new stdClass;
343 // Delete the units previously saved for this question.
344 $DB->delete_records('question_numerical_units', array('question' => $question->id));
347 if (!isset($question->multiplier)) {
348 $result->units = array();
352 // Save the new units.
354 $unitalreadyinsert = array();
355 foreach ($question->multiplier as $i => $multiplier) {
356 // Discard any unit which doesn't specify the unit or the multiplier
357 if (!empty($question->multiplier[$i]) && !empty($question->unit[$i])&& !array_key_exists($question->unit[$i],$unitalreadyinsert)) {
358 $unitalreadyinsert[$question->unit[$i]] = 1 ;
359 $units[$i] = new stdClass;
360 $units[$i]->question = $question->id;
361 $units[$i]->multiplier = $this->apply_unit($question->multiplier[$i], array());
362 $units[$i]->unit = $question->unit[$i];
363 $DB->insert_record('question_numerical_units', $units[$i]);
366 unset($question->multiplier, $question->unit);
368 $result->units = &$units;
372 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
373 $state->responses = array();
374 $state->responses['answer'] = '';
375 $state->responses['unit'] = '';
379 function restore_session_and_responses(&$question, &$state) {
380 if(false === strpos($state->responses[''], '|||||')){
381 $state->responses['answer']= $state->responses[''];
382 $state->responses['unit'] = '';
383 $this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
385 $responses = explode('|||||', $state->responses['']);
386 $state->responses['answer']= $responses[0];
387 $state->responses['unit'] = $responses[1];
393 function find_unit_index(&$question,$value){
396 foreach ($question->options->units as $key => $unit){
397 if($unit->unit ==$value ) {
404 function split_old_answer($rawresponse, $units, &$answer ,&$unit ) {
405 $answer = $rawresponse ;
406 // remove spaces and normalise decimal places.
407 $search = array(' ', ',');
408 $replace = array('', '.');
409 $rawresponse = str_replace($search, $replace, trim($rawresponse));
410 if (preg_match('~^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$~',
411 $rawresponse, $responseparts)) {
412 if(isset($responseparts[5]) ){
413 $unit = $responseparts[5] ;
415 if(isset($responseparts[1]) ){
416 $answer = $responseparts[1] ;
423 function save_session_and_responses(&$question, &$state) {
427 if(isset($state->responses['unit']) && isset($question->options->units[$state->responses['unit']])){
428 $responses = $state->responses['answer'].'|||||'.$question->options->units[$state->responses['unit']]->unit;
429 }else if(isset($state->responses['unit'])){
430 $responses = $state->responses['answer'].'|||||'.$state->responses['unit'] ;
432 $responses = $state->responses['answer'].'|||||';
434 // Set the legacy answer field
435 $DB->set_field('question_states', 'answer', $responses, array('id' => $state->id));
440 * Deletes question from the question-type specific tables
442 * @return boolean Success/Failure
443 * @param object $question The question being deleted
445 function delete_question($questionid) {
447 $DB->delete_records("question_numerical", array("question" => $questionid));
448 $DB->delete_records("question_numerical_options", array("question" => $questionid));
449 $DB->delete_records("question_numerical_units", array("question" => $questionid));
453 * This function has been reinserted in numerical/questiontype.php to simplify
454 * the separate rendering of number and unit
456 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
457 global $CFG, $OUTPUT;
458 //echo"<p> ".$question->id."question->options<pre>";print_r($question->options) ;echo"</pre></p>";
459 //echo"<p> ".$question->id."state<pre>";print_r($state) ;echo"</pre></p>";
461 $context = $this->get_context_by_category_id($question->category);
462 $readonly = empty($options->readonly) ? '' : 'readonly="readonly"';
463 $formatoptions = new stdClass;
464 $formatoptions->noclean = true;
465 $formatoptions->para = false;
466 $nameprefix = $question->name_prefix;
467 $component = 'qtype_' . $question->qtype;
468 // rewrite instructions text
469 $question->options->instructions = quiz_rewrite_question_urls($question->options->instructions, 'pluginfile.php', $context->id, $component, 'instruction', array($state->attempt, $state->question), $question->id);
471 /// Print question text and media
473 $questiontext = format_text($question->questiontext,
474 $question->questiontextformat,
475 $formatoptions, $cmoptions->course);
477 /// Print input controls
478 // as the entry is controlled the question type here is numerical
479 // In all cases there is a text input for the number
480 // If $question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY
481 // there is an additional text input for the unit
482 // If $question->options->showunits == NUMERICALQUESTIONUNITMULTICHOICEDISPLAY"
483 // radio elements display the defined unit
484 // The code allows the input number elememt to be displayed
485 // before i.e. at left or after at rigth of the unit variants.
486 $nameanswer = "name=\"".$question->name_prefix."answer\"";
487 $nameunit = "name=\"".$question->name_prefix."unit\"";
488 // put old answer data in $state->responses['answer'] and $state->responses['unit']
489 if (isset($state->responses['']) && $state->responses[''] != '' && !isset($state->responses['answer'])){
490 $this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
492 // prepare the values of the input elements to be dispalyed answer i.e. number and unit
493 if (isset($state->responses['answer']) && $state->responses['answer']!='') {
494 $valueanswer = ' value="'.s($state->responses['answer']).'" ';
496 $valueanswer = ' value="" ';
498 if (isset($state->responses['unit']) && $state->responses['unit']!='') {
499 $valueunit = ' value="'.s($state->responses['unit']).'" ';
501 $valueunit = ' value="" ';
502 if ($question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY ){
503 $valueunit = ' value="'.s($question->options->units[0]->unit).'" ';
510 $classunitvalue = '' ;
512 $feedbackimgunit = '' ;
513 $answerasterisk = false ;
515 $valid_numerical_unit = false ;
516 $valid_numerical_unit_index = -1 ;
517 $unit_in_numerical_answer = false ;
519 if ($options->feedback) {
520 $class = question_get_feedback_class(0);
521 $classunit = question_get_feedback_class(0);
522 $feedbackimg = question_get_feedback_image(0);
523 $feedbackimgunit = question_get_feedback_image(0);
524 $classunitvalue = 0 ;
525 $valid_numerical_unit_index = -1 ;
526 // if there is unit in answer and unitgradingtype = 0
528 //this is OK for the first answer with a good response
529 // having to test for * so response as long as not empty
530 // $response = $this->extract_numerical_response($state->responses['answer']);
531 // test for a greater than 0 grade
532 foreach($question->options->answers as $answer) {
533 if ($this->test_response($question, $state, $answer)) {
534 // Answer was correct or partially correct.
535 if ( $answer->answer === '*'){
536 $answerasterisk = true ;
539 $class = question_get_feedback_class($answer->fraction);
540 $feedbackimg = question_get_feedback_image($answer->fraction);
541 if ($question->options->unitgradingtype == 0 || ($question->options->unitgradingtype == 0 && $answer->answer === '*')){
542 // if * then unit has the $answer->fraction value
543 // if $question->options->unitgradingtype == 0 everything has been checked
544 // if $question->options->showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
545 // then number - unit combination has been used to test response
546 // so the unit should have same color
547 $classunit = question_get_feedback_class($answer->fraction);
548 $feedbackimgunit = question_get_feedback_image($answer->fraction);
549 $rawgrade = $answer->fraction ;
553 // so we need to apply unit grading i.e. to check if the number-unit combination
555 // on NUMERICALQUESTIONUNITTEXTINPUTDISPLAY we need only to ckeck if applyunit will test OK
556 // with the $state->responses['unit'] value which cannot be empty
557 // if $state->responses['unit']
558 // if apply-unit is true with a specific unit as long as the unit as been written either in the
559 // we need the numerical response and test it with the available units
560 // if the unit used is good then it should be set OK
561 // however the unit could have been put in the number element in this case
562 // the unit penalty should be apllied.
563 // testing apply_unit with no units will get us a false response if there is any text in it
564 // testing apply_unit with a given unit will get a good value if the number is good with this unit
565 // apply unit will return the numerical if
566 // we need to know which conditions let to a good numerical value that were done in the
568 // echo"<p> unit grading > 0 asterisk <pre>";print_r($answer) ;echo"</pre></p>";
569 $valid_numerical_unit = false ;
571 $rawgrade = $answer->fraction ;
572 $valid_numerical_unit_index = -1 ;
573 $invalid_unit_in_numerical_answer = false ;
574 if ( $answerasterisk ) {
575 $classunit = question_get_feedback_class($answer->fraction);
576 $feedbackimgunit = question_get_feedback_image($answer->fraction);
577 $valid_numerical_unit = true ;//everything is true with *
578 //echo"<p> answer asterisk <pre>";print_r($answer) ;echo"</pre></p>";
580 //echo"<p> else after answer asterisk <pre>";print_r($answer) ;echo"</pre></p>";
581 // if( isset($state->responses['unit']) && $state->responses['unit'] != '' ){// unit should be written in the unit input or checked in multichoice
582 // we need to see if something was written in the answer field that was not in the number
583 // although we cannot actually detect units put before the number which will cause bad numerical.
584 // use extract response
585 $response = $this->extract_numerical_response($state->responses['answer']);
586 if(isset($response->unit ) && $response->unit != ''){
587 $unit_in_numerical_answer = true ;
589 $unit_in_numerical_answer = false ;
592 // the we let the testing to the two cases either
593 // NUMERICALQUESTIONUNITTEXTINPUTDISPLAY or
594 // NUMERICALQUESTIONUNITMULTICHOICEDISPLAY
595 if( !isset($state->responses['unit']) || $state->responses['unit'] == '' ){
596 // unit should be written in the unit input or checked in multichoice
597 $valid_numerical_unit = false ;
598 $classunit = question_get_feedback_class(0);
599 $feedbackimgunit = question_get_feedback_image(0);
602 // echo"<p> some unit answer <pre>";print_r($answer) ;echo"</pre></p>";
603 // echo"<p> some unit answer <pre>";print_r($answer) ;echo"</pre></p>";
604 $empty_unit = false ;
605 $valid_numerical_unit = false ;
607 foreach ($question->options->units as $key => $unit) {
608 if ($unit->unit == $state->responses['unit']){
609 // $response = $this->apply_unit($state->responses['answer'].$unit->unit, array($question->options->units[$key])) ;
610 // echo "<p> avant false valid_numerical_unit_index $valid_numerical_unit_index ".$state->responses['answer']."</p>";
611 $invalid_unit_found = 0 ;
612 if ($response->number !== false) {
613 //echo "<p> avanr get valid_numerical_unit_index $valid_numerical_unit_index </p>";
614 // $this->get_tolerance_interval($answer);
615 $testresponse = $response->number /$unit->multiplier ;
616 if($answer->min <= $testresponse && $testresponse <= $answer->max){
617 //echo "<p> apres min max valid_numerical_unit_index $valid_numerical_unit_index </p>";
618 $classunit = question_get_feedback_class($answer->fraction) ; //question_get_feedback_class(1);
619 $feedbackimgunit = question_get_feedback_image($rawgrade);
620 $valid_numerical_unit = true ;
622 $valid_numerical_unit_index = $key ;
630 //echo "<p> apres la boucle valid_numerical_unit $valid_numerical_unit valid_numerical_unit_index $valid_numerical_unit_index </p>";
635 // echo "<p> dans valid_numerical_unit_index $valid_numerical_unit_index </p>";
636 if ($answer->feedback) {
637 $answer->feedback = quiz_rewrite_question_urls($answer->feedback, 'pluginfile.php', $context->id, 'question', 'answerfeedback', array($state->attempt, $state->question), $answer->id);
638 $feedback = format_text($answer->feedback, true, $formatoptions, $cmoptions->course);
647 // echo "<p> rawgrade $rawgrade classunit $classunit valid_numerical_unit_index $valid_numerical_unit_index ".$feedbackimgunit."</p>";
648 $state->options->raw_unitpenalty = 0 ;
649 $raw_unitpenalty = 0 ;
650 if( $question->options->showunits == NUMERICALQUESTIONUNITNODISPLAY ||
651 $question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY ) {
652 $classunitvalue = 1 ;
655 if(! $answerasterisk && $question->options->unitgradingtype != 0 && (! $valid_numerical_unit || $unit_in_numerical_answer)){
656 if($question->options->unitgradingtype == 1){
657 $raw_unitpenalty = $question->options->unitpenalty * $rawgrade ;
659 $raw_unitpenalty = $question->options->unitpenalty * $question->maxgrade;
661 $state->options->raw_unitpenalty = $raw_unitpenalty ;
664 /// Removed correct answer, to be displayed later MDL-7496
665 include("$CFG->dirroot/question/type/numerical/display.html");
669 function compare_responses(&$question, $state, $teststate) {
671 if ($question->options->showunits == NUMERICALQUESTIONUNITMULTICHOICEDISPLAY && isset($question->options->units) && isset($state->responses['unit']) && isset($question->options->units[$state->responses['unit']] )){
672 $state->responses['unit']=$question->options->units[$state->responses['unit']]->unit;
678 if (isset($state->responses['answer'])){
679 $responses = $state->responses['answer'];
681 if (isset($state->responses['unit'])){
682 $responses .= $state->responses['unit'];
684 if (isset($teststate->responses['answer'])){
685 $testresponses = $teststate->responses['answer'];
687 if (isset($teststate->responses['unit'])){
688 $testresponses .= $teststate->responses['unit'];
691 if ( isset($responses) && isset($testresponses )) {
693 return $responses == $testresponses ;
699 * Checks whether a response matches a given answer, taking the tolerance
700 * and but NOT the unit into account. Returns a true for if a response matches the
701 * answer or in one of the unit , false if it doesn't.
702 * the total grading will see if the unit match.
703 * if unit != -1 then the test is done only on this unit
705 function test_response(&$question, &$state, $answer ) {
706 // Deal with the match anything answer.
707 // echo"<p> test_response answer <pre>";print_r($answer) ;echo"</pre></p>";
708 // echo"<p>test_response state <pre>";print_r($state) ;echo"</pre></p>";
709 if ($answer->answer === '*') {
712 // using old grading process if $question->unitgradingtype == 0
713 // and adding unit1 for the new option NUMERICALQUESTIONUNITTEXTDISPLAY
714 if ($question->options->unitgradingtype == 0 ){
715 // values coming form old question stored in attempts
716 if (!isset($state->responses['answer']) && isset($state->responses[''])){
717 $state->responses['answer'] = $state->responses[''];
719 $answertotest = $state->responses['answer'];
720 // values coming from NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
721 // or NUMERICALQUESTIONUNITTEXTDISPLAY as unit hidden HTML element
722 if(isset($state->responses['unit'])) {
723 $answertotest .= $state->responses['unit'] ;
725 // if ($question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY && isset($question->options->units[0])){
726 // $answertotest .= $question->options->units[0]->unit ;
728 // test OK if only numerical or numerical with known unit names with the unit mltiplier applied
729 $response = $this->apply_unit($answertotest, $question->options->units);
730 // echo"<p> dans response apres apply <pre>";print_r($response) ;echo"</pre></p>";
732 if ($response === false) {
733 return false; // The student did not type a number.
736 // The student did type a number, so check it with tolerances.
737 $this->get_tolerance_interval($answer);
738 // echo"<p> test_response apres get tolerance interval answer <pre>";print_r($answer) ;echo"</pre></p>";
739 return ($answer->min <= $response && $response <= $answer->max);
740 }else { // $question->options->unitgradingtype > 0
741 /* testing with unitgradingtype $question->options->unitgradingtype > 0
742 * if the response is at least patially true
743 * if the numerical value agree in the interval
744 * if so the only non valid case will be a bad unit and a unity penalty.
746 To be able to test (old) questions that do not have an unit
747 * input element the test is done using the $state->responses['']
748 * which contains the response which is analyzed by extract_numerical_response()
749 * If the data comes from the numerical or calculated display
750 * the $state->responses['unit'] comes from either
751 * a multichoice radio element NUMERICALQUESTIONUNITMULTICHOICEDISPLAY
752 * where the $state->responses['unit'] value is the key => unit object
753 * in the the $question->options->units array
754 * or an input text element NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
755 * which contains the student response
756 * for NUMERICALQUESTIONUNITTEXTDISPLAY and NUMERICALQUESTIONUNITNODISPLAY
760 $response = $this->extract_numerical_response($state->responses['answer']);
762 // echo"<p> response <pre>";print_r($response) ;echo"</pre></p>";
763 // echo"<p> response <pre>";print_r($response) ;echo"</pre></p>";
765 if ($response->number === false ) {
766 return false; // The student did not type a number.
769 // The student did type a number, so check it with tolerances.
770 $this->get_tolerance_interval($answer);
771 if ($answer->min <= $response->number && $response->number <= $answer->max){
772 // echo"<p> response true <pre>";print_r($response) ;echo"</pre></p>";
775 // testing for other units
776 if ( isset($question->options->units) && count($question->options->units) > 0) {
777 foreach($question->options->units as $key =>$unit){
778 $testresponse = $response->number /$unit->multiplier ;
779 if($answer->min <= $testresponse && $testresponse<= $answer->max) {
790 * Performs response processing and grading
791 * The function was redefined for handling correctly the two parts
792 * number and unit of numerical or calculated questions
793 * The code handles also the case when there no unit defined by the user or
794 * when used in a multianswer (Cloze) question.
795 * This function performs response processing and grading and updates
796 * the state accordingly.
797 * @return boolean Indicates success or failure.
798 * @param object $question The question to be graded. Question type
799 * specific information is included.
800 * @param object $state The state of the question to grade. The current
801 * responses are in ->responses. The last graded state
802 * is in ->last_graded (hence the most recently graded
803 * responses are in ->last_graded->responses). The
804 * question type specific information is also
805 * included. The ->raw_grade and ->penalty fields
806 * must be updated. The method is able to
807 * close the question session (preventing any further
808 * attempts at this question) by setting
809 * $state->event to QUESTION_EVENTCLOSEANDGRADE
810 * @param object $cmoptions
812 function grade_responses(&$question, &$state, $cmoptions) {
813 // echo"<p>grade question->options<pre>";print_r($question->options) ;echo"</pre></p>";
814 // echo"<p>grade state response<pre>";print_r($state->responses) ;echo"</pre></p>";
815 /* if (!isset($state->responses['answer']) && isset($state->responses[''])){
816 $state->responses['answer'] = $state->responses[''];
818 if ( isset($state->responses['']) && $state->responses[''] != '' && !isset($state->responses['answer'])){
819 $this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
822 //to apply the unit penalty we need to analyse the response in a more complex way
823 //the apply_unit() function analysis could be used to obtain the infos
824 // however it is used to detect good or bad numbers but also
825 // gives false if there is a unit
826 $state->raw_grade = 0;
827 $valid_numerical_unit = false ;
831 // $response = $this->extract_numerical_response($state->responses['answer']);
832 $answerasterisk = false ;
835 foreach($question->options->answers as $answer) {
836 if ($this->test_response($question, $state, $answer)) {
837 // Answer was correct or partially correct.
838 $state->raw_grade = $answer->fraction ;
839 if ($question->options->unitgradingtype == 0 || $answer->answer === '*'){
840 // if * then unit has the $answer->fraction value
841 // if $question->options->unitgradingtype == 0 everything has been checked
842 // if $question->options->showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
843 // then number - unit combination has been used to test response
844 // so the unit should have same color
847 // so we need to apply unit grading i.e. to check if the number-unit combination
849 $valid_numerical_unit = false ;
850 $class = question_get_feedback_class($answer->fraction);
851 $feedbackimg = question_get_feedback_image($answer->fraction);
852 if(isset($state->responses['unit']) && $state->responses['unit'] != '' ){
853 foreach ($question->options->units as $key => $unit) {
854 if ($unit->unit == $state->responses['unit']){
856 $response = $this->apply_unit($state->responses['answer'].$state->responses['unit'], array($question->options->units[$key])) ;
857 if ($response !== false) {
858 $this->get_tolerance_interval($answer);
859 if($answer->min <= $response && $response <= $answer->max){
860 $valid_numerical_unit = true ;
871 // apply unit penalty
872 $raw_unitpenalty = 0 ;
873 if($question->options->unitgradingtype != 0 && !empty($question->options->unitpenalty)&& $valid_numerical_unit != true ){
874 if($question->options->unitgradingtype == 1){
875 $raw_unitpenalty = $question->options->unitpenalty * $state->raw_grade ;
877 $raw_unitpenalty = $question->options->unitpenalty * $question->maxgrade;
879 $state->raw_grade -= $raw_unitpenalty ;
882 // Make sure we don't assign negative or too high marks.
883 $state->raw_grade = min(max((float) $state->raw_grade,
884 0.0), 1.0) * $question->maxgrade;
886 // Update the penalty.
887 $state->penalty = $question->penalty * $question->maxgrade;
889 // mark the state as graded
890 $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
896 function get_correct_responses(&$question, &$state) {
897 $correct = parent::get_correct_responses($question, $state);
898 $unit = $this->get_default_numerical_unit($question);
899 if (isset($correct['']) && $correct[''] != '*' && $unit) {
900 $correct[''] .= ' '.$unit->unit;
906 function get_all_responses(&$question, &$state) {
907 $result = new stdClass;
909 $unit = $this->get_default_numerical_unit($question);
910 if (is_array($question->options->answers)) {
911 foreach ($question->options->answers as $aid=>$answer) {
913 $r->answer = $answer->answer;
914 $r->credit = $answer->fraction;
915 $this->get_tolerance_interval($answer);
916 if ($r->answer != '*' && $unit) {
917 $r->answer .= ' ' . $unit->unit;
919 if ($answer->max != $answer->min) {
920 $max = "$answer->max"; //format_float($answer->max, 2);
921 $min = "$answer->min"; //format_float($answer->max, 2);
922 $r->answer .= ' ('.$min.'..'.$max.')';
927 $result->id = $question->id;
928 $result->responses = $answers;
931 function get_actual_response($question, $state) {
932 if (!empty($state->responses) && !empty($state->responses[''])) {
933 if(false === strpos($state->responses[''], '|||||')){
934 $responses[] = $state->responses[''];
936 $resp = explode('|||||', $state->responses['']);
937 $responses[] = $resp[0].$resp[1];
947 function get_tolerance_interval(&$answer) {
949 if (empty($answer->tolerance)) {
950 $answer->tolerance = 0;
953 // Calculate the interval of correct responses (min/max)
954 if (!isset($answer->tolerancetype)) {
955 $answer->tolerancetype = 2; // nominal
958 // We need to add a tiny fraction depending on the set precision to make the
959 // comparison work correctly. Otherwise seemingly equal values can yield
960 // false. (fixes bug #3225)
961 $tolerance = (float)$answer->tolerance + ("1.0e-".ini_get('precision'));
962 switch ($answer->tolerancetype) {
963 case '1': case 'relative':
964 /// Recalculate the tolerance and fall through
965 /// to the nominal case:
966 $tolerance = $answer->answer * $tolerance;
967 // Do not fall through to the nominal case because the tiny fraction is a factor of the answer
968 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
969 $max = $answer->answer + $tolerance;
970 $min = $answer->answer - $tolerance;
972 case '2': case 'nominal':
973 $tolerance = abs($tolerance); // important - otherwise min and max are swapped
974 // $answer->tolerance 0 or something else
975 if ((float)$answer->tolerance == 0.0 && abs((float)$answer->answer) <= $tolerance ){
976 $tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction
977 } else if ((float)$answer->tolerance != 0.0 && abs((float)$answer->tolerance) < abs((float)$answer->answer) && abs((float)$answer->answer) <= $tolerance){
978 $tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction
981 $max = $answer->answer + $tolerance;
982 $min = $answer->answer - $tolerance;
984 case '3': case 'geometric':
985 $quotient = 1 + abs($tolerance);
986 $max = $answer->answer * $quotient;
987 $min = $answer->answer / $quotient;
990 print_error('unknowntolerance', 'question', '', $answer->tolerancetype);
999 * Checks if the $rawresponse has a unit and applys it if appropriate.
1001 * @param string $rawresponse The response string to be converted to a float.
1002 * @param array $units An array with the defined units, where the
1003 * unit is the key and the multiplier the value.
1004 * @return float The rawresponse with the unit taken into
1005 * account as a float.
1007 function extract_numerical_response($rawresponse) {
1008 $extractedresponse = new stdClass() ;
1009 $rawresponse = trim($rawresponse) ;
1010 $search = array(' ', ',');
1011 // test if a . is present or there are multiple , (i.e. 2,456,789 ) so that we don't need spaces and ,
1012 if ( strpos($rawresponse,'.' ) !== false || substr_count($rawresponse,',') > 1 ) {
1013 $replace = array('', '');
1014 }else { // remove spaces and normalise , to a . .
1015 $replace = array('', '.');
1017 $rawresponse = str_replace($search, $replace, $rawresponse);
1019 if (preg_match('~^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$~',
1020 $rawresponse, $responseparts)) {
1021 //return (float)$responseparts[1] ;
1022 $extractedresponse->number = (float)$responseparts[1] ;
1024 $extractedresponse->number = false ;
1026 if (!empty($responseparts[5])) {
1027 $extractedresponse->unit = $responseparts[5] ;
1029 $extractedresponse->unit = '';
1032 // Invalid number. Must be wrong.
1033 return clone($extractedresponse) ;
1036 * Checks if the $rawresponse has a unit and applys it if appropriate.
1038 * @param string $rawresponse The response string to be converted to a float.
1039 * @param array $units An array with the defined units, where the
1040 * unit is the key and the multiplier the value.
1041 * @return float The rawresponse with the unit taken into
1042 * account as a float.
1044 function apply_unit($rawresponse, $units) {
1045 // echo"<p> rawresponse $rawresponse <pre>";print_r($units) ;echo"</pre></p>";
1047 // Make units more useful
1048 $tmpunits = array();
1049 foreach ($units as $unit) {
1050 $tmpunits[$unit->unit] = $unit->multiplier;
1052 // remove spaces and normalise decimal places.
1053 $rawresponse = trim($rawresponse) ;
1054 $search = array(' ', ',');
1055 // test if a . is present or there are multiple , (i.e. 2,456,789 ) so that we don't need spaces and ,
1056 if ( strpos($rawresponse,'.' ) !== false || substr_count($rawresponse,',') > 1 ) {
1057 $replace = array('', '');
1058 }else { // remove spaces and normalise , to a . .
1059 $replace = array('', '.');
1061 $rawresponse = str_replace($search, $replace, $rawresponse);
1064 // Apply any unit that is present.
1065 if (ereg('^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$',
1066 $rawresponse, $responseparts)) {
1067 // echo"<p> responseparts <pre>";print_r($responseparts) ;echo"</pre></p>";
1069 if (!empty($responseparts[5])) {
1071 if (isset($tmpunits[$responseparts[5]])) {
1072 // Valid number with unit.
1073 return (float)$responseparts[1] / $tmpunits[$responseparts[5]];
1075 // Valid number with invalid unit. Must be wrong.
1080 // Valid number without unit.
1081 return (float)$responseparts[1];
1084 // Invalid number. Must be wrong.
1089 * function used in function definition_inner()
1090 * of edit_..._form.php for
1091 * numerical, calculated, calculatedsimple
1093 function add_units_options(&$mform, &$that){
1095 $mform->addElement('header', 'unithandling', get_string('unitshandling', 'qtype_numerical'));
1096 $mform->addElement('radio', 'unitrole', get_string('unitnotused', 'qtype_numerical'), get_string('onlynumerical', 'qtype_numerical'),0);
1097 // $mform->addElement('header', 'unithandling1', get_string('unitnotgraded', 'qtype_numerical'));
1098 $mform->addElement('radio', 'unitrole', get_string('unitdisplay', 'qtype_numerical'), get_string('oneunitshown', 'qtype_numerical'),1);
1099 $mform->addElement('radio', 'unitrole', get_string('unitsused', 'qtype_numerical'), get_string('manynumerical', 'qtype_numerical'),2);
1100 /* $showunits1grp = array();
1101 $showunits1grp[] = & $mform->createElement('radio', 'showunits1', '', get_string('no', 'moodle'),3);
1102 $showunits1grp[] = & $mform->createElement('radio', 'showunits1', '', get_string('yes', 'moodle'),2);*/
1103 // $mform->addGroup($showunits1grp, 'showunits1grp', get_string('unitdisplay', 'qtype_numerical'),' ' , false);
1104 $mform->addElement('static', 'separator2', '', '<HR/>');
1105 $mform->addElement('radio', 'unitrole', get_string('unitgraded1', 'qtype_numerical'), get_string('unitgraded', 'qtype_numerical'),3);
1106 $penaltygrp = array();
1107 $penaltygrp[] =& $mform->createElement('text', 'unitpenalty', get_string('unitpenalty', 'qtype_numerical') ,
1108 array('size' => 6));
1109 $unitgradingtypes = array('1' => get_string('decfractionofquestiongrade', 'qtype_numerical'), '2' => get_string('decfractionofresponsegrade', 'qtype_numerical'));
1110 $penaltygrp[] =& $mform->createElement('select', 'unitgradingtypes', '' , $unitgradingtypes );
1111 $mform->addGroup($penaltygrp, 'penaltygrp', get_string('unitpenalty', 'qtype_numerical'),' ' , false);
1112 $multichoicedisplaygrp = array();
1113 $multichoicedisplaygrp[] =& $mform->createElement('radio', 'multichoicedisplay', get_string('unitedit', 'qtype_numerical'), get_string('editableunittext', 'qtype_numerical'),0);
1114 $multichoicedisplaygrp[] =& $mform->createElement('radio', 'multichoicedisplay', get_string('selectunits', 'qtype_numerical') , get_string('unitchoice', 'qtype_numerical'),1);
1115 $mform->addGroup($multichoicedisplaygrp, 'multichoicedisplaygrp', get_string('studentunitanswer', 'qtype_numerical'),' OR ' , false);
1119 $unitslefts = array('0' => get_string('rightexample', 'qtype_numerical'),'1' => get_string('leftexample', 'qtype_numerical'));
1120 $mform->addElement('select', 'unitsleft', get_string('unitposition', 'qtype_numerical') , $unitslefts );
1122 $mform->addElement('static', 'separator2', '<HR/>', '<HR/>');
1125 $mform->addElement('editor', 'instructions', get_string('instructions', 'qtype_numerical'), null, $that->editoroptions);
1126 // $mform->addElement('static', 'separator1', '<HR/>', '<HR/>');
1127 // Units are not graded
1128 $showunits1grp = array();
1129 $mform->addElement('static', 'separator2', '<HR/>', '<HR/>');
1131 $mform->setType('unitpenalty', PARAM_NUMBER);
1132 $mform->setDefault('unitpenalty', 0.1);
1133 $mform->setDefault('unitgradingtypes', 1);
1134 $mform->addHelpButton('penaltygrp', 'unitpenalty', 'qtype_numerical'); // TODO help did not exist before MDL-21695
1135 // $mform->setDefault('multichoicedisplay', 1);
1136 // $mform->setDefault('showunits1', 3);
1137 $mform->setDefault('unitsleft', 0);
1138 $mform->setType('instructions', PARAM_RAW);
1139 // $mform->addHelpButton('instructions', 'unituses', 'qtype_numerical');
1140 $mform->addHelpButton('instructions', 'numericalinstructions', 'qtype_numerical');
1141 $mform->disabledIf('penaltygrp', 'unitrole','eq','0');
1142 $mform->disabledIf('penaltygrp', 'unitrole','eq','1');
1143 $mform->disabledIf('penaltygrp', 'unitrole','eq','2');
1144 // $mform->disabledIf('unitgradingtype', 'unitrole','eq','1');
1145 // $mform->disabledIf('instructions', 'unitrole','eq','1');
1146 $mform->disabledIf('unitsleft', 'unitrole','eq','0');
1147 // $mform->disabledIf('showunits1','unitrole','eq','0');
1148 $mform->disabledIf('multichoicedisplay','unitrole','eq','0');
1149 $mform->disabledIf('multichoicedisplay','unitrole','eq','1');
1150 $mform->disabledIf('multichoicedisplay','unitrole','eq','2');
1156 * function used in in function definition_inner()
1157 * of edit_..._form.php for
1158 * numerical, calculated, calculatedsimple
1160 function add_units_elements(& $mform,& $that) {
1161 $repeated = array();
1162 $repeated[] =& $mform->createElement('header', 'unithdr', get_string('unithdr', 'qtype_numerical', '{no}'));
1164 $repeated[] =& $mform->createElement('text', 'unit', get_string('unit', 'quiz'));
1165 $mform->setType('unit', PARAM_NOTAGS);
1167 $repeated[] =& $mform->createElement('text', 'multiplier', get_string('multiplier', 'quiz'));
1168 $mform->setType('multiplier', PARAM_NUMBER);
1170 if (isset($that->question->options)){
1171 $countunits = count($that->question->options->units);
1175 if ($that->question->formoptions->repeatelements){
1176 $repeatsatstart = $countunits + 1;
1178 $repeatsatstart = $countunits;
1180 $that->repeat_elements($repeated, $repeatsatstart, array(), 'nounits', 'addunits', 2, get_string('addmoreunitblanks', 'qtype_calculated', '{no}'));
1182 if ($mform->elementExists('multiplier[0]')){
1183 $firstunit =& $mform->getElement('multiplier[0]');
1184 $firstunit->freeze();
1185 $firstunit->setValue('1.0');
1186 $firstunit->setPersistantFreeze(true);
1187 $mform->addHelpButton('multiplier[0]', 'numericalmultiplier', 'qtype_numerical');
1192 * function used in in function data_preprocessing() of edit_numerical_form.php for
1193 * numerical, calculated, calculatedsimple
1195 function set_numerical_unit_data($mform, &$question, &$default_values){
1197 list($categoryid) = explode(',', $question->category);
1198 $context = $this->get_context_by_category_id($categoryid);
1200 if (isset($question->options)){
1201 $default_values['unitgradingtypes'] = 1 ;
1202 if ($question->options->unitgradingtype == 2 ) {
1203 $default_values['unitgradingtypes'] = 1 ;
1205 if ($question->options->unitgradingtype == 0 ) {
1206 $default_values['unitgradingtypes'] = 0 ;
1208 $default_values['unitpenalty'] = $question->options->unitpenalty ;
1209 switch ($question->options->showunits){
1210 case 0 :// NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
1211 if($question->options->unitgradingtype == 0 ){
1212 $default_values['unitrole'] = 2 ;
1213 $default_values['multichoicedisplay'] = 0 ;
1215 $default_values['unitrole'] = 3 ;
1216 $default_values['multichoicedisplay'] = 0 ;
1217 $default_values['unitgradingtypes'] = $question->options->unitgradingtype ;
1220 case 1 : // NUMERICALQUESTIONUNITMULTICHOICEDISPLAY
1221 $default_values['unitrole'] = 3 ;
1222 $default_values['multichoicedisplay'] = $question->options->unitgradingtype ;
1223 $default_values['unitgradingtypes'] = $question->options->unitgradingtype ;
1225 case 2 : // NUMERICALQUESTIONUNITTEXTDISPLAY
1226 $default_values['unitrole'] = 1 ;
1227 case 3 : // NUMERICALQUESTIONUNITNODISPLAY
1228 $default_values['unitrole'] = 0 ;
1229 // $default_values['showunits1'] = $question->options->showunits ;
1232 $default_values['unitsleft'] = $question->options->unitsleft ;
1233 // $question->unitrole = $default_values['unitrole'] ;
1236 $component = 'qtype_' . $question->qtype;
1237 $draftid = file_get_submitted_draft_itemid('instructions');
1238 $default_values['instructions'] = array();
1239 $default_values['instructions']['format'] = $question->options->instructionsformat;
1240 $default_values['instructions']['text'] = file_prepare_draft_area(
1241 $draftid, // draftid
1242 $context->id, // context
1243 $component, // component
1244 'instruction', // filarea
1245 !empty($question->id)?(int)$question->id:null, // itemid
1246 $mform->fileoptions, // options
1247 $question->options->instructions // text
1249 $default_values['instructions']['itemid'] = $draftid;
1251 if (isset($question->options->units)) {
1252 $units = array_values($question->options->units);
1253 if (!empty($units)) {
1254 foreach ($units as $key => $unit){
1255 $default_values['unit['.$key.']'] = $unit->unit;
1256 $default_values['multiplier['.$key.']'] = $unit->multiplier;
1264 * function use in in function validation()
1265 * of edit_..._form.php for
1266 * numerical, calculated, calculatedsimple
1269 function validate_numerical_options(& $data, & $errors){
1270 $units = $data['unit'];
1271 switch ($data['unitrole']){
1272 case '0' : $showunits = NUMERICALQUESTIONUNITNODISPLAY ;
1274 case '1' : $showunits = NUMERICALQUESTIONUNITTEXTDISPLAY ;
1276 case '2' : $showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
1278 case '3' : $showunits = $data['multichoicedisplay'] ;
1282 if (($showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY) ||
1283 ($showunits == NUMERICALQUESTIONUNITMULTICHOICEDISPLAY ) ||
1284 ($showunits == NUMERICALQUESTIONUNITTEXTDISPLAY )){
1285 if (trim($units[0]) == ''){
1286 $errors['unit[0]'] = 'You must set a valid unit name' ;
1289 if ($showunits == NUMERICALQUESTIONUNITNODISPLAY ){
1290 if (count($units)) {
1291 foreach ($units as $key => $unit){
1292 if ($units[$key] != ''){
1293 $errors["unit[$key]"] = 'You must erase this unit name' ;
1300 // Check double units.
1301 $alreadyseenunits = array();
1302 if (isset($data['unit'])) {
1303 foreach ($data['unit'] as $key => $unit) {
1304 $trimmedunit = trim($unit);
1305 if ($trimmedunit!='' && in_array($trimmedunit, $alreadyseenunits)) {
1306 $errors["unit[$key]"] = get_string('errorrepeatedunit', 'qtype_numerical');
1307 if (trim($data['multiplier'][$key]) == '') {
1308 $errors["multiplier[$key]"] = get_string('errornomultiplier', 'qtype_numerical');
1310 } elseif($trimmedunit!='') {
1311 $alreadyseenunits[] = $trimmedunit;
1315 $units = $data['unit'];
1316 if (count($units)) {
1317 foreach ($units as $key => $unit){
1318 if (is_numeric($unit)){
1319 $errors['unit['.$key.']'] = get_string('mustnotbenumeric', 'qtype_calculated');
1321 $trimmedunit = trim($unit);
1322 $trimmedmultiplier = trim($data['multiplier'][$key]);
1323 if (!empty($trimmedunit)){
1324 if (empty($trimmedmultiplier)){
1325 $errors['multiplier['.$key.']'] = get_string('youmustenteramultiplierhere', 'qtype_calculated');
1327 if (!is_numeric($trimmedmultiplier)){
1328 $errors['multiplier['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
1338 function valid_unit($rawresponse, $units) {
1339 // Make units more useful
1340 $tmpunits = array();
1341 foreach ($units as $unit) {
1342 $tmpunits[$unit->unit] = $unit->multiplier;
1344 // remove spaces and normalise decimal places.
1345 $search = array(' ', ',');
1346 $replace = array('', '.');
1347 $rawresponse = str_replace($search, $replace, trim($rawresponse));
1349 // Apply any unit that is present.
1350 if (preg_match('~^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$~',
1351 $rawresponse, $responseparts)) {
1353 if (!empty($responseparts[5])) {
1355 if (isset($tmpunits[$responseparts[5]])) {
1356 // Valid number with unit.
1357 return true ; //(float)$responseparts[1] / $tmpunits[$responseparts[5]];
1359 // Valid number with invalid unit. Must be wrong.
1364 // Valid number without unit.
1365 return false ; //(float)$responseparts[1];
1368 // Invalid number. Must be wrong.
1373 * Runs all the code required to set up and save an essay question for testing purposes.
1374 * Alternate DB table prefix may be used to facilitate data deletion.
1376 function generate_test($name, $courseid = null) {
1378 list($form, $question) = default_questiontype::generate_test($name, $courseid);
1379 $question->category = $form->category;
1381 $form->questiontext = "What is 674 * 36?";
1382 $form->generalfeedback = "Thank you";
1383 $form->penalty = 0.1;
1384 $form->defaultgrade = 1;
1385 $form->noanswers = 3;
1386 $form->answer = array('24264', '24264', '1');
1387 $form->tolerance = array(10, 100, 0);
1388 $form->fraction = array(1, 0.5, 0);
1390 $form->unit = array(0 => null, 1 => null);
1391 $form->multiplier = array(1, 0);
1392 $form->feedback = array('Very good', 'Close, but not quite there', 'Well at least you tried....');
1395 $course = $DB->get_record('course', array('id' => $courseid));
1398 return $this->save_question($question, $form, $course);
1401 * When move the category of questions, the belonging files should be moved as well
1402 * @param object $question, question information
1403 * @param object $newcategory, target category information
1405 function move_files($question, $newcategory) {
1407 parent::move_files($question, $newcategory);
1409 $fs = get_file_storage();
1410 // process files in answer
1411 if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) {
1412 $oldanswers = array();
1414 $component = 'question';
1415 $filearea = 'answerfeedback';
1416 foreach ($oldanswers as $answer) {
1417 $files = $fs->get_area_files($question->contextid, $component, $filearea, $answer->id);
1418 foreach ($files as $storedfile) {
1419 if (!$storedfile->is_directory()) {
1420 $newfile = new stdClass();
1421 $newfile->contextid = (int)$newcategory->contextid;
1422 $fs->create_file_from_storedfile($newfile, $storedfile);
1423 $storedfile->delete();
1427 $component = 'qtype_numerical';
1428 $filearea = 'instruction';
1429 $files = $fs->get_area_files($question->contextid, $component, $filearea, $question->id);
1430 foreach ($files as $storedfile) {
1431 if (!$storedfile->is_directory()) {
1432 $newfile = new stdClass();
1433 $newfile->contextid = (int)$newcategory->contextid;
1434 $fs->create_file_from_storedfile($newfile, $storedfile);
1435 $storedfile->delete();
1440 function check_file_access($question, $state, $options, $contextid, $component,
1442 $itemid = reset($args);
1443 if ($component == 'question' && $filearea == 'answerfeedback') {
1444 $result = $options->feedback && array_key_exists($itemid, $question->options->answers);
1448 foreach($question->options->answers as $answer) {
1449 if ($this->test_response($question, $state, $answer)) {
1454 } else if ($filearea == 'instruction') {
1455 if ($itemid != $question->id) {
1461 return parent::check_file_access($question, $state, $options, $contextid, $component,
1467 // INITIATION - Without this line the question type is not in use.
1468 question_register_questiontype(new question_numerical_qtype());
1469 if ( ! defined ("NUMERICALQUESTIONUNITTEXTINPUTDISPLAY")) {
1470 define("NUMERICALQUESTIONUNITTEXTINPUTDISPLAY", 0);
1472 if ( ! defined ("NUMERICALQUESTIONUNITMULTICHOICEDISPLAY")) {
1473 define("NUMERICALQUESTIONUNITMULTICHOICEDISPLAY", 1);
1475 if ( ! defined ("NUMERICALQUESTIONUNITTEXTDISPLAY")) {
1476 define("NUMERICALQUESTIONUNITTEXTDISPLAY", 2);
1478 if ( ! defined ("NUMERICALQUESTIONUNITNODISPLAY")) {
1479 define("NUMERICALQUESTIONUNITNODISPLAY", 3);