mirrored from git://git.moodle.org/moodle.git
/
questionlib.php
1668 lines (1449 loc) · 59.8 KB
/
questionlib.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 // $Id$
/**
* Code for handling and processing questions
*
* This is code that is module independent, i.e., can be used by any module that
* uses questions, like quiz, lesson, ..
* This script also loads the questiontype classes
* Code for handling the editing of questions is in {@link question/editlib.php}
*
* TODO: separate those functions which form part of the API
* from the helper functions.
*
* @version $Id$
* @author Martin Dougiamas and many others. This has recently been completely
* rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
* the Serving Mathematics project
* {@link http://maths.york.ac.uk/serving_maths}
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package question
*/
/// CONSTANTS ///////////////////////////////////
/**#@+
* The different types of events that can create question states
*/
define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle
define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used)
define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated
define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded.
define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked
define('QUESTION_EVENTCLOSE', '8'); // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded.
define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher
/**#@-*/
/**#@+
* The core question types
*/
define("SHORTANSWER", "shortanswer");
define("TRUEFALSE", "truefalse");
define("MULTICHOICE", "multichoice");
define("RANDOM", "random");
define("MATCH", "match");
define("RANDOMSAMATCH", "randomsamatch");
define("DESCRIPTION", "description");
define("NUMERICAL", "numerical");
define("MULTIANSWER", "multianswer");
define("CALCULATED", "calculated");
define("RQP", "rqp");
define("ESSAY", "essay");
/**#@-*/
/**
* Constant determines the number of answer boxes supplied in the editing
* form for multiple choice and similar question types.
*/
define("QUESTION_NUMANS", "10");
/**#@+
* Option flags for ->optionflags
* The options are read out via bitwise operation using these constants
*/
/**
* Whether the questions is to be run in adaptive mode. If this is not set then
* a question closes immediately after the first submission of responses. This
* is how question is Moodle always worked before version 1.5
*/
define('QUESTION_ADAPTIVE', 1);
/** When processing responses the code checks that the new responses at
* a question differ from those given on the previous submission. If
* furthermore this flag is set to true
* then the code goes through the whole history of responses and checks if
* ANY of them are identical to the current response in which case the
* current response is ignored.
*/
define('QUESTION_IGNORE_DUPRESP', 2);
/**#@-*/
/// QTYPES INITIATION //////////////////
/**
* Array holding question type objects
*/
global $QTYPES;
$QTYPES = array(); // This array will be populated when the questiontype.php files are loaded below
/**
* Array of question types names translated to the user's language
*
* The $QTYPE_MENU array holds the names of all the question types that the user should
* be able to create directly. Some internal question types like random questions are excluded.
* The complete list of question types can be found in {@link $QTYPES}.
*/
$QTYPE_MENU = array(); // This array will be populated when the questiontype.php files are loaded
require_once("$CFG->dirroot/question/type/questiontype.php");
/*
* Load the questiontype.php file for each question type
* These files in turn instantiate the corresponding question type class
* and add them to the $QTYPES array
*/
$qtypenames= get_list_of_plugins('question/type');
foreach($qtypenames as $qtypename) {
// Instanciates all plug-in question types
$qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
// echo "Loading $qtypename<br/>"; // Uncomment for debugging
if (is_readable($qtypefilepath)) {
require_once($qtypefilepath);
}
}
/// OTHER CLASSES /////////////////////////////////////////////////////////
/**
* This holds the options that are set by the course module
*/
class cmoptions {
/**
* Whether a new attempt should be based on the previous one. If true
* then a new attempt will start in a state where all responses are set
* to the last responses from the previous attempt.
*/
var $attemptonlast = false;
/**
* Various option flags. The flags are accessed via bitwise operations
* using the constants defined in the CONSTANTS section above.
*/
var $optionflags = QUESTION_ADAPTIVE;
/**
* Determines whether in the calculation of the score for a question
* penalties for earlier wrong responses within the same attempt will
* be subtracted.
*/
var $penaltyscheme = true;
/**
* The maximum time the user is allowed to answer the questions withing
* an attempt. This is measured in minutes so needs to be multiplied by
* 60 before compared to timestamps. If set to 0 no timelimit will be applied
*/
var $timelimit = 0;
/**
* Timestamp for the closing time. Responses submitted after this time will
* be saved but no credit will be given for them.
*/
var $timeclose = 9999999999;
/**
* The id of the course from withing which the question is currently being used
*/
var $course = SITEID;
/**
* Whether the answers in a multiple choice question should be randomly
* shuffled when a new attempt is started.
*/
var $shuffleanswers = false;
/**
* The number of decimals to be shown when scores are printed
*/
var $decimalpoints = 2;
}
/// FUNCTIONS //////////////////////////////////////////////////////
/**
* Returns an array of names of activity modules that use this question
*
* @param object $questionid
* @return array of strings
*/
function question_list_instances($questionid) {
$instances = array();
$modules = get_records('modules');
foreach ($modules as $module) {
$fn = $module->name.'_question_list_instances';
if (function_exists($fn)) {
$instances = $instances + $fn($questionid);
}
}
return $instances;
}
/**
* Returns list of 'allowed' grades for grade selection
* formatted suitably for dropdown box function
* @return object ->gradeoptionsfull full array ->gradeoptions +ve only
*/
function get_grade_options() {
// define basic array of grades
$grades = array(
1,
0.9,
0.8,
0.75,
0.70,
0.66666,
0.60,
0.50,
0.40,
0.33333,
0.30,
0.25,
0.20,
0.16666,
0.142857,
0.125,
0.11111,
0.10,
0.05,
0);
// iterate through grades generating full range of options
$gradeoptionsfull = array();
$gradeoptions = array();
foreach ($grades as $grade) {
$percentage = 100 * $grade;
$neggrade = -$grade;
$gradeoptions["$grade"] = "$percentage %";
$gradeoptionsfull["$grade"] = "$percentage %";
$gradeoptionsfull["$neggrade"] = -$percentage." %";
}
$gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
// sort lists
arsort($gradeoptions, SORT_NUMERIC);
arsort($gradeoptionsfull, SORT_NUMERIC);
// construct return object
$grades = new stdClass;
$grades->gradeoptions = $gradeoptions;
$grades->gradeoptionsfull = $gradeoptionsfull;
return $grades;
}
/**
* match grade options
* if no match return error or match nearest
* @param array $gradeoptionsfull list of valid options
* @param int $grade grade to be tested
* @param string $matchgrades 'error' or 'nearest'
* @return mixed either 'fixed' value or false if erro
*/
function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
// if we just need an error...
if ($matchgrades=='error') {
foreach($gradeoptionsfull as $value => $option) {
if ($grade==$value) {
return $grade;
}
}
// didn't find a match so that's an error
return false;
}
// work out nearest value
else if ($matchgrades=='nearest') {
$hownear = array();
foreach($gradeoptionsfull as $value => $option) {
if ($grade==$value) {
return $grade;
}
$hownear[ $value ] = abs( $grade - $value );
}
// reverse sort list of deltas and grab the last (smallest)
asort( $hownear, SORT_NUMERIC );
reset( $hownear );
return key( $hownear );
}
else {
return false;
}
}
/**
* Tests whether a category is in use by any activity module
*
* @return boolean
* @param integer $categoryid
* @param boolean $recursive Whether to examine category children recursively
*/
function question_category_isused($categoryid, $recursive = false) {
//Look at each question in the category
if ($questions = get_records('question', 'category', $categoryid)) {
foreach ($questions as $question) {
if (count(question_list_instances($question->id))) {
return true;
}
}
}
//Look under child categories recursively
if ($recursive) {
if ($children = get_records('question_categories', 'parent', $categoryid)) {
foreach ($children as $child) {
if (question_category_isused($child->id, $recursive)) {
return true;
}
}
}
}
return false;
}
/**
* Deletes all data associated to an attempt from the database
*
* @param object $question The question being deleted
*/
function delete_attempt($attemptid) {
global $QTYPES;
$states = get_records('question_states', 'attempt', $attemptid);
$stateslist = implode(',', array_keys($states));
// delete questiontype-specific data
foreach ($QTYPES as $qtype) {
$qtype->delete_states($stateslist);
}
// delete entries from all other question tables
// It is important that this is done only after calling the questiontype functions
delete_records("question_states", "attempt", $attemptid);
delete_records("question_sessions", "attemptid", $attemptid);
return;
}
/**
* Deletes question and all associated data from the database
*
* It will not delete a question if it is used by an activity module
* @param object $question The question being deleted
*/
function delete_question($questionid) {
global $QTYPES;
// Do not delete a question if it is used by an activity module
if (count(question_list_instances($questionid))) {
return;
}
// delete questiontype-specific data
if ($question = get_record('question', 'id', $questionid)) {
if (isset($QTYPES[$question->qtype])) {
$QTYPES[$question->qtype]->delete_question($questionid);
}
} else {
echo "Question with id $questionid does not exist.<br />";
}
if ($states = get_records('question_states', 'question', $questionid)) {
$stateslist = implode(',', array_keys($states));
// delete questiontype-specific data
foreach ($QTYPES as $qtype) {
$qtype->delete_states($stateslist);
}
}
// delete entries from all other question tables
// It is important that this is done only after calling the questiontype functions
delete_records("question_answers", "question", $questionid);
delete_records("question_states", "question", $questionid);
delete_records("question_sessions", "questionid", $questionid);
// Now recursively delete all child questions
if ($children = get_records('question', 'parent', $questionid)) {
foreach ($children as $child) {
delete_question($child->id);
}
}
// Finally delete the question record itself
delete_records('question', 'id', $questionid);
return;
}
/**
* All non-used question categories and their questions are deleted and
* categories still used by other courses are moved to the site course.
*
* @param object $course an object representing the course
* @param boolean $feedback to specify if the process must output a summary of its work
* @return boolean
*/
function question_delete_course($course, $feedback=true) {
global $CFG, $QTYPES;
//To detect if we have created the "container category"
$concatid = 0;
//The "container" category we'll create if we need if
$contcat = new object;
//To temporary store changes performed with parents
$parentchanged = array();
//To store feedback to be showed at the end of the process
$feedbackdata = array();
//Cache some strings
$strcatcontainer=get_string('containercategorycreated', 'quiz');
$strcatmoved = get_string('usedcategorymoved', 'quiz');
$strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
if ($categories = get_records('question_categories', 'course', $course->id, 'parent', 'id, parent, name, course')) {
//Sort categories following their tree (parent-child) relationships
$categories = sort_categories_by_tree($categories);
foreach ($categories as $cat) {
//Get the full record
$category = get_record('question_categories', 'id', $cat->id);
//Check if the category is being used anywhere
if(question_category_isused($category->id, true)) {
//It's being used. Cannot delete it, so:
//Create a container category in SITEID course if it doesn't exist
if (!$concatid) {
$concat->course = SITEID;
if (!isset($course->shortname)) {
$course->shortname = 'id=' . $course->id;
}
$concat->name = get_string('savedfromdeletedcourse', 'quiz', $course->shortname);
$concat->info = $concat->name;
$concat->publish = 1;
$concat->stamp = make_unique_id_code();
$concatid = insert_record('question_categories', $concat);
//Fill feedback
$feedbackdata[] = array($concat->name, $strcatcontainer);
}
//Move the category to the container category in SITEID course
$category->course = SITEID;
//Assign to container if the category hasn't parent or if the parent is wrong (not belongs to the course)
if (!$category->parent || !isset($categories[$category->parent])) {
$category->parent = $concatid;
}
//If it's being used, its publish field should be 1
$category->publish = 1;
//Let's update it
update_record('question_categories', $category);
//Save this parent change for future use
$parentchanged[$category->id] = $category->parent;
//Fill feedback
$feedbackdata[] = array($category->name, $strcatmoved);
} else {
//Category isn't being used so:
//Delete it completely (questions and category itself)
//deleting questions
if ($questions = get_records("question", "category", $category->id)) {
foreach ($questions as $question) {
delete_question($question->id);
}
delete_records("question", "category", $category->id);
}
//delete the category
delete_records('question_categories', 'id', $category->id);
//Save this parent change for future use
if (!empty($category->parent)) {
$parentchanged[$category->id] = $category->parent;
} else {
$parentchanged[$category->id] = $concatid;
}
//Update all its child categories to re-parent them to grandparent.
set_field ('question_categories', 'parent', $parentchanged[$category->id], 'parent', $category->id);
//Fill feedback
$feedbackdata[] = array($category->name, $strcatdeleted);
}
}
//Inform about changes performed if feedback is enabled
if ($feedback) {
$table->head = array(get_string('category','quiz'), get_string('action'));
$table->data = $feedbackdata;
print_table($table);
}
}
return true;
}
/**
* Updates the question objects with question type specific
* information by calling {@link get_question_options()}
*
* Can be called either with an array of question objects or with a single
* question object.
* @return bool Indicates success or failure.
* @param mixed $questions Either an array of question objects to be updated
* or just a single question object
*/
function get_question_options(&$questions) {
global $QTYPES;
if (is_array($questions)) { // deal with an array of questions
// get the keys of the input array
$keys = array_keys($questions);
// update each question object
foreach ($keys as $i) {
if (!array_key_exists($questions[$i]->qtype, $QTYPES)) {
$questions[$i]->qtype = 'missingtype';
}
// set name prefix
$questions[$i]->name_prefix = question_make_name_prefix($i);
if (!$QTYPES[$questions[$i]->qtype]->get_question_options($questions[$i]))
return false;
}
return true;
} else { // deal with single question
if (!array_key_exists($questions->qtype, $QTYPES)) {
$questions->qtype = 'missingtype';
}
$questions->name_prefix = question_make_name_prefix($questions->id);
return $QTYPES[$questions->qtype]->get_question_options($questions);
}
}
/**
* Loads the most recent state of each question session from the database
* or create new one.
*
* For each question the most recent session state for the current attempt
* is loaded from the question_states table and the question type specific data and
* responses are added by calling {@link restore_question_state()} which in turn
* calls {@link restore_session_and_responses()} for each question.
* If no states exist for the question instance an empty state object is
* created representing the start of a session and empty question
* type specific information and responses are created by calling
* {@link create_session_and_responses()}.
*
* @return array An array of state objects representing the most recent
* states of the question sessions.
* @param array $questions The questions for which sessions are to be restored or
* created.
* @param object $cmoptions
* @param object $attempt The attempt for which the question sessions are
* to be restored or created.
*/
function get_question_states(&$questions, $cmoptions, $attempt) {
global $CFG, $QTYPES;
// get the question ids
$ids = array_keys($questions);
$questionlist = implode(',', $ids);
// The question field must be listed first so that it is used as the
// array index in the array returned by get_records_sql
$statefields = 'n.questionid as question, s.*, n.sumpenalty, n.comment';
// Load the newest states for the questions
$sql = "SELECT $statefields".
" FROM {$CFG->prefix}question_states s,".
" {$CFG->prefix}question_sessions n".
" WHERE s.id = n.newest".
" AND n.attemptid = '$attempt->uniqueid'".
" AND n.questionid IN ($questionlist)";
$states = get_records_sql($sql);
// Load the newest graded states for the questions
$sql = "SELECT $statefields".
" FROM {$CFG->prefix}question_states s,".
" {$CFG->prefix}question_sessions n".
" WHERE s.id = n.newgraded".
" AND n.attemptid = '$attempt->uniqueid'".
" AND n.questionid IN ($questionlist)";
$gradedstates = get_records_sql($sql);
// loop through all questions and set the last_graded states
foreach ($ids as $i) {
if (isset($states[$i])) {
restore_question_state($questions[$i], $states[$i]);
if (isset($gradedstates[$i])) {
restore_question_state($questions[$i], $gradedstates[$i]);
$states[$i]->last_graded = $gradedstates[$i];
} else {
$states[$i]->last_graded = clone($states[$i]);
}
} else {
// create a new empty state
$states[$i] = new object;
$states[$i]->attempt = $attempt->uniqueid;
$states[$i]->question = (int) $i;
$states[$i]->seq_number = 0;
$states[$i]->timestamp = $attempt->timestart;
$states[$i]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN;
$states[$i]->grade = 0;
$states[$i]->raw_grade = 0;
$states[$i]->penalty = 0;
$states[$i]->sumpenalty = 0;
$states[$i]->comment = '';
$states[$i]->responses = array('' => '');
// Prevent further changes to the session from incrementing the
// sequence number
$states[$i]->changed = true;
// Create the empty question type specific information
if (!$QTYPES[$questions[$i]->qtype]
->create_session_and_responses($questions[$i], $states[$i], $cmoptions, $attempt)) {
return false;
}
$states[$i]->last_graded = clone($states[$i]);
}
}
return $states;
}
/**
* Creates the run-time fields for the states
*
* Extends the state objects for a question by calling
* {@link restore_session_and_responses()}
* @return boolean Represents success or failure
* @param object $question The question for which the state is needed
* @param object $state The state as loaded from the database
*/
function restore_question_state(&$question, &$state) {
global $QTYPES;
// initialise response to the value in the answer field
$state->responses = array('' => $state->answer);
unset($state->answer);
// Set the changed field to false; any code which changes the
// question session must set this to true and must increment
// ->seq_number. The save_question_session
// function will save the new state object to the database if the field is
// set to true.
$state->changed = false;
// Load the question type specific data
return $QTYPES[$question->qtype]
->restore_session_and_responses($question, $state);
}
/**
* Saves the current state of the question session to the database
*
* The state object representing the current state of the session for the
* question is saved to the question_states table with ->responses[''] saved
* to the answer field of the database table. The information in the
* question_sessions table is updated.
* The question type specific data is then saved.
* @return mixed The id of the saved or updated state or false
* @param object $question The question for which session is to be saved.
* @param object $state The state information to be saved. In particular the
* most recent responses are in ->responses. The object
* is updated to hold the new ->id.
*/
function save_question_session(&$question, &$state) {
global $QTYPES;
// Check if the state has changed
if (!$state->changed && isset($state->id)) {
return $state->id;
}
// Set the legacy answer field
$state->answer = isset($state->responses['']) ? $state->responses[''] : '';
// Save the state
if (isset($state->update)) { // this forces the old state record to be overwritten
update_record('question_states', $state);
} else {
if (!$state->id = insert_record('question_states', $state)) {
unset($state->id);
unset($state->answer);
return false;
}
}
// create or update the session
if (!record_exists('question_sessions', 'attemptid',
$state->attempt, 'questionid', $question->id)) {
$new->attemptid = $state->attempt;
$new->questionid = $question->id;
$new->newest = $state->id;
$new->sumpenalty = $state->sumpenalty;
if (!insert_record('question_sessions', $new)) {
error('Could not insert entry in question_sessions');
}
} else {
set_field('question_sessions', 'newest', $state->id, 'attemptid',
$state->attempt, 'questionid', $question->id);
}
if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) {
// this state is graded or newly opened, so it goes into the lastgraded field as well
if ($newest = get_record('question_sessions', 'attemptid',
$state->attempt, 'questionid', $question->id)) {
$newest->newgraded = $state->id;
$newest->sumpenalty = $state->sumpenalty;
$newest->comment = $state->comment;
update_record('question_sessions', $newest);
}
}
unset($state->answer);
// Save the question type specific state information and responses
if (!$QTYPES[$question->qtype]->save_session_and_responses(
$question, $state)) {
return false;
}
// Reset the changed flag
$state->changed = false;
return $state->id;
}
/**
* Determines whether a state has been graded by looking at the event field
*
* @return boolean true if the state has been graded
* @param object $state
*/
function question_state_is_graded($state) {
return ($state->event == QUESTION_EVENTGRADE
or $state->event == QUESTION_EVENTCLOSEANDGRADE
or $state->event == QUESTION_EVENTMANUALGRADE);
}
/**
* Determines whether a state has been closed by looking at the event field
*
* @return boolean true if the state has been closed
* @param object $state
*/
function question_state_is_closed($state) {
return ($state->event == QUESTION_EVENTCLOSE
or $state->event == QUESTION_EVENTCLOSEANDGRADE
or $state->event == QUESTION_EVENTMANUALGRADE);
}
/**
* Extracts responses from submitted form
*
* This can extract the responses given to one or several questions present on a page
* It returns an array with one entry for each question, indexed by question id
* Each entry is an object with the properties
* ->event The event that has triggered the submission. This is determined by which button
* the user has pressed.
* ->responses An array holding the responses to an individual question, indexed by the
* name of the corresponding form element.
* ->timestamp A unix timestamp
* @return array array of action objects, indexed by question ids.
* @param array $questions an array containing at least all questions that are used on the form
* @param array $formdata the data submitted by the form on the question page
* @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
*/
function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) {
$time = time();
$actions = array();
foreach ($formdata as $key => $response) {
// Get the question id from the response name
if (false !== ($quid = question_get_id_from_name_prefix($key))) {
// check if this is a valid id
if (!isset($questions[$quid])) {
error('Form contained question that is not in questionids');
}
// Remove the name prefix from the name
//decrypt trying
$key = substr($key, strlen($questions[$quid]->name_prefix));
if (false === $key) {
$key = '';
}
// Check for question validate and mark buttons & set events
if ($key === 'validate') {
$actions[$quid]->event = QUESTION_EVENTVALIDATE;
} else if ($key === 'submit') {
$actions[$quid]->event = QUESTION_EVENTSUBMIT;
} else {
$actions[$quid]->event = $defaultevent;
}
// Update the state with the new response
$actions[$quid]->responses[$key] = $response;
// Set the timestamp
$actions[$quid]->timestamp = $time;
}
}
return $actions;
}
/**
* For a given question in an attempt we walk the complete history of states
* and recalculate the grades as we go along.
*
* This is used when a question is changed and old student
* responses need to be marked with the new version of a question.
*
* TODO: Make sure this is not quiz-specific
*
* @return boolean Indicates whether the grade has changed
* @param object $question A question object
* @param object $attempt The attempt, in which the question needs to be regraded.
* @param object $cmoptions
* @param boolean $verbose Optional. Whether to print progress information or not.
*/
function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
// load all states for this question in this attempt, ordered in sequence
if ($states = get_records_select('question_states',
"attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'", 'seq_number ASC')) {
$states = array_values($states);
// Subtract the grade for the latest state from $attempt->sumgrades to get the
// sumgrades for the attempt without this question.
$attempt->sumgrades -= $states[count($states)-1]->grade;
// Initialise the replaystate
$state = clone($states[0]);
restore_question_state($question, $state);
$state->sumpenalty = 0.0;
$replaystate = clone($state);
$replaystate->last_graded = $state;
$changed = false;
for($j = 1; $j < count($states); $j++) {
restore_question_state($question, $states[$j]);
$action = new stdClass;
$action->responses = $states[$j]->responses;
$action->timestamp = $states[$j]->timestamp;
// Change event to submit so that it will be reprocessed
if (QUESTION_EVENTCLOSE == $states[$j]->event
or QUESTION_EVENTGRADE == $states[$j]->event
or QUESTION_EVENTCLOSEANDGRADE == $states[$j]->event) {
$action->event = QUESTION_EVENTSUBMIT;
// By default take the event that was saved in the database
} else {
$action->event = $states[$j]->event;
}
// Reprocess (regrade) responses
if (!question_process_responses($question, $replaystate, $action, $cmoptions,
$attempt)) {
$verbose && notify("Couldn't regrade state #{$state->id}!");
}
// We need rounding here because grades in the DB get truncated
// e.g. 0.33333 != 0.3333333, but we want them to be equal here
if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5))
or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5))
or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) {
$changed = true;
}
$replaystate->id = $states[$j]->id;
$replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created
save_question_session($question, $replaystate);
}
if ($changed) {
update_record('quiz_attempts', $attempt);
}
return $changed;
}
return false;
}
/**
* Processes an array of student responses, grading and saving them as appropriate
*
* @return boolean Indicates success/failure
* @param object $question Full question object, passed by reference
* @param object $state Full state object, passed by reference
* @param object $action object with the fields ->responses which
* is an array holding the student responses,
* ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
* and ->timestamp which is a timestamp from when the responses
* were submitted by the student.
* @param object $cmoptions
* @param object $attempt The attempt is passed by reference so that
* during grading its ->sumgrades field can be updated
*/
function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
global $QTYPES;
// if no responses are set initialise to empty response
if (!isset($action->responses)) {
$action->responses = array('' => '');
}
// make sure these are gone!
unset($action->responses['submit'], $action->responses['validate']);
// Check the question session is still open
if (question_state_is_closed($state)) {
return true;
}
// If $action->event is not set that implies saving
if (! isset($action->event)) {
$action->event = QUESTION_EVENTSAVE;
}
// If submitted then compare against last graded
// responses, not last given responses in this case
if (question_isgradingevent($action->event)) {
$state->responses = $state->last_graded->responses;
}
// Check for unchanged responses (exactly unchanged, not equivalent).
// We also have to catch questions that the student has not yet attempted
$sameresponses = (($state->responses == $action->responses) or
($state->responses == array(''=>'') && array_keys(array_count_values($action->responses))===array('')));
// If the response has not been changed then we do not have to process it again
// unless the attempt is closing or validation is requested
if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
and QUESTION_EVENTVALIDATE != $action->event) {
return true;
}
// Roll back grading information to last graded state and set the new
// responses
$newstate = clone($state->last_graded);
$newstate->responses = $action->responses;
$newstate->seq_number = $state->seq_number + 1;
$newstate->changed = true; // will assure that it gets saved to the database
$newstate->last_graded = $state->last_graded;
$newstate->timestamp = $action->timestamp;
$state = $newstate;
// Set the event to the action we will perform. The question type specific
// grading code may override this by setting it to QUESTION_EVENTCLOSE if the
// attempt at the question causes the session to close
$state->event = $action->event;
if (!question_isgradingevent($action->event)) {
// Grade the response but don't update the overall grade
$QTYPES[$question->qtype]->grade_responses(
$question, $state, $cmoptions);
// Don't allow the processing to change the event type
$state->event = $action->event;
} else if (QUESTION_EVENTSUBMIT == $action->event) {
// Work out if the current responses (or equivalent responses) were
// already given in
// a. the last graded attempt
// b. any other graded attempt
if($QTYPES[$question->qtype]->compare_responses(
$question, $state, $state->last_graded)) {
$state->event = QUESTION_EVENTDUPLICATE;
} else {
if ($cmoptions->optionflags & QUESTION_IGNORE_DUPRESP) {
/* Walk back through the previous graded states looking for
one where the responses are equivalent to the current
responses. If such a state is found, set the current grading
details to those of that state and set the event to
QUESTION_EVENTDUPLICATE */
question_search_for_duplicate_responses($question, $state);
}
}
// If we did not find a duplicate, perform grading
if (QUESTION_EVENTDUPLICATE != $state->event) {
// Decrease sumgrades by previous grade and then later add new grade
$attempt->sumgrades -= (float)$state->last_graded->grade;
$QTYPES[$question->qtype]->grade_responses(
$question, $state, $cmoptions);
// Calculate overall grade using correct penalty method
question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
// Update the last graded state (don't simplify!)
unset($state->last_graded);
$state->last_graded = clone($state);
unset($state->last_graded->changed);
$attempt->sumgrades += (float)$state->last_graded->grade;