mirrored from git://git.moodle.org/moodle.git
/
locallib.php
2438 lines (2179 loc) · 98.9 KB
/
locallib.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$
/**
* Library of functions used by the quiz module.
*
* This contains functions that are called from within the quiz module only
* Functions that are also called by core Moodle are in {@link lib.php}
* @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 quiz
*/
/**
* Include those library functions that are also used by core Moodle
*/
require_once("$CFG->dirroot/mod/quiz/lib.php");
/// CONSTANTS ///////////////////////////////////////////////////////////////////
/**#@+
* Options determining how the grades from individual attempts are combined to give
* the overall grade for a user
*/
define("QUIZ_GRADEHIGHEST", "1");
define("QUIZ_GRADEAVERAGE", "2");
define("QUIZ_ATTEMPTFIRST", "3");
define("QUIZ_ATTEMPTLAST", "4");
$QUIZ_GRADE_METHOD = array ( QUIZ_GRADEHIGHEST => get_string("gradehighest", "quiz"),
QUIZ_GRADEAVERAGE => get_string("gradeaverage", "quiz"),
QUIZ_ATTEMPTFIRST => get_string("attemptfirst", "quiz"),
QUIZ_ATTEMPTLAST => get_string("attemptlast", "quiz"));
/**#@-*/
/**#@+
* The different types of events that can create question states
*/
define('QUIZ_EVENTOPEN', '0');
define('QUIZ_EVENTNAVIGATE', '1');
define('QUIZ_EVENTSAVE', '2');
define('QUIZ_EVENTGRADE', '3');
define('QUIZ_EVENTDUPLICATEGRADE', '4');
define('QUIZ_EVENTVALIDATE', '5');
define('QUIZ_EVENTCLOSE', '6');
/**#@-*/
/**#@+
* The defined question types
*
* @todo It would be nicer to have a fully automatic plug-in system
*/
define("SHORTANSWER", "1");
define("TRUEFALSE", "2");
define("MULTICHOICE", "3");
define("RANDOM", "4");
define("MATCH", "5");
define("RANDOMSAMATCH", "6");
define("DESCRIPTION", "7");
define("NUMERICAL", "8");
define("MULTIANSWER", "9");
define("CALCULATED", "10");
define("RQP", "11");
/**#@-*/
/**
* Array of question types names translated to the user's language
*
* The $QUIZ_QUESTION_TYPE 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 $QUIZ_QTYPES}.
*/
// Note: Commented-out questiontypes are disabled, because they have not been
// upgraded to the new code yet.
$QUIZ_QUESTION_TYPE = array ( MULTICHOICE => get_string("multichoice", "quiz"),
TRUEFALSE => get_string("truefalse", "quiz"),
SHORTANSWER => get_string("shortanswer", "quiz"),
NUMERICAL => get_string("numerical", "quiz"),
CALCULATED => get_string("calculated", "quiz"),
MATCH => get_string("match", "quiz"),
DESCRIPTION => get_string("description", "quiz"),
RANDOMSAMATCH => get_string("randomsamatch", "quiz"),
MULTIANSWER => get_string("multianswer", "quiz"),
RQP => get_string("rqp", "quiz")
);
define("QUIZ_PICTURE_MAX_HEIGHT", "600"); // Not currently implemented
define("QUIZ_PICTURE_MAX_WIDTH", "600"); // Not currently implemented
define("QUIZ_MAX_NUMBER_ANSWERS", "10");
define("QUIZ_CATEGORIES_SORTORDER", "999");
/**
* Array holding question type objects
*/
$QUIZ_QTYPES= array();
/// Question type class //////////////////////////////////////////////
class quiz_default_questiontype {
/**
* Name of the question type
*
* The name returned should coincide with the name of the directory
* in which this questiontype is located
* @ return string
*/
function name() {
return 'default';
}
/**
* Checks whether a given file is used by a particular question
*
* This is used by {@see quizfile.php} to determine whether a file
* should be served to the user
* @return boolean
* @param question $question
* @param string $relativefilepath
*/
function uses_quizfile($question, $relativefilepath) {
// The default does only check whether the file is used as image:
return $question->image == $relativefilepath;
}
/**
* Saves or updates a question after editing by a teacher
*
* Given some question info and some data about the answers
* this function parses, organises and saves the question
* It is used by {@link question.php} when saving new data from
* a form, and also by {@link import.php} when importing questions
* This function in turn calls {@link save_question_options}
* to save question-type specific options
* @return object A {@link question} object
* @param object $question The question object which should be updated
* @param object $form The form submitted by the teacher
* @param object $course The course we are in
*/
function save_question($question, $form, $course) {
// This default implementation is suitable for most
// question types.
// First, save the basic question itself
$question->name = trim($form->name);
$question->questiontext = trim($form->questiontext);
$question->questiontextformat = $form->questiontextformat;
$question->parent = isset($form->parent)? $form->parent : 0;
$question->length = $this->actual_number_of_questions($question);
$question->penalty = isset($form->penalty) ? $form->penalty : 0;
if (empty($form->image)) {
$question->image = "";
} else {
$question->image = $form->image;
}
if (empty($question->name)) {
$question->name = strip_tags($question->questiontext);
if (empty($question->name)) {
$question->name = '-';
}
}
if ($question->penalty > 1 or $question->penalty < 0) {
$question->errors['penalty'] = get_string('invalidpenalty', 'quiz');
}
if (isset($form->defaultgrade)) {
$question->defaultgrade = $form->defaultgrade;
}
if (!empty($question->id)) { // Question already exists
$question->version ++; // Update version number of question
if (!update_record("quiz_questions", $question)) {
error("Could not update question!");
}
} else { // Question is a new one
$question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
$question->version = 1;
if (!$question->id = insert_record("quiz_questions", $question)) {
error("Could not insert new question!");
}
}
// Now to save all the answers and type-specific options
$form->id = $question->id;
$form->qtype = $question->qtype;
$form->category = $question->category;
$result = $this->save_question_options($form);
if (!empty($result->error)) {
error($result->error);
}
if (!empty($result->notice)) {
notice($result->notice, "question.php?id=$question->id");
}
if (!empty($result->noticeyesno)) {
notice_yesno($result->noticeyesno, "question.php?id=$question->id", "edit.php");
print_footer($course);
exit;
}
return $question;
}
/**
* Saves question-type specific options
*
* This is called by {@link save_question()} to save the question-type specific data
* @return object $result->error or $result->noticeyesno or $result->notice
* @param object $question This holds the information from the editing form,
* it is not a standard question object.
*/
function save_question_options($question) {
/// This default implementation must be overridden:
$result->error = "Unsupported question type ($question->qtype)!";
return $result;
}
/**
* Loads the question type specific options for the question.
*
* This function loads any question type specific options for the
* question from the database into the question object. This information
* is placed in the $question->options field. A question type is
* free, however, to decide on a internal structure of the options field.
* @return bool Indicates success or failure.
* @param object $question The question object for the question. This object
* should be updated to include the question type
* specific information (it is passed by reference).
*/
function get_question_options(&$question) {
if (!isset($question->options)) {
$question->options = new object;
}
// The default implementation attaches all answers for this question
if (!$question->options->answers = get_records('quiz_answers', 'question',
$question->id)) {
notify('Error: Missing question answers!');
return false;
}
return true;
}
/**
* Returns the number of question numbers which are used by the question
*
* This function returns the number of question numbers to be assigned
* to the question. Most question types will have length one; they will be
* assigned one number. The DESCRIPTION type, however does not use up a
* number and so has a length of zero. Other question types may wish to
* handle a bundle of questions and hence return a number greater than one.
* @return integer The number of question numbers which should be
* assigned to the question.
* @param object $question The question whose length is to be determined.
* Question type specific information is included.
*/
function actual_number_of_questions($question) {
// By default, each question is given one number
return 1;
}
/**
* Creates empty session and response information for the question
*
* This function is called to start a question session. Empty question type
* specific session data (if any) and empty response data will be added to the
* state object. Session data is any data which must persist throughout the
* quiz attempt possibly with updates as the user interacts with the
* question. This function does NOT create new entries in the database for
* the session; a call to the {@link save_session_and_responses} member will
* occur to do this.
* @return bool Indicates success or failure.
* @param object $question The question for which the session is to be
* created. Question type specific information is
* included.
* @param object $state The state to create the session for. Note that
* this will not have been saved in the database so
* there will be no id. This object will be updated
* to include the question type specific information
* (it is passed by reference). In particular, empty
* responses will be created in the ->responses
* field.
* @param object $quiz The quiz for which the session is to be started.
* Questions may wish to initialize the session in
* different ways depending on quiz settings.
* @param object $attempt The quiz attempt for which the session is to be
* started. Questions may wish to initialize the
* session in different ways depending on the user id
* or time available for the attempt.
*/
function create_session_and_responses(&$question, &$state, $quiz, $attempt) {
// The default implementation should work for the legacy question types.
// Most question types with only a single form field for the student's response
// will use the empty string '' as the index for that one response. This will
// automatically be stored in and restored from the answer field in the
// quiz_states table.
$state->responses = array('' => '');
return true;
}
/**
* Restores the session data and most recent responses for the given state
*
* This function loads any session data associated with the question
* session in the given state from the database into the state object.
* In particular it loads the responses that have been saved for the given
* state into the ->responses member of the state object.
*
* Question types with only a single form field for the student's response
* will not need not restore the responses; the value of the answer
* field in the quiz_states table is restored to ->responses['']
* before this function is called. Question types with more response fields
* should override this method and set the ->responses field to an
* associative array of responses.
* @return bool Indicates success or failure.
* @param object $question The question object for the question including any
* question type specific information.
* @param object $state The saved state to load the session for. This
* object should be updated to include the question
* type specific session information and responses
* (it is passed by reference).
*/
function restore_session_and_responses(&$question, &$state) {
// The default implementation does nothing (successfully)
return true;
}
/**
* Saves the session data and responses for the given question and state
*
* This function saves the question type specific session data from the
* state object to the database. In particular for most question types it saves the
* responses from the ->responses member of the state object. The question type
* non-specific data for the state has already been saved in the quiz_states
* table and the state object contains the corresponding id and
* sequence number which may be used to index a question type specific table.
*
* Question types with only a single form field for the student's response
* which is contained in ->responses[''] will not have to save this response,
* it will already have been saved to the answer field of the quiz_states table.
* Question types with more response fields should override this method and save
* the responses in their own database tables.
* @return bool Indicates success or failure.
* @param object $question The question object for the question including
* the question type specific information.
* @param object $state The state for which the question type specific
* data and responses should be saved.
*/
function save_session_and_responses(&$question, &$state) {
// The default implementation does nothing (successfully)
return true;
}
/**
* This function is obsolete. It is only used during the database
* upgrade
*/
function extract_response($rawresponse, $nameprefix) {
/// This function is obsolete. It is only used during the database
/// upgrade to version 2005030100 to extract the responses from the
/// legacy answers field. Question types written after this date do not
/// need to implement this member.
/// Returning a single value indicates that the value should remain
/// stored in the legacy answer field in the quiz_states table (was
/// quiz_responses).
/// Question types which implement their own response storage with
/// a question type specific table must return an associative array
/// of responses (without the name prefix) and in this case the update
/// script will call the save_session_and_responses member to save
/// the responses using the new mechanism.
/// Default behaviour that works for singleton response question types
/// like SHORTANSWER, NUMERICAL and TRUEFALSE and legacy question types
/// which have not changed their response storage model
return $rawresponse->answer;
}
/**
* Returns an array of values which will give full marks if graded as
* the $state->responses field
*
* The correct answer to the question in the given state, or an example of
* a correct answer if there are many, is returned. This is used by some question
* types in the {@link grade_responses()} function but it is also used by the
* question preview screen to fill in correct responses.
* @return mixed An array of values giving the responses corresponding
* to the (or a) correct answer to the question. If there is
* no correct answer that scores 100% then null is returned.
* @param object $question The question for which the correct answer is to
* be retrieved. Question type specific information is
* available.
* @param object $state The state of the question, for which a correct answer is
* needed. Question type specific information is included.
*/
function get_correct_responses(&$question, &$state) {
/* The default implementation returns the response for the first answer
that gives full marks. */
foreach ($question->options->answers as $answer) {
if (((int) $answer->fraction) === 1) {
return array('' => $answer->answer);
}
}
return null;
}
/**
* Prints the question including the number, grading details, content,
* feedback and interactions
*
* This function prints the question including the question number,
* grading details, content for the question, any feedback for the previously
* submitted responses and the interactions. The default implementation calls
* various other methods to print each of these parts and most question types
* will just override those methods.
* @todo Use CSS stylesheet
* @param object $question The question to be rendered. Question type
* specific information is included. The
* maximum possible grade is in ->maxgrade. The name
* prefix for any named elements is in ->name_prefix.
* @param object $state The state to render the question in. The grading
* information is in ->grade, ->raw_grade and
* ->penalty. The current responses are in
* ->responses. This is an associative array (or the
* empty string or null in the case of no responses
* submitted). 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.
* @param integer $number The number for this question.
* @param object $quiz The quiz to which the question belongs. The
* question will likely be rendered differently
* depending on the quiz settings.
* @param object $options An object describing the rendering options.
*/
function print_question(&$question, &$state, $number, $quiz, $options) {
/* The default implementation should work for most question types
provided the member functions it calls are overridden where required.
The question number is printed in the first cell of a table.
The main content is printed below in the top row of the second column
using {@link print_question_formulation_and_controls}.
The grading details are printed in the second row in the second column
using {@print_question_grading_details}.
The {@link print_question_submit_buttons} member is invoked to add a third
row containing the submit button(s) when $options->readonly is false. */
print_simple_box_start('center', '90%');
echo '<table width="100%" cellspacing="10"><tr>';
if ($options->readonly) {
echo '<td nowrap="nowrap" width="80" valign="top" rowspan="2">';
} else {
echo '<td nowrap="nowrap" width="80" valign="top" rowspan="3">';
}
// Print question number
echo '<b><font size="+1">' . $number . '</font></b>';
if (isteacher($quiz->course)) {
echo ' <font size="1">( ';
link_to_popup_window ('/mod/quiz/question.php?id=' . $question->id,
'editquestion', $question->id, 450, 550, get_string('edit'));
echo ')</font>';
}
if ($question->maxgrade and $options->scores) {
echo '<div class="grade">';
echo get_string('marks', 'quiz').': ';
if ($quiz->optionflags & QUIZ_ADAPTIVE) {
echo '<br />';
echo ('' === $state->last_graded->grade) ? '--/' : round($state->last_graded->grade, $quiz->decimalpoints).'/';
}
echo $question->maxgrade.'</div>';
}
echo '</td><td valign="top">';
$this->print_question_formulation_and_controls($question, $state,
$quiz, $options);
echo '</td></tr><tr><td valign="top">';
if ($question->maxgrade and $options->scores and ($quiz->optionflags & QUIZ_ADAPTIVE)) {
$this->print_question_grading_details($question, $state, $quiz, $options);
}
if (QUIZ_EVENTDUPLICATEGRADE == $state->event) {
echo ' ';
print_string('duplicateresponse', 'quiz');
}
if(!$options->readonly) {
echo '</td></tr><tr><td align="right">';
$this->print_question_submit_buttons($question, $state,
$quiz, $options);
}
if(isset($options->history) and $options->history) {
if ($options->history == 'all') {
// show all states
$states = get_records_select('quiz_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number DESC');
} else {
// show only graded states
$states = get_records_select('quiz_states', "attempt = '$state->attempt' AND question = '$question->id' AND event = '".QUIZ_EVENTGRADE."'", 'seq_number DESC');
}
if (count($states) > 1) {
$strreviewquestion = get_string('reviewresponse', 'quiz');
unset($table);
$table->head = array (
get_string('numberabbr', 'quiz'),
get_string('action', 'quiz'),
get_string('response', 'quiz'),
get_string('time'),
get_string('score', 'quiz'),
get_string('penalty', 'quiz'),
get_string('grade', 'quiz'),
);
$table->align = array ('center', 'center', 'left', 'left', 'left', 'left', 'left');
$table->size = array ('', '', '', '', '', '', '');
$table->width = '100%';
foreach ($states as $st) {
$b = ($state->id == $st->id) ? '<b>' : '';
$be = ($state->id == $st->id) ? '</b>' : '';
$table->data[] = array (
($state->id == $st->id) ? '<b>'.$st->seq_number.'</b>' : link_to_popup_window ('/mod/quiz/reviewquestion.php?state='.$st->id.'&number='.$number, 'reviewquestion', $st->seq_number, 450, 650, $strreviewquestion, 'none', true),
$b.get_string('event'.$st->event, 'quiz').$be,
$b.$this->response_summary($st).$be,
$b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
$b.round($st->raw_grade, $quiz->decimalpoints).$be,
$b.round($st->penalty, $quiz->decimalpoints).$be,
$b.round($st->grade, $quiz->decimalpoints).$be
);
}
echo '</td></tr><tr><td colspan="2" valign="top">';
print_table($table);
}
}
echo '</td></tr></table>';
print_simple_box_end();
}
/**
* Prints the score obtained and maximum score available plus any penalty
* information
*
* This function prints a summary of the scoring in the most recently
* graded state (the question may not have been submitted for marking at
* the current state). The default implementation should be suitable for most
* question types.
* @param object $question The question for which the grading details are
* to be rendered. Question type specific information
* is included. The maximum possible grade is in
* ->maxgrade.
* @param object $state The state. In particular the grading information
* is in ->grade, ->raw_grade and ->penalty.
* @param object $quiz The quiz to which the question belongs. The
* grading details may be rendered differently
* depending on the quiz settings.
* @param object $options An object describing the rendering options.
*/
function print_question_grading_details(&$question, &$state, $quiz, $options) {
/* The default implementation prints the number of marks if no attempt
has been made. Otherwise it displays the grade obtained out of the
maximum grade available and a warning if a penalty was applied for the
attempt and displays the overall grade obtained counting all previous
responses (and penalties) */
if (!empty($question->maxgrade)) {
if (!('' === $state->last_graded->grade)) {
// Display the grading details from the last graded state
$grade->cur = round($state->last_graded->grade, $quiz->decimalpoints);
$grade->max = $question->maxgrade;
$grade->raw = round($state->last_graded->raw_grade, $quiz->decimalpoints);
// let student know wether the answer was correct
echo '<div class="correctness">';
if ($state->last_graded->raw_grade >= $question->maxgrade) {
print_string('correct', 'quiz');
} else if ($state->last_graded->raw_grade > 0) {
print_string('partiallycorrect', 'quiz');
} else {
print_string('incorrect', 'quiz');
}
echo '</div>';
echo '<div class="gradingdetails">';
// print grade for this submission
print_string('gradingdetails', 'quiz', $grade);
// print details of grade adjustment due to penalties
if ($state->last_graded->raw_grade > $state->last_graded->grade){
print_string('gradingdetailsadjustment', 'quiz', $grade);
}
// print info about new penalty
// penalty is relevant only if the answer is not correct and further attempts are possible
if (($state->last_graded->raw_grade < $question->maxgrade) and (QUIZ_EVENTCLOSE !== $state->event)) {
if ('' !== $state->last_graded->penalty && ((float)$state->last_graded->penalty) > 0.0) {
// A penalty was applied so display it
print_string('gradingdetailspenalty', 'quiz', $state->last_graded->penalty);
} else {
/* No penalty was applied even though the answer was
not correct (eg. a syntax error) so tell the student
that they were not penalised for the attempt */
print_string('gradingdetailszeropenalty', 'quiz');
}
}
echo '</div>';
}
}
}
/**
* Prints the main content of the question including any interactions
*
* This function prints the main content of the question including the
* interactions for the question in the state given. The last graded responses
* are printed or indicated and the current responses are selected or filled in.
* Any names (eg. for any form elements) are prefixed with $question->name_prefix.
* This method is called from the print_question method.
* @param object $question The question to be rendered. Question type
* specific information is included. The name
* prefix for any named elements is in ->name_prefix.
* @param object $state The state to render the question in. The grading
* information is in ->grade, ->raw_grade and
* ->penalty. The current responses are in
* ->responses. This is an associative array (or the
* empty string or null in the case of no responses
* submitted). 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 state is passed by reference because some adaptive
* questions may want to update it during rendering
* @param object $quiz The quiz to which the question belongs. The
* question might be rendered differently
* depending on the quiz settings.
* @param object $options An object describing the rendering options.
*/
function print_question_formulation_and_controls(&$question, &$state, $quiz, $options) {
/* This default implementation prints an error and must be overridden
by all question type implementations, unless the default implementation
of print_question has been overridden. */
notify('Error: Question formulation and input controls has not'
.' been implemented for question type '.$this->name());
}
/**
* Prints the submit button(s) for the question in the given state
*
* This function prints the submit button(s) for the question in the
* given state. The name of any button created will be prefixed with the
* unique prefix for the question in $question->name_prefix. The suffix
* 'mark' is reserved for the single question mark button and the suffix
* 'validate' is reserved for the single question validate button (for
* question types which support it). Other suffixes will result in a response
* of that name in $state->responses which the printing and grading methods
* can then use.
* @param object $question The question for which the submit button(s) are to
* be rendered. Question type specific information is
* included. The name prefix for any
* named elements is in ->name_prefix.
* @param object $state The state to render the buttons for. The
* question type specific information is also
* included.
* @param object $quiz The quiz to which the question belongs. The
* choice of buttons may depend on the quiz
* settings.
* @param object $options An object describing the rendering options.
*/
function print_question_submit_buttons(&$question, &$state, $quiz, $options) {
/* The default implementation should be suitable for most question
types. It prints a mark button in the case where individual marking is
allowed in the quiz. */
if($quiz->optionflags & QUIZ_ADAPTIVE) {
echo '<input type="submit" name="';
echo $question->name_prefix;
echo 'mark" value="';
print_string('mark', 'quiz');
echo '" />';
}
}
/**
* Return a summary of the student response
*
* This function returns a short string of no more than a given length that
* summarizes the student's response in the given $state. This is used for
* example in the response history table
* @return string The summary of the student response
* @param object $state The state whose responses are to be summarized
* @param int $length The maximum length of the returned string
*/
function response_summary($state, $length=80) {
// This should almost certainly be overridden
return substr($state->answer, 0, $length);
}
/**
* Renders the question for printing and returns the LaTeX source produced
*
* This function should render the question suitable for a printed problem
* or solution sheet in LaTeX and return the rendered output.
* @return string The LaTeX output.
* @param object $question The question to be rendered. Question type
* specific information is included.
* @param object $state The state to render the question in. The
* question type specific information is also
* included.
* @param object $quiz The quiz to which the question belongs. The
* question will likely be rendered differently
* depending on the quiz settings.
* @param string $type Indicates if the question or the solution is to be
* rendered with the values 'question' and
* 'solution'.
*/
function get_texsource(&$question, &$state, $quiz, $type) {
// The default implementation simply returns a string stating that
// the question is only available online.
return get_string('onlineonly', 'texsheet');
}
/**
* Compares two question states for equivalence of the student's responses
*
* The responses for the two states must be examined to see if they represent
* equivalent answers to the question by the student. This method will be
* invoked for each of the previous states of the question before grading
* occurs. If the student is found to have already attempted the question
* with equivalent responses then the attempt at the question is ignored;
* grading does not occur and the state does not change. Thus they are not
* penalized for this case.
* @return boolean
* @param object $question The question for which the states are to be
* compared. Question type specific information is
* included.
* @param object $state The state of the question. The responses are in
* ->responses.
* @param object $teststate The state whose responses are to be
* compared. The state will be of the same age or
* older than $state.
*/
function compare_responses(&$question, $state, $teststate) {
// The default implementation performs a comparison of the response
// arrays. The ordering of the arrays does not matter.
// Question types may wish to override this (eg. to ignore trailing
// white space or to make "7.0" and "7" compare equal).
return $state->responses == $teststate->responses;
}
/**
* Performs response processing and grading
*
* 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 QUIZ_EVENTCLOSE.
* @param object $quiz The quiz to which the question belongs. The
* question might be graded differently depending on
* the quiz settings.
*/
function grade_responses(&$question, &$state, $quiz) {
/* The default implementation uses the comparison method to check if
the responses given are equivalent to the responses for each answer
in turn and sets the marks and penalty accordingly. This works for the
most simple question types. */
$teststate = clone($state);
foreach($question->options->answers as $answer) {
$teststate->responses[''] = $answer->answer;
if($this->compare_responses($question, $state, $teststate)) {
$state->raw_grade = min(max((float) $answer->fraction,
0.0), 1.0) * $question->maxgrade;
break;
}
}
if (empty($state->raw_grade)) {
$state->raw_grade = 0.0;
}
// Only allow one attempt at the question
$state->penalty = 1;
return true;
}
/**
* Includes configuration settings for the question type on the quiz admin
* page
*
* Returns an array of objects describing the options for the question type
* to be included on the quiz module admin page.
* Configuration options can be included by setting the following fields in
* the object:
* ->name The name of the option within this question type.
* The full option name will be constructed as
* "quiz_{$this->name()}_$name", the human readable name
* will be displayed with get_string($name, 'quiz').
* ->code The code to display the form element, help button, etc.
* i.e. the content for the central table cell. Be sure
* to name the element "quiz_{$this->name()}_$name" and
* set the value to $CFG->{"quiz_{$this->name()}_$name"}.
* ->help Name of the string from the quiz module language file
* to be used for the help message in the third column of
* the table. An empty string (or the field not set)
* means to leave the box empty.
* Links to custom settings pages can be included by setting the following
* fields in the object:
* ->name The name of the link text string.
* get_string($name, 'quiz') will be called.
* ->link The filename part of the URL for the link. The full URL
* is contructed as
* "$CFG->wwwroot/mod/quiz/questiontypes/{$this->name()}/$link?sesskey=$sesskey"
* [but with the relavant calls to the s and rawurlencode
* functions] where $sesskey is the sesskey for the user.
* @return array Array of objects describing the configuration options to
* be included on the quiz module admin page.
*/
function get_config_options() {
// No options by default
return false;
}
/**
* Returns true if the editing wizard is finished, false otherwise. The
* default implementation returns true, which is suitable for all question-
* types that only use one editing form. This function is used in
* question.php to decide whether we can regrade any states of the edited
* question and redirect to edit.php.
*
* The dataset dependent question-type, which is extended by the calculated
* question-type, overwrites this method because it uses multiple pages (i.e.
* a wizard) to set up the question and associated datasets.
*
* @param object $form The data submitted by the previous page.
*
* @return boolean Whether the wizard's last page was submitted or not.
*/
function finished_edit_wizard(&$form) {
//In the default case there is only one edit page.
return true;
}
function print_replacement_options($question, $course, $quizid='0') {
// This function is used near the end of the question edit forms in all question types
// It prints the table of quizzes in which the question is used
// containing checkboxes to allow the teacher to replace the old question version
// no need to display replacement options if the question is new
if(empty($question->id)) {
return true;
}
// get quizzes using the question (using the question_instances table)
$quizlist = array();
if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) {
$instances = array();
}
foreach($instances as $instance) {
$quizlist[$instance->quiz] = $instance->quiz;
}
$quizlist = implode(',', $quizlist);
if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
$quizzes = array();
}
// do the printing
if(count($quizzes) > 0) {
// print the table
$strquizname = get_string('modulename', 'quiz');
$strdoreplace = get_string('replace', 'quiz');
$straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
echo "<tr valign=\"top\">\n";
echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
echo "<td align=\"left\">\n";
echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
echo "<tr>\n";
echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strquizname</th>\n";
echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strdoreplace</th>\n";
echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$straffectedstudents</th>\n";
echo "</tr>\n";
foreach($quizzes as $quiz) {
// work out whethere it should be checked by default
$checked = '';
if((int)$quizid === (int)$quiz->id
or empty($quiz->usercount)) {
$checked = "checked=\"checked\"";
}
// find how many different students have already attempted this quiz
$students = array();
if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
foreach($attempts as $attempt) {
if (record_exists('quiz_states', 'attempt', $attempt->id, 'question', $question->id, 'originalquestion', 0)) {
$students[$attempt->userid] = 1;
}
}
}
$studentcount = count($students);
$strstudents = $studentcount === 1 ? $course->student : $course->students;
echo "<tr>\n";
echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name)."</td>\n";
echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ? $studentcount.' '.$strstudents : '-')."</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
echo "</td></tr>\n";
}
function print_question_form_end($question, $submitscript='') {
// This function is used at the end of the question edit forms in all question types
// It prints the submit, copy, and cancel buttons and the standard hidden form fields
global $USER;
echo '<tr valign="top">
<td colspan="2" align="center">
<input type="submit" '.$submitscript.' value="'.get_string('savechanges').'" /> ';
if ($question->id) {
echo '<input type="submit" name="makecopy" '.$submitscript.' value="'.get_string("makecopy", "quiz").'" /> ';
}
echo '<input type="submit" name="cancel" value="'.get_string("cancel").'" />
<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />
<input type="hidden" name="id" value="'.$question->id.'" />
<input type="hidden" name="qtype" value="'.$question->qtype.'" />';
// The following hidden field indicates that the versioning code should be turned on, i.e.,
// that old versions should be kept if necessary
echo '<input type="hidden" name="versioning" value="on" />
</td></tr>';
}
}
/// QUIZ_QTYPES INITIATION //////////////////
quiz_load_questiontypes();
/**
* Loads the questiontype.php file for each question type
*
* These files in turn instantiate the corresponding question type class
* and adds it to the $QUIZ_QTYPES array
*/
function quiz_load_questiontypes() {
global $QUIZ_QTYPES;
global $CFG;
$qtypenames= get_list_of_plugins('mod/quiz/questiontypes');
foreach($qtypenames as $qtypename) {
// Instanciates all plug-in question types
$qtypefilepath= "$CFG->dirroot/mod/quiz/questiontypes/$qtypename/questiontype.php";
// echo "Loading $qtypename<br/>"; // Uncomment for debugging
if (is_readable($qtypefilepath)) {
require_once($qtypefilepath);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
/// Any other quiz functions go here. Each of them must have a name that
/// starts with quiz_
/**