mirrored from git://git.moodle.org/moodle.git
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
questiontype.php
1397 lines (1253 loc) · 63.5 KB
/
questiontype.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @author Martin Dougiamas and many others. Tim Hunt.
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package questionbank
* @subpackage questiontypes
*/
require_once("$CFG->dirroot/question/type/shortanswer/questiontype.php");
/**
* NUMERICAL QUESTION TYPE CLASS
*
* This class contains some special features in order to make the
* question type embeddable within a multianswer (cloze) question
*
* This question type behaves like shortanswer in most cases.
* Therefore, it extends the shortanswer question type...
* @package questionbank
* @subpackage questiontypes
*/
class question_numerical_qtype extends question_shortanswer_qtype {
public $virtualqtype = false;
function name() {
return 'numerical';
}
function has_wildcards_in_responses() {
return true;
}
function requires_qtypes() {
return array('shortanswer');
}
function get_question_options(&$question) {
// Get the question answers and their respective tolerances
// Note: question_numerical is an extension of the answer table rather than
// the question table as is usually the case for qtype
// specific tables.
global $CFG, $DB, $OUTPUT;
if (!$question->options->answers = $DB->get_records_sql(
"SELECT a.*, n.tolerance " .
"FROM {question_answers} a, " .
" {question_numerical} n " .
"WHERE a.question = ? " .
" AND a.id = n.answer " .
"ORDER BY a.id ASC", array($question->id))) {
echo $OUTPUT->notification('Error: Missing question answer for numerical question ' . $question->id . '!');
return false;
}
$this->get_numerical_units($question);
//get_numerical_options() need to know if there are units
// to set correctly default values
$this->get_numerical_options($question);
// If units are defined we strip off the default unit from the answer, if
// it is present. (Required for compatibility with the old code and DB).
if ($defaultunit = $this->get_default_numerical_unit($question)) {
foreach($question->options->answers as $key => $val) {
$answer = trim($val->answer);
$length = strlen($defaultunit->unit);
if ($length && substr($answer, -$length) == $defaultunit->unit) {
$question->options->answers[$key]->answer =
substr($answer, 0, strlen($answer)-$length);
}
}
}
return true;
}
function get_numerical_units(&$question) {
global $DB;
if ($units = $DB->get_records('question_numerical_units', array('question' => $question->id), 'id ASC')) {
$units = array_values($units);
} else {
$units = array();
}
foreach ($units as $key => $unit) {
$units[$key]->multiplier = clean_param($unit->multiplier, PARAM_NUMBER);
}
$question->options->units = $units;
return true;
}
function get_default_numerical_unit(&$question) {
if (isset($question->options->units[0])) {
foreach ($question->options->units as $unit) {
if (abs($unit->multiplier - 1.0) < '1.0e-' . ini_get('precision')) {
return $unit;
}
}
}
return false;
}
function get_numerical_options(&$question) {
global $DB;
if (!$options = $DB->get_record('question_numerical_options', array('question' => $question->id))) {
$question->options->unitgradingtype = 0; // total grade
$question->options->unitpenalty = 0.1; // default for old questions
// the default
if ($defaultunit = $this->get_default_numerical_unit($question)) {
// so units can be graded
$question->options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
}else {
// only numerical will be graded
$question->options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
}
$question->options->unitsleft = 0 ;
$question->options->instructions = '';
$question->options->instructionsformat = editors_get_preferred_format();
} else {
$question->options->unitgradingtype = $options->unitgradingtype;
$question->options->unitpenalty = $options->unitpenalty;
$question->options->showunits = $options->showunits;
$question->options->unitsleft = $options->unitsleft;
$question->options->instructions = $options->instructions;
$question->options->instructionsformat = $options->instructionsformat;
}
return true;
}
/**
* Save the units and the answers associated with this question.
*/
function save_question_options($question) {
global $DB;
$context = $question->context;
// Get old versions of the objects
$oldanswers = $DB->get_records('question_answers',
array('question' => $question->id), 'id ASC');
$oldoptions = $DB->get_records('question_numerical',
array('question' => $question->id), 'answer ASC');
// Save the units.
$result = $this->save_numerical_units($question);
if (isset($result->error)) {
return $result;
} else {
$units = $result->units;
}
// Insert all the new answers
foreach ($question->answer as $key => $answerdata) {
// Check for, and ingore, completely blank answer from the form.
if (trim($answerdata) == '' && $question->fraction[$key] == 0 &&
html_is_blank($question->feedback[$key]['text'])) {
continue;
}
// Update an existing answer if possible.
$answer = array_shift($oldanswers);
if (!$answer) {
$answer = new stdClass();
$answer->question = $question->id;
$answer->answer = '';
$answer->feedback = '';
$answer->id = $DB->insert_record('question_answers', $answer);
}
if (trim($answerdata) === '*') {
$answer->answer = '*';
} else {
$answer->answer = $this->apply_unit($answerdata, $units);
if ($answer->answer === false) {
$result->notice = get_string('invalidnumericanswer', 'quiz');
}
}
$answer->fraction = $question->fraction[$key];
$answer->feedback = $this->import_or_save_files($question->feedback[$key],
$context, 'question', 'answerfeedback', $answer->id);
$answer->feedbackformat = $question->feedback[$key]['format'];
$DB->update_record('question_answers', $answer);
// Set up the options object
if (!$options = array_shift($oldoptions)) {
$options = new stdClass();
}
$options->question = $question->id;
$options->answer = $answer->id;
if (trim($question->tolerance[$key]) == '') {
$options->tolerance = '';
} else {
$options->tolerance = $this->apply_unit($question->tolerance[$key], $units);
if ($options->tolerance === false) {
$result->notice = get_string('invalidnumerictolerance', 'quiz');
}
}
if (isset($options->id)) {
$DB->update_record('question_numerical', $options);
} else {
$DB->insert_record('question_numerical', $options);
}
}
// Delete any left over old answer records.
$fs = get_file_storage();
foreach($oldanswers as $oldanswer) {
$fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
$DB->delete_records('question_answers', array('id' => $oldanswer->id));
}
foreach($oldoptions as $oldoption) {
$DB->delete_records('question_numerical', array('id' => $oldoption->id));
}
$result = $this->save_numerical_options($question);
if (!empty($result->error) || !empty($result->notice)) {
return $result;
}
return true;
}
/**
* The numerical options control the display and the grading of the unit
* part of the numerical question and related types (calculateds)
* Questions previous to 2,0 do not have this table as multianswer questions
* in all versions including 2,0. The default values are set to give the same grade
* as old question.
*
*/
function save_numerical_options($question) {
global $DB;
$result = new stdClass;
$update = true ;
$options = $DB->get_record('question_numerical_options', array('question' => $question->id));
if (!$options) {
$options = new stdClass;
$options->question = $question->id;
$options->instructions = '';
$options->id = $DB->insert_record('question_numerical_options', $options);
}
if (isset($question->options->unitgradingtype)) {
$options->unitgradingtype = $question->options->unitgradingtype;
} else {
$options->unitgradingtype = 0 ;
}
if (isset($question->unitpenalty)){
$options->unitpenalty = $question->unitpenalty;
} else { //so this is either an old question or a close question type
$options->unitpenalty = 1 ;
}
// if we came from the form then 'unitrole' exists
if (isset($question->unitrole)){
switch ($question->unitrole){
case '0' : $options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
break ;
case '1' : $options->showunits = NUMERICALQUESTIONUNITTEXTDISPLAY ;
break ;
case '2' : $options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
$options->unitgradingtype = 0 ;
break ;
case '3' : $options->showunits = $question->multichoicedisplay ;
$options->unitgradingtype = $question->unitgradingtypes ;
break ;
}
} else {
if (isset($question->showunits)){
$options->showunits = $question->showunits;
} else {
if ($defaultunit = $this->get_default_numerical_unit($question)) {
// so units can be used
$options->showunits = NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ;
} else {
// only numerical will be graded
$options->showunits = NUMERICALQUESTIONUNITNODISPLAY ;
}
}
}
if (isset($question->unitsleft)) {
$options->unitsleft = $question->unitsleft;
} else {
$options->unitsleft = 0 ;
}
if (isset($question->instructions) && is_array($question->instructions)){
$options->instructions = $this->import_or_save_files($question->instructions,
$question->context, 'qtype_'.$question->qtype , 'instruction', $question->id);
$options->instructionsformat = $question->instructions['format'];
} else {
$options->instructions = '' ;
$options->instructionsformat = editors_get_preferred_format();
}
$DB->update_record('question_numerical_options', $options);
return $result;
}
function save_numerical_units($question) {
global $DB;
$result = new stdClass;
// Delete the units previously saved for this question.
$DB->delete_records('question_numerical_units', array('question' => $question->id));
// Nothing to do.
if (!isset($question->multiplier)) {
$result->units = array();
return $result;
}
// Save the new units.
$units = array();
$unitalreadyinsert = array();
foreach ($question->multiplier as $i => $multiplier) {
// Discard any unit which doesn't specify the unit or the multiplier
if (!empty($question->multiplier[$i]) && !empty($question->unit[$i])&& !array_key_exists($question->unit[$i],$unitalreadyinsert)) {
$unitalreadyinsert[$question->unit[$i]] = 1 ;
$units[$i] = new stdClass;
$units[$i]->question = $question->id;
$units[$i]->multiplier = $this->apply_unit($question->multiplier[$i], array());
$units[$i]->unit = $question->unit[$i];
$DB->insert_record('question_numerical_units', $units[$i]);
}
}
unset($question->multiplier, $question->unit);
$result->units = &$units;
return $result;
}
function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
$state->responses = array();
$state->responses['answer'] = '';
$state->responses['unit'] = '';
return true;
}
function restore_session_and_responses(&$question, &$state) {
if(false === strpos($state->responses[''], '|||||')){
$state->responses['answer']= $state->responses[''];
$state->responses['unit'] = '';
$this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
}else {
$responses = explode('|||||', $state->responses['']);
$state->responses['answer']= $responses[0];
$state->responses['unit'] = $responses[1];
}
return true;
}
function find_unit_index(&$question,$value){
$length = 0;
$goodkey = 0 ;
foreach ($question->options->units as $key => $unit){
if($unit->unit ==$value ) {
return $key ;
}
}
return 0 ;
}
function split_old_answer($rawresponse, $units, &$answer ,&$unit ) {
$answer = $rawresponse ;
// remove spaces and normalise decimal places.
$search = array(' ', ',');
$replace = array('', '.');
$rawresponse = str_replace($search, $replace, trim($rawresponse));
if (preg_match('~^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$~',
$rawresponse, $responseparts)) {
if(isset($responseparts[5]) ){
$unit = $responseparts[5] ;
}
if(isset($responseparts[1]) ){
$answer = $responseparts[1] ;
}
}
return ;
}
function save_session_and_responses(&$question, &$state) {
global $DB;
$responses = '';
if(isset($state->responses['unit']) && isset($question->options->units[$state->responses['unit']])){
$responses = $state->responses['answer'].'|||||'.$question->options->units[$state->responses['unit']]->unit;
}else if(isset($state->responses['unit'])){
$responses = $state->responses['answer'].'|||||'.$state->responses['unit'] ;
}else {
$responses = $state->responses['answer'].'|||||';
}
// Set the legacy answer field
$DB->set_field('question_states', 'answer', $responses, array('id' => $state->id));
return true;
}
function delete_question($questionid, $contextid) {
global $DB;
$DB->delete_records('question_numerical', array('question' => $questionid));
$DB->delete_records('question_numerical_options', array('question' => $questionid));
$DB->delete_records('question_numerical_units', array('question' => $questionid));
parent::delete_question($questionid, $contextid);
}
/**
* This function has been reinserted in numerical/questiontype.php to simplify
* the separate rendering of number and unit
*/
function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
global $CFG, $OUTPUT;
$context = $this->get_context_by_category_id($question->category);
$readonly = empty($options->readonly) ? '' : 'readonly="readonly"';
$formatoptions = new stdClass;
$formatoptions->noclean = true;
$formatoptions->para = false;
$nameprefix = $question->name_prefix;
$component = 'qtype_' . $question->qtype;
// rewrite instructions text
$question->options->instructions = quiz_rewrite_question_urls($question->options->instructions, 'pluginfile.php', $context->id, $component, 'instruction', array($state->attempt, $state->question), $question->id);
/// Print question text and media
$questiontext = format_text($question->questiontext,
$question->questiontextformat,
$formatoptions, $cmoptions->course);
/// Print input controls
// as the entry is controlled the question type here is numerical
// In all cases there is a text input for the number
// If $question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY
// there is an additional text input for the unit
// If $question->options->showunits == NUMERICALQUESTIONUNITMULTICHOICEDISPLAY"
// radio elements display the defined unit
// The code allows the input number elememt to be displayed
// before i.e. at left or after at rigth of the unit variants.
$nameanswer = "name=\"".$question->name_prefix."answer\"";
$nameunit = "name=\"".$question->name_prefix."unit\"";
// put old answer data in $state->responses['answer'] and $state->responses['unit']
if (isset($state->responses['']) && $state->responses[''] != '' && !isset($state->responses['answer'])){
$this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
}
// prepare the values of the input elements to be dispalyed answer i.e. number and unit
if (isset($state->responses['answer']) && $state->responses['answer']!='') {
$valueanswer = ' value="'.s($state->responses['answer']).'" ';
} else {
$valueanswer = ' value="" ';
}
if (isset($state->responses['unit']) && $state->responses['unit']!='') {
$valueunit = ' value="'.s($state->responses['unit']).'" ';
} else {
$valueunit = ' value="" ';
if ($question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY ){
$valueunit = ' value="'.s($question->options->units[0]->unit).'" ';
}
}
$feedback = '';
$class = '';
$classunit = '' ;
$classunitvalue = '' ;
$feedbackimg = '';
$feedbackimgunit = '' ;
$answerasterisk = false ;
$response = '' ;
$valid_numerical_unit = false ;
$valid_numerical_unit_index = -1 ;
$unit_in_numerical_answer = false ;
$rawgrade = 0 ;
if ($options->feedback) {
$class = question_get_feedback_class(0);
$classunit = question_get_feedback_class(0);
$feedbackimg = question_get_feedback_image(0);
$feedbackimgunit = question_get_feedback_image(0);
$classunitvalue = 0 ;
$valid_numerical_unit_index = -1 ;
// if there is unit in answer and unitgradingtype = 0
// the grade is 0
//this is OK for the first answer with a good response
// having to test for * so response as long as not empty
// $response = $this->extract_numerical_response($state->responses['answer']);
// test for a greater than 0 grade
foreach($question->options->answers as $answer) {
if ($this->test_response($question, $state, $answer)) {
// Answer was correct or partially correct.
if ( $answer->answer === '*'){
$answerasterisk = true ;
}
// in all cases
$class = question_get_feedback_class($answer->fraction);
$feedbackimg = question_get_feedback_image($answer->fraction);
if ($question->options->unitgradingtype == 0 || ($question->options->unitgradingtype == 0 && $answer->answer === '*')){
// if * then unit has the $answer->fraction value
// if $question->options->unitgradingtype == 0 everything has been checked
// if $question->options->showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
// then number - unit combination has been used to test response
// so the unit should have same color
$classunit = question_get_feedback_class($answer->fraction);
$feedbackimgunit = question_get_feedback_image($answer->fraction);
$rawgrade = $answer->fraction ;
}else {
/* so we need to apply unit grading i.e. to check if the number-unit combination
* was the rigth one
* on NUMERICALQUESTIONUNITTEXTINPUTDISPLAY we need only to ckeck if applyunit will test OK
* with the $state->responses['unit'] value which cannot be empty
* if $state->responses['unit']
* if apply-unit is true with a specific unit as long as the unit as been written either in the
* we need the numerical response and test it with the available units
* if the unit used is good then it should be set OK
* however the unit could have been put in the number element in this case
* the unit penalty should be apllied.
* testing apply_unit with no units will get us a false response if there is any text in it
* testing apply_unit with a given unit will get a good value if the number is good with this unit
* apply unit will return the numerical if
* we need to know which conditions let to a good numerical value that were done in the
*/
$valid_numerical_unit = false ;
$rawgrade = $answer->fraction ;
$valid_numerical_unit_index = -1 ;
$invalid_unit_in_numerical_answer = false ;
if ( $answerasterisk ) {
$classunit = question_get_feedback_class($answer->fraction);
$feedbackimgunit = question_get_feedback_image($answer->fraction);
$valid_numerical_unit = true ;//everything is true with *
} else {
// if( isset($state->responses['unit']) && $state->responses['unit'] != '' ){// unit should be written in the unit input or checked in multichoice
// we need to see if something was written in the answer field that was not in the number
// although we cannot actually detect units put before the number which will cause bad numerical.
// use extract response
$response = $this->extract_numerical_response($state->responses['answer']);
if(isset($response->unit ) && $response->unit != ''){
$unit_in_numerical_answer = true ;
}else {
$unit_in_numerical_answer = false ;
}
// the we let the testing to the two cases either
// NUMERICALQUESTIONUNITTEXTINPUTDISPLAY or
// NUMERICALQUESTIONUNITMULTICHOICEDISPLAY
if( !isset($state->responses['unit']) || $state->responses['unit'] == '' ){
// unit should be written in the unit input or checked in multichoice
$valid_numerical_unit = false ;
$classunit = question_get_feedback_class(0);
$feedbackimgunit = question_get_feedback_image(0);
$empty_unit = true ;
} else {
// echo"<p> some unit answer <pre>";print_r($answer) ;echo"</pre></p>";
// echo"<p> some unit answer <pre>";print_r($answer) ;echo"</pre></p>";
$empty_unit = false ;
$valid_numerical_unit = false ;
foreach ($question->options->units as $key => $unit) {
if ($unit->unit == $state->responses['unit']){
// $response = $this->apply_unit($state->responses['answer'].$unit->unit, array($question->options->units[$key])) ;
// echo "<p> avant false valid_numerical_unit_index $valid_numerical_unit_index ".$state->responses['answer']."</p>";
$invalid_unit_found = 0 ;
if ($response->number !== false) {
//echo "<p> avanr get valid_numerical_unit_index $valid_numerical_unit_index </p>";
// $this->get_tolerance_interval($answer);
$testresponse = $response->number /$unit->multiplier ;
if($answer->min <= $testresponse && $testresponse <= $answer->max){
//echo "<p> apres min max valid_numerical_unit_index $valid_numerical_unit_index </p>";
$classunit = question_get_feedback_class($answer->fraction) ; //question_get_feedback_class(1);
$feedbackimgunit = question_get_feedback_image($rawgrade);
$valid_numerical_unit = true ;
$valid_numerical_unit_index = $key ;
break ;
}
}
}
}
}
}
}
if ($answer->feedback) {
$answer->feedback = quiz_rewrite_question_urls($answer->feedback, 'pluginfile.php', $context->id, 'question', 'answerfeedback', array($state->attempt, $state->question), $answer->id);
$feedback = format_text($answer->feedback, $answer->feedbackformat, $formatoptions, $cmoptions->course);
}
break;
}
}
}
$state->options->raw_unitpenalty = 0 ;
$raw_unitpenalty = 0 ;
if( $question->options->showunits == NUMERICALQUESTIONUNITNODISPLAY ||
$question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY ) {
$classunitvalue = 1 ;
}
if(! $answerasterisk && $question->options->unitgradingtype != 0 && (! $valid_numerical_unit || $unit_in_numerical_answer)){
if($question->options->unitgradingtype == 1){
$raw_unitpenalty = $question->options->unitpenalty * $rawgrade ;
}else {
$raw_unitpenalty = $question->options->unitpenalty ;
}
$state->options->raw_unitpenalty = $raw_unitpenalty ;
}
/// Removed correct answer, to be displayed later MDL-7496
include("$CFG->dirroot/question/type/numerical/display.html");
}
function compare_responses(&$question, $state, $teststate) {
if ($question->options->showunits == NUMERICALQUESTIONUNITMULTICHOICEDISPLAY && isset($question->options->units) && isset($state->responses['unit']) && isset($question->options->units[$state->responses['unit']] )){
$state->responses['unit']=$question->options->units[$state->responses['unit']]->unit;
};
$responses = '';
$testresponses = '';
if (isset($state->responses['answer'])){
$responses = $state->responses['answer'];
}
if (isset($state->responses['unit'])){
$responses .= $state->responses['unit'];
}
if (isset($teststate->responses['answer'])){
$testresponses = $teststate->responses['answer'];
}
if (isset($teststate->responses['unit'])){
$testresponses .= $teststate->responses['unit'];
}
if ( isset($responses) && isset($testresponses )) {
return $responses == $testresponses ;
}
return false;
}
/**
* Checks whether a response matches a given answer, taking the tolerance
* and but NOT the unit into account. Returns a true for if a response matches the
* answer or in one of the unit , false if it doesn't.
* the total grading will see if the unit match.
* if unit != -1 then the test is done only on this unit
*/
function test_response(&$question, &$state, $answer ) {
// Deal with the match anything answer.
if ($answer->answer === '*') {
return true;
}
// using old grading process if $question->unitgradingtype == 0
// and adding unit1 for the new option NUMERICALQUESTIONUNITTEXTDISPLAY
if ($question->options->unitgradingtype == 0 ){
// values coming form old question stored in attempts
if (!isset($state->responses['answer']) && isset($state->responses[''])){
$state->responses['answer'] = $state->responses[''];
}
$answertotest = $state->responses['answer'];
// values coming from NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
// or NUMERICALQUESTIONUNITTEXTDISPLAY as unit hidden HTML element
if($question->options->showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY ){
$testresponse = $this->extract_numerical_response($state->responses['answer']);
if($testresponse->unit != '' || $testresponse->number === false){
return false;
}
$answertotest = $testresponse->number ;
}
if(isset($state->responses['unit'])) {
$answertotest .= $state->responses['unit'] ;
}
// if ($question->options->showunits == NUMERICALQUESTIONUNITTEXTDISPLAY && isset($question->options->units[0])){
// $answertotest .= $question->options->units[0]->unit ;
// }
// test OK if only numerical or numerical with known unit names with the unit mltiplier applied
$response = $this->apply_unit($answertotest, $question->options->units);
if ($response === false) {
return false; // The student did not type a number.
}
// The student did type a number, so check it with tolerances.
$this->get_tolerance_interval($answer);
return ($answer->min <= $response && $response <= $answer->max);
} else { // $question->options->unitgradingtype > 0
/* testing with unitgradingtype $question->options->unitgradingtype > 0
* if the response is at least patially true
* if the numerical value agree in the interval
* if so the only non valid case will be a bad unit and a unity penalty.
To be able to test (old) questions that do not have an unit
* input element the test is done using the $state->responses['']
* which contains the response which is analyzed by extract_numerical_response()
* If the data comes from the numerical or calculated display
* the $state->responses['unit'] comes from either
* a multichoice radio element NUMERICALQUESTIONUNITMULTICHOICEDISPLAY
* where the $state->responses['unit'] value is the key => unit object
* in the the $question->options->units array
* or an input text element NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
* which contains the student response
* for NUMERICALQUESTIONUNITTEXTDISPLAY and NUMERICALQUESTIONUNITNODISPLAY
*
*/
$response = $this->extract_numerical_response($state->responses['answer']);
if ($response->number === false ) {
return false; // The student did not type a number.
}
// The student did type a number, so check it with tolerances.
$this->get_tolerance_interval($answer);
if ($answer->min <= $response->number && $response->number <= $answer->max){
return true;
}
// testing for other units
if ( isset($question->options->units) && count($question->options->units) > 0) {
foreach($question->options->units as $key =>$unit){
$testresponse = $response->number /$unit->multiplier ;
if($answer->min <= $testresponse && $testresponse<= $answer->max) {
return true;
}
}
}
return false;
}
return false;
}
/**
* Performs response processing and grading
* The function was redefined for handling correctly the two parts
* number and unit of numerical or calculated questions
* The code handles also the case when there no unit defined by the user or
* when used in a multianswer (Cloze) question.
* This function performs response processing and grading and updates
* the state accordingly.
* @return boolean Indicates success or failure.
* @param object $question The question to be graded. Question type
* specific information is included.
* @param object $state The state of the question to grade. The current
* responses are in ->responses. The last graded state
* is in ->last_graded (hence the most recently graded
* responses are in ->last_graded->responses). The
* question type specific information is also
* included. The ->raw_grade and ->penalty fields
* must be updated. The method is able to
* close the question session (preventing any further
* attempts at this question) by setting
* $state->event to QUESTION_EVENTCLOSEANDGRADE
* @param object $cmoptions
*/
function grade_responses(&$question, &$state, $cmoptions) {
if ( isset($state->responses['']) && $state->responses[''] != '' && !isset($state->responses['answer'])){
$this->split_old_answer($state->responses[''], $question->options->units, $state->responses['answer'] ,$state->responses['unit'] );
}
$state->raw_grade = 0;
$valid_numerical_unit = false ;
$break = 0 ;
$unittested = '';
$hasunits = 0 ;
$answerasterisk = false ;
$break = 0 ;
foreach($question->options->answers as $answer) {
if ($this->test_response($question, $state, $answer)) {
// Answer was correct or partially correct.
$state->raw_grade = $answer->fraction ;
if ($question->options->unitgradingtype == 0 || $answer->answer === '*'){
// if * then unit has the $answer->fraction value
// if $question->options->unitgradingtype == 0 everything has been checked
// if $question->options->showunits == NUMERICALQUESTIONUNITTEXTINPUTDISPLAY
// then number - unit combination has been used to test response
// so the unit should have same color
}else {
// so we need to apply unit grading i.e. to check if the number-unit combination
// was the rigth one
$valid_numerical_unit = false ;
$class = question_get_feedback_class($answer->fraction);
$feedbackimg = question_get_feedback_image($answer->fraction);
if(isset($state->responses['unit']) && $state->responses['unit'] != '' ){
foreach ($question->options->units as $key => $unit) {
if ($unit->unit == $state->responses['unit']){
$response = $this->apply_unit($state->responses['answer'].$state->responses['unit'], array($question->options->units[$key])) ;
if ($response !== false) {
$this->get_tolerance_interval($answer);
if($answer->min <= $response && $response <= $answer->max){
$valid_numerical_unit = true ;
}
}
break ;
}
}
}
}
break ;
}
}
// apply unit penalty
$raw_unitpenalty = 0 ;
if($question->options->unitgradingtype != 0 && !empty($question->options->unitpenalty)&& $valid_numerical_unit != true ){
if($question->options->unitgradingtype == 1){
$raw_unitpenalty = $question->options->unitpenalty * $state->raw_grade ;
}else {
$raw_unitpenalty = $question->options->unitpenalty ;
}
$state->raw_grade -= $raw_unitpenalty ;
}
// Make sure we don't assign negative or too high marks.
$state->raw_grade = min(max((float) $state->raw_grade,
0.0), 1.0) * $question->maxgrade;
// Update the penalty.
$state->penalty = $question->penalty * $question->maxgrade;
// mark the state as graded
$state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
return true;
}
function get_correct_responses(&$question, &$state) {
$correct = parent::get_correct_responses($question, $state);
$unit = $this->get_default_numerical_unit($question);
if (isset($correct['']) && $correct[''] != '*' && $unit) {
$correct[''] .= ' '.$unit->unit;
}
return $correct;
}
// ULPGC ecastro
function get_all_responses(&$question, &$state) {
$result = new stdClass;
$answers = array();
$unit = $this->get_default_numerical_unit($question);
if (is_array($question->options->answers)) {
foreach ($question->options->answers as $aid=>$answer) {
$r = new stdClass;
$r->answer = $answer->answer;
$r->credit = $answer->fraction;
$this->get_tolerance_interval($answer);
if ($r->answer != '*' && $unit) {
$r->answer .= ' ' . $unit->unit;
}
if ($answer->max != $answer->min) {
$max = "$answer->max"; //format_float($answer->max, 2);
$min = "$answer->min"; //format_float($answer->max, 2);
$r->answer .= ' ('.$min.'..'.$max.')';
}
$answers[$aid] = $r;
}
}
$result->id = $question->id;
$result->responses = $answers;
return $result;
}
function get_actual_response($question, $state) {
if (!empty($state->responses) && !empty($state->responses[''])) {
if(false === strpos($state->responses[''], '|||||')){
$responses[] = $state->responses[''];
}else {
$resp = explode('|||||', $state->responses['']);
$responses[] = $resp[0].$resp[1];
}
} else {
$responses[] = '';
}
return $responses;
}
function get_tolerance_interval(&$answer) {
// No tolerance
if (empty($answer->tolerance)) {
$answer->tolerance = 0;
}
// Calculate the interval of correct responses (min/max)
if (!isset($answer->tolerancetype)) {
$answer->tolerancetype = 2; // nominal
}
// We need to add a tiny fraction depending on the set precision to make the
// comparison work correctly. Otherwise seemingly equal values can yield
// false. (fixes bug #3225)
$tolerance = (float)$answer->tolerance + ("1.0e-".ini_get('precision'));
switch ($answer->tolerancetype) {
case '1': case 'relative':
/// Recalculate the tolerance and fall through
/// to the nominal case:
$tolerance = $answer->answer * $tolerance;
// Do not fall through to the nominal case because the tiny fraction is a factor of the answer
$tolerance = abs($tolerance); // important - otherwise min and max are swapped
$max = $answer->answer + $tolerance;
$min = $answer->answer - $tolerance;
break;
case '2': case 'nominal':
$tolerance = abs($tolerance); // important - otherwise min and max are swapped
// $answer->tolerance 0 or something else
if ((float)$answer->tolerance == 0.0 && abs((float)$answer->answer) <= $tolerance ){
$tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction
} else if ((float)$answer->tolerance != 0.0 && abs((float)$answer->tolerance) < abs((float)$answer->answer) && abs((float)$answer->answer) <= $tolerance){
$tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction
}
$max = $answer->answer + $tolerance;
$min = $answer->answer - $tolerance;
break;
case '3': case 'geometric':
$quotient = 1 + abs($tolerance);
$max = $answer->answer * $quotient;
$min = $answer->answer / $quotient;
break;
default:
print_error('unknowntolerance', 'question', '', $answer->tolerancetype);
}
$answer->min = $min;
$answer->max = $max;
return true;
}
/**
* Checks if the $rawresponse has a unit and applys it if appropriate.
*
* @param string $rawresponse The response string to be converted to a float.
* @param array $units An array with the defined units, where the
* unit is the key and the multiplier the value.
* @return float The rawresponse with the unit taken into
* account as a float.
*/
function extract_numerical_response($rawresponse) {
$extractedresponse = new stdClass() ;
$rawresponse = trim($rawresponse) ;
$search = array(' ', ',');
// test if a . is present or there are multiple , (i.e. 2,456,789 ) so that we don't need spaces and ,
if ( strpos($rawresponse,'.' ) !== false || substr_count($rawresponse,',') > 1 ) {
$replace = array('', '');
}else { // remove spaces and normalise , to a . .
$replace = array('', '.');
}
$rawresponse = str_replace($search, $replace, $rawresponse);
if (preg_match('~^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$~',
$rawresponse, $responseparts)) {
//return (float)$responseparts[1] ;
$extractedresponse->number = (float)$responseparts[1] ;
}else {
$extractedresponse->number = false ;
}
if (!empty($responseparts[5])) {
$extractedresponse->unit = $responseparts[5] ;
}else {
$extractedresponse->unit = '';
}
// Invalid number. Must be wrong.
return clone($extractedresponse) ;
}
/**
* Checks if the $rawresponse has a unit and applys it if appropriate.
*
* @param string $rawresponse The response string to be converted to a float.
* @param array $units An array with the defined units, where the
* unit is the key and the multiplier the value.
* @return float The rawresponse with the unit taken into
* account as a float.
*/
function apply_unit($rawresponse, $units) {
// Make units more useful
$tmpunits = array();
foreach ($units as $unit) {
$tmpunits[$unit->unit] = $unit->multiplier;
}
// remove spaces and normalise decimal places.