Moving quiz-independent question scripts to their new location. In a following commit...
[moodle.git] / question / questiontypes / questiontype.php
CommitLineData
516cf3eb 1<?php // $Id$
2/**
3* The default questiontype class.
4*
5* @version $Id$
6* @author Martin Dougiamas and many others. This has recently been completely
7* rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
8* the Serving Mathematics project
9* {@link http://maths.york.ac.uk/serving_maths}
10* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
11* @package quiz
12*/
13
14/// Question type class //////////////////////////////////////////////
15
16class quiz_default_questiontype {
17
18 /**
19 * Name of the question type
20 *
21 * The name returned should coincide with the name of the directory
22 * in which this questiontype is located
23 * @ return string
24 */
25 function name() {
26 return 'default';
27 }
28
29 /**
30 * Saves or updates a question after editing by a teacher
31 *
32 * Given some question info and some data about the answers
33 * this function parses, organises and saves the question
34 * It is used by {@link question.php} when saving new data from
35 * a form, and also by {@link import.php} when importing questions
36 * This function in turn calls {@link save_question_options}
37 * to save question-type specific options
38 * @return object A {@link question} object
39 * @param object $question The question object which should be updated
40 * @param object $form The form submitted by the teacher
41 * @param object $course The course we are in
42 */
43 function save_question($question, $form, $course) {
44 // This default implementation is suitable for most
45 // question types.
46
47 // First, save the basic question itself
48
49 $question->name = trim($form->name);
50 $question->questiontext = trim($form->questiontext);
51 $question->questiontextformat = $form->questiontextformat;
52 $question->parent = isset($form->parent)? $form->parent : 0;
53 $question->length = $this->actual_number_of_questions($question);
54 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
55
56 if (empty($form->image)) {
57 $question->image = "";
58 } else {
59 $question->image = $form->image;
60 }
61
62 if (empty($question->name)) {
63 $question->name = strip_tags($question->questiontext);
64 if (empty($question->name)) {
65 $question->name = '-';
66 }
67 }
68
69 if ($question->penalty > 1 or $question->penalty < 0) {
70 $question->errors['penalty'] = get_string('invalidpenalty', 'quiz');
71 }
72
73 if (isset($form->defaultgrade)) {
74 $question->defaultgrade = $form->defaultgrade;
75 }
76
77 // Set the unique code
78 // TODO: set the stamp to a hash of the questiondata so that identical
79 // questions will get the same stamp. That will elliminate possible
80 // duplication during backup when questions get changed without changes
81 $question->stamp = make_unique_id_code();
82
83 if (!empty($question->id)) { // Question already exists
84 $question->version ++; // Update version number of question
85 if (!update_record("quiz_questions", $question)) {
86 error("Could not update question!");
87 }
88 } else { // Question is a new one
89 $question->version = 1;
90 if (!$question->id = insert_record("quiz_questions", $question)) {
91 error("Could not insert new question!");
92 }
93 }
94
95 // Now to save all the answers and type-specific options
96
97 $form->id = $question->id;
98 $form->qtype = $question->qtype;
99 $form->category = $question->category;
100
101 $result = $this->save_question_options($form);
102
103 if (!empty($result->error)) {
104 error($result->error);
105 }
106
107 if (!empty($result->notice)) {
108 notice($result->notice, "question.php?id=$question->id");
109 }
110
111 if (!empty($result->noticeyesno)) {
112 notice_yesno($result->noticeyesno, "question.php?id=$question->id", "edit.php");
113 print_footer($course);
114 exit;
115 }
116
117 return $question;
118 }
119
120 /**
121 * Saves question-type specific options
122 *
123 * This is called by {@link save_question()} to save the question-type specific data
124 * @return object $result->error or $result->noticeyesno or $result->notice
125 * @param object $question This holds the information from the editing form,
126 * it is not a standard question object.
127 */
128 function save_question_options($question) {
129 /// This default implementation must be overridden:
130
131 $result->error = "Unsupported question type ($question->qtype)!";
132 return $result;
133 }
134
135 /**
136 * Changes all states for the given attempts over to a new question
137 *
138 * This is used by the versioning code if the teacher requests that a question
139 * gets replaced by the new version. In order for the attempts to be regraded
140 * properly all data in the states referring to the old question need to be
141 * changed to refer to the new version instead. In particular for question types
142 * that use the answers table the answers belonging to the old question have to
143 * be changed to those belonging to the new version.
144 *
145 * @param integer $oldquestionid The id of the old question
146 * @param object $newquestion The new question
147 * @param array $attempts An array of all attempt objects in whose states
148 * replacement should take place
149 */
150 function replace_question_in_attempts($oldquestionid, $newquestion, $attemtps) {
151 echo 'Not yet implemented';
152 return;
153 }
154
155 /**
156 * Loads the question type specific options for the question.
157 *
158 * This function loads any question type specific options for the
159 * question from the database into the question object. This information
160 * is placed in the $question->options field. A question type is
161 * free, however, to decide on a internal structure of the options field.
162 * @return bool Indicates success or failure.
163 * @param object $question The question object for the question. This object
164 * should be updated to include the question type
165 * specific information (it is passed by reference).
166 */
167 function get_question_options(&$question) {
168 if (!isset($question->options)) {
169 $question->options = new object;
170 }
171 // The default implementation attaches all answers for this question
172 if (!$question->options->answers = get_records('quiz_answers', 'question',
173 $question->id)) {
174 //notify('Error: Missing question answers!');
175 return false;
176 }
177 return true;
178 }
179
180 /**
181 * Deletes question from the question-type specific tables
182 *
183 * @return boolean Success/Failure
184 * @param object $question The question being deleted
185 */
186 function delete_question($question) {
187 /// The default question type does not have any tables of its own
188 // therefore there is nothing to delete
189
190 return true;
191 }
192
193 /**
194 * Returns the number of question numbers which are used by the question
195 *
196 * This function returns the number of question numbers to be assigned
197 * to the question. Most question types will have length one; they will be
198 * assigned one number. The DESCRIPTION type, however does not use up a
199 * number and so has a length of zero. Other question types may wish to
200 * handle a bundle of questions and hence return a number greater than one.
201 * @return integer The number of question numbers which should be
202 * assigned to the question.
203 * @param object $question The question whose length is to be determined.
204 * Question type specific information is included.
205 */
206 function actual_number_of_questions($question) {
207 // By default, each question is given one number
208 return 1;
209 }
210
211 /**
212 * Creates empty session and response information for the question
213 *
214 * This function is called to start a question session. Empty question type
215 * specific session data (if any) and empty response data will be added to the
216 * state object. Session data is any data which must persist throughout the
217 * attempt possibly with updates as the user interacts with the
218 * question. This function does NOT create new entries in the database for
219 * the session; a call to the {@link save_session_and_responses} member will
220 * occur to do this.
221 * @return bool Indicates success or failure.
222 * @param object $question The question for which the session is to be
223 * created. Question type specific information is
224 * included.
225 * @param object $state The state to create the session for. Note that
226 * this will not have been saved in the database so
227 * there will be no id. This object will be updated
228 * to include the question type specific information
229 * (it is passed by reference). In particular, empty
230 * responses will be created in the ->responses
231 * field.
232 * @param object $cmoptions
233 * @param object $attempt The attempt for which the session is to be
234 * started. Questions may wish to initialize the
235 * session in different ways depending on the user id
236 * or time available for the attempt.
237 */
238 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
239 // The default implementation should work for the legacy question types.
240 // Most question types with only a single form field for the student's response
241 // will use the empty string '' as the index for that one response. This will
242 // automatically be stored in and restored from the answer field in the
243 // quiz_states table.
244 $state->responses = array('' => '');
245 return true;
246 }
247
248 /**
249 * Restores the session data and most recent responses for the given state
250 *
251 * This function loads any session data associated with the question
252 * session in the given state from the database into the state object.
253 * In particular it loads the responses that have been saved for the given
254 * state into the ->responses member of the state object.
255 *
256 * Question types with only a single form field for the student's response
257 * will not need not restore the responses; the value of the answer
258 * field in the quiz_states table is restored to ->responses['']
259 * before this function is called. Question types with more response fields
260 * should override this method and set the ->responses field to an
261 * associative array of responses.
262 * @return bool Indicates success or failure.
263 * @param object $question The question object for the question including any
264 * question type specific information.
265 * @param object $state The saved state to load the session for. This
266 * object should be updated to include the question
267 * type specific session information and responses
268 * (it is passed by reference).
269 */
270 function restore_session_and_responses(&$question, &$state) {
271 // The default implementation does nothing (successfully)
272 return true;
273 }
274
275 /**
276 * Saves the session data and responses for the given question and state
277 *
278 * This function saves the question type specific session data from the
279 * state object to the database. In particular for most question types it saves the
280 * responses from the ->responses member of the state object. The question type
281 * non-specific data for the state has already been saved in the quiz_states
282 * table and the state object contains the corresponding id and
283 * sequence number which may be used to index a question type specific table.
284 *
285 * Question types with only a single form field for the student's response
286 * which is contained in ->responses[''] will not have to save this response,
287 * it will already have been saved to the answer field of the quiz_states table.
288 * Question types with more response fields should override this method and save
289 * the responses in their own database tables.
290 * @return bool Indicates success or failure.
291 * @param object $question The question object for the question including
292 * the question type specific information.
293 * @param object $state The state for which the question type specific
294 * data and responses should be saved.
295 */
296 function save_session_and_responses(&$question, &$state) {
297 // The default implementation does nothing (successfully)
298 return true;
299 }
300
301 /**
302 * Returns an array of values which will give full marks if graded as
303 * the $state->responses field
304 *
305 * The correct answer to the question in the given state, or an example of
306 * a correct answer if there are many, is returned. This is used by some question
307 * types in the {@link grade_responses()} function but it is also used by the
308 * question preview screen to fill in correct responses.
309 * @return mixed A response array giving the responses corresponding
310 * to the (or a) correct answer to the question. If there is
311 * no correct answer that scores 100% then null is returned.
312 * @param object $question The question for which the correct answer is to
313 * be retrieved. Question type specific information is
314 * available.
315 * @param object $state The state of the question, for which a correct answer is
316 * needed. Question type specific information is included.
317 */
318 function get_correct_responses(&$question, &$state) {
319 /* The default implementation returns the response for the first answer
320 that gives full marks. */
321 foreach ($question->options->answers as $answer) {
322 if (((int) $answer->fraction) === 1) {
323 return array('' => $answer->answer);
324 }
325 }
326 return null;
327 }
328
329 /**
330 * Return an array of values with the texts for all possible responses stored
331 * for the question
332 *
333 * All answers are found and their text values isolated
334 * @return object A mixed object
335 * ->id question id. Needed to manage random questions:
336 * it's the id of the actual question presented to user in a given attempt
337 * ->responses An array of values giving the responses corresponding
338 * to all answers to the question. Answer ids are used as keys.
339 * The text and partial credit are the object components
340 * @param object $question The question for which the answers are to
341 * be retrieved. Question type specific information is
342 * available.
343 */
344 // ULPGC ecastro
345 function get_all_responses(&$question, &$state) {
346 unset($answers);
347 if (is_array($question->options->answers)) {
348 foreach ($question->options->answers as $aid=>$answer) {
349 unset ($r);
350 $r->answer = $answer->answer;
351 $r->credit = $answer->fraction;
352 $answers[$aid] = $r;
353 }
354 } else {
355 $answers[]="error"; // just for debugging, eliminate
356 }
357 $result->id = $question->id;
358 $result->responses = $answers;
359 return $result;
360 }
361
362 /**
363 * Return the actual response to the question in a given state
364 * for the question
365 *
366 * @return mixed An array containing the response or reponses (multiple answer, match)
367 * given by the user in a particular attempt.
368 * @param object $question The question for which the correct answer is to
369 * be retrieved. Question type specific information is
370 * available.
371 * @param object $state The state object that corresponds to the question,
372 * for which a correct answer is needed. Question
373 * type specific information is included.
374 */
375 // ULPGC ecastro
376 function get_actual_response(&$question, &$state) {
377 /* The default implementation only returns the raw ->responses.
378 may be overridden by each type*/
379 //unset($resp);
380 if (isset($state->responses)) {
381 return $state->responses;
382 } else {
383 return null;
384 }
385 }
386
387 // ULPGC ecastro
388 function get_fractional_grade(&$question, &$state) {
389 $maxgrade = $question->maxgrade;
390 $grade = $state->grade;
391 if ($maxgrade) {
392 return (float)($grade/$maxgrade);
393 } else {
394 return (float)$grade;
395 }
396 }
397
398
399 /**
400 * Checks if the response given is correct and returns the id
401 *
402 * @return int The ide number for the stored answer that matches the response
403 * given by the user in a particular attempt.
404 * @param object $question The question for which the correct answer is to
405 * be retrieved. Question type specific information is
406 * available.
407 * @param object $state The state object that corresponds to the question,
408 * for which a correct answer is needed. Question
409 * type specific information is included.
410 */
411 // ULPGC ecastro
412 function check_response(&$question, &$state){
413 return false;
414 }
415
416 /**
417 * Prints the question including the number, grading details, content,
418 * feedback and interactions
419 *
420 * This function prints the question including the question number,
421 * grading details, content for the question, any feedback for the previously
422 * submitted responses and the interactions. The default implementation calls
423 * various other methods to print each of these parts and most question types
424 * will just override those methods.
425 * @todo Use CSS stylesheet
426 * @param object $question The question to be rendered. Question type
427 * specific information is included. The
428 * maximum possible grade is in ->maxgrade. The name
429 * prefix for any named elements is in ->name_prefix.
430 * @param object $state The state to render the question in. The grading
431 * information is in ->grade, ->raw_grade and
432 * ->penalty. The current responses are in
433 * ->responses. This is an associative array (or the
434 * empty string or null in the case of no responses
435 * submitted). The last graded state is in
436 * ->last_graded (hence the most recently graded
437 * responses are in ->last_graded->responses). The
438 * question type specific information is also
439 * included.
440 * @param integer $number The number for this question.
441 * @param object $cmoptions
442 * @param object $options An object describing the rendering options.
443 */
444 function print_question(&$question, &$state, $number, $cmoptions, $options) {
445 /* The default implementation should work for most question types
446 provided the member functions it calls are overridden where required.
447 The question number is printed in the first cell of a table.
448
449 The main content is printed below in the top row of the second column
450 using {@link print_question_formulation_and_controls}.
451 The grading details are printed in the second row in the second column
452 using {@print_question_grading_details}.
453 The {@link print_question_submit_buttons} member is invoked to add a third
454 row containing the submit button(s) when $options->readonly is false. */
455 global $CFG;
456
457 // For editing teachers print a link to an editing popup window
458 $editlink = '';
459 if (isteacheredit($cmoptions->course)) {
460 $stredit = get_string('edit');
461 $linktext = '<img src="'.$CFG->pixpath.'/t/edit.gif" border="0" alt="'.$stredit.'" />';
462 $editlink = link_to_popup_window('/mod/quiz/question.php?id='.$question->id, $stredit, $linktext, 450, 550, $stredit, '', true);
463 }
464
465 $grade = '';
466 if ($question->maxgrade and $options->scores) {
467 if ($cmoptions->optionflags & QUIZ_ADAPTIVE) {
468 $grade = (!$state->last_graded->event == QUIZ_EVENTGRADE) ? '--/' : round($state->last_graded->grade, $cmoptions->decimalpoints).'/';
469 }
470 $grade .= $question->maxgrade;
471 }
472
473 $history = '';
474 if(isset($options->history) and $options->history) {
475 if ($options->history == 'all') {
476 // show all states
477 $states = get_records_select('quiz_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number DESC');
478 } else {
479 // show only graded states
480 $states = get_records_select('quiz_states', "attempt = '$state->attempt' AND question = '$question->id' AND event = '".QUIZ_EVENTGRADE."'", 'seq_number DESC');
481 }
482 if (count($states) > 1) {
483 $strreviewquestion = get_string('reviewresponse', 'quiz');
484 unset($table);
485 $table->head = array (
486 get_string('numberabbr', 'quiz'),
487 get_string('action', 'quiz'),
488 get_string('response', 'quiz'),
489 get_string('time'),
490 get_string('score', 'quiz'),
491 get_string('penalty', 'quiz'),
492 get_string('grade', 'quiz'),
493 );
494 $table->align = array ('center', 'center', 'left', 'left', 'left', 'left', 'left');
495 $table->size = array ('', '', '', '', '', '', '');
496 $table->width = '100%';
497 foreach ($states as $st) {
498 $b = ($state->id == $st->id) ? '<b>' : '';
499 $be = ($state->id == $st->id) ? '</b>' : '';
500 $table->data[] = array (
501 ($state->id == $st->id) ? '<b>'.$st->seq_number.'</b>' : link_to_popup_window ('/mod/quiz/reviewquestion.php?state='.$st->id.'&amp;number='.$number, 'reviewquestion', $st->seq_number, 450, 650, $strreviewquestion, 'none', true),
502 $b.get_string('event'.$st->event, 'quiz').$be,
503 $b.$this->response_summary($st).$be,
504 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
505 $b.round($st->raw_grade, $cmoptions->decimalpoints).$be,
506 $b.round($st->penalty, $cmoptions->decimalpoints).$be,
507 $b.round($st->grade, $cmoptions->decimalpoints).$be
508 );
509 }
510 $history = make_table($table);
511 }
512 }
513 include "$CFG->dirroot/mod/quiz/questiontypes/question.html";
514 }
515
516
517 /**
518 * Prints the score obtained and maximum score available plus any penalty
519 * information
520 *
521 * This function prints a summary of the scoring in the most recently
522 * graded state (the question may not have been submitted for marking at
523 * the current state). The default implementation should be suitable for most
524 * question types.
525 * @param object $question The question for which the grading details are
526 * to be rendered. Question type specific information
527 * is included. The maximum possible grade is in
528 * ->maxgrade.
529 * @param object $state The state. In particular the grading information
530 * is in ->grade, ->raw_grade and ->penalty.
531 * @param object $cmoptions
532 * @param object $options An object describing the rendering options.
533 */
534 function print_question_grading_details(&$question, &$state, $cmoptions, $options) {
535 /* The default implementation prints the number of marks if no attempt
536 has been made. Otherwise it displays the grade obtained out of the
537 maximum grade available and a warning if a penalty was applied for the
538 attempt and displays the overall grade obtained counting all previous
539 responses (and penalties) */
540
541 if (QUIZ_EVENTDUPLICATEGRADE == $state->event) {
542 echo ' ';
543 print_string('duplicateresponse', 'quiz');
544 }
545 if (!empty($question->maxgrade) && $options->scores) {
546 if ($state->last_graded->event == QUIZ_EVENTGRADE) {
547 // Display the grading details from the last graded state
548 $grade->cur = round($state->last_graded->grade, $cmoptions->decimalpoints);
549 $grade->max = $question->maxgrade;
550 $grade->raw = round($state->last_graded->raw_grade, $cmoptions->decimalpoints);
551
552 // let student know wether the answer was correct
553 echo '<div class="correctness ';
554 if ($state->last_graded->raw_grade >= $question->maxgrade/1.01) { // We divide by 1.01 so that rounding errors dont matter.
555 echo ' correct">';
556 print_string('correct', 'quiz');
557 } else if ($state->last_graded->raw_grade > 0) {
558 echo ' partiallycorrect">';
559 print_string('partiallycorrect', 'quiz');
560 } else {
561 echo ' incorrect">';
562 print_string('incorrect', 'quiz');
563 }
564 echo '</div>';
565
566 echo '<div class="gradingdetails">';
567 // print grade for this submission
568 print_string('gradingdetails', 'quiz', $grade);
569 if ($cmoptions->penaltyscheme) {
570 // print details of grade adjustment due to penalties
571 if ($state->last_graded->raw_grade > $state->last_graded->grade){
572 print_string('gradingdetailsadjustment', 'quiz', $grade);
573 }
574 // print info about new penalty
575 // penalty is relevant only if the answer is not correct and further attempts are possible
576 if (($state->last_graded->raw_grade < $question->maxgrade) and (QUIZ_EVENTCLOSE !== $state->event)) {
577 if ('' !== $state->last_graded->penalty && ((float)$state->last_graded->penalty) > 0.0) {
578 // A penalty was applied so display it
579 print_string('gradingdetailspenalty', 'quiz', $state->last_graded->penalty);
580 } else {
581 /* No penalty was applied even though the answer was
582 not correct (eg. a syntax error) so tell the student
583 that they were not penalised for the attempt */
584 print_string('gradingdetailszeropenalty', 'quiz');
585 }
586 }
587 }
588 echo '</div>';
589 }
590 }
591 }
592
593 /**
594 * Prints the main content of the question including any interactions
595 *
596 * This function prints the main content of the question including the
597 * interactions for the question in the state given. The last graded responses
598 * are printed or indicated and the current responses are selected or filled in.
599 * Any names (eg. for any form elements) are prefixed with $question->name_prefix.
600 * This method is called from the print_question method.
601 * @param object $question The question to be rendered. Question type
602 * specific information is included. The name
603 * prefix for any named elements is in ->name_prefix.
604 * @param object $state The state to render the question in. The grading
605 * information is in ->grade, ->raw_grade and
606 * ->penalty. The current responses are in
607 * ->responses. This is an associative array (or the
608 * empty string or null in the case of no responses
609 * submitted). The last graded state is in
610 * ->last_graded (hence the most recently graded
611 * responses are in ->last_graded->responses). The
612 * question type specific information is also
613 * included.
614 * The state is passed by reference because some adaptive
615 * questions may want to update it during rendering
616 * @param object $cmoptions
617 * @param object $options An object describing the rendering options.
618 */
619 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
620 /* This default implementation prints an error and must be overridden
621 by all question type implementations, unless the default implementation
622 of print_question has been overridden. */
623
624 notify('Error: Question formulation and input controls has not'
625 .' been implemented for question type '.$this->name());
626 }
627
628 /**
629 * Prints the submit button(s) for the question in the given state
630 *
631 * This function prints the submit button(s) for the question in the
632 * given state. The name of any button created will be prefixed with the
633 * unique prefix for the question in $question->name_prefix. The suffix
634 * 'mark' is reserved for the single question mark button and the suffix
635 * 'validate' is reserved for the single question validate button (for
636 * question types which support it). Other suffixes will result in a response
637 * of that name in $state->responses which the printing and grading methods
638 * can then use.
639 * @param object $question The question for which the submit button(s) are to
640 * be rendered. Question type specific information is
641 * included. The name prefix for any
642 * named elements is in ->name_prefix.
643 * @param object $state The state to render the buttons for. The
644 * question type specific information is also
645 * included.
646 * @param object $cmoptions
647 * @param object $options An object describing the rendering options.
648 */
649 function print_question_submit_buttons(&$question, &$state, $cmoptions, $options) {
650 /* The default implementation should be suitable for most question
651 types. It prints a mark button in the case where individual marking is
652 allowed. */
653
654 if (($cmoptions->optionflags & QUIZ_ADAPTIVE) and !$options->readonly) {
655 echo '<input type="submit" name="';
656 echo $question->name_prefix;
657 echo 'mark" value="';
658 print_string('mark', 'quiz');
659 echo '" />';
660 }
661 }
662
663
664 /**
665 * Return a summary of the student response
666 *
667 * This function returns a short string of no more than a given length that
668 * summarizes the student's response in the given $state. This is used for
669 * example in the response history table
670 * @return string The summary of the student response
671 * @param object $state The state whose responses are to be summarized
672 * @param int $length The maximum length of the returned string
673 */
674 function response_summary($state, $length=80) {
675 // This should almost certainly be overridden
676 return substr($state->answer, 0, $length);
677 }
678
679 /**
680 * Renders the question for printing and returns the LaTeX source produced
681 *
682 * This function should render the question suitable for a printed problem
683 * or solution sheet in LaTeX and return the rendered output.
684 * @return string The LaTeX output.
685 * @param object $question The question to be rendered. Question type
686 * specific information is included.
687 * @param object $state The state to render the question in. The
688 * question type specific information is also
689 * included.
690 * @param object $cmoptions
691 * @param string $type Indicates if the question or the solution is to be
692 * rendered with the values 'question' and
693 * 'solution'.
694 */
695 function get_texsource(&$question, &$state, $cmoptions, $type) {
696 // The default implementation simply returns a string stating that
697 // the question is only available online.
698
699 return get_string('onlineonly', 'texsheet');
700 }
701
702 /**
703 * Compares two question states for equivalence of the student's responses
704 *
705 * The responses for the two states must be examined to see if they represent
706 * equivalent answers to the question by the student. This method will be
707 * invoked for each of the previous states of the question before grading
708 * occurs. If the student is found to have already attempted the question
709 * with equivalent responses then the attempt at the question is ignored;
710 * grading does not occur and the state does not change. Thus they are not
711 * penalized for this case.
712 * @return boolean
713 * @param object $question The question for which the states are to be
714 * compared. Question type specific information is
715 * included.
716 * @param object $state The state of the question. The responses are in
717 * ->responses.
718 * @param object $teststate The state whose responses are to be
719 * compared. The state will be of the same age or
720 * older than $state.
721 */
722 function compare_responses(&$question, $state, $teststate) {
723 // The default implementation performs a comparison of the response
724 // arrays. The ordering of the arrays does not matter.
725 // Question types may wish to override this (eg. to ignore trailing
726 // white space or to make "7.0" and "7" compare equal).
727 return $state->responses == $teststate->responses;
728 }
729
730 /**
731 * Performs response processing and grading
732 *
733 * This function performs response processing and grading and updates
734 * the state accordingly.
735 * @return boolean Indicates success or failure.
736 * @param object $question The question to be graded. Question type
737 * specific information is included.
738 * @param object $state The state of the question to grade. The current
739 * responses are in ->responses. The last graded state
740 * is in ->last_graded (hence the most recently graded
741 * responses are in ->last_graded->responses). The
742 * question type specific information is also
743 * included. The ->raw_grade and ->penalty fields
744 * must be updated. The method is able to
745 * close the question session (preventing any further
746 * attempts at this question) by setting
747 * $state->event to QUIZ_EVENTCLOSE.
748 * @param object $cmoptions
749 */
750 function grade_responses(&$question, &$state, $cmoptions) {
751 /* The default implementation uses the comparison method to check if
752 the responses given are equivalent to the responses for each answer
753 in turn and sets the marks and penalty accordingly. This works for the
754 most simple question types. */
755
756 $teststate = clone($state);
757 $teststate->raw_grade = 0;
758 foreach($question->options->answers as $answer) {
759 $teststate->responses[''] = $answer->answer;
760
761 if($this->compare_responses($question, $state, $teststate)) {
762 $state->raw_grade = min(max((float) $answer->fraction,
763 0.0), 1.0) * $question->maxgrade;
764 break;
765 }
766 }
767 if (empty($state->raw_grade)) {
768 $state->raw_grade = 0.0;
769 }
770 // Only allow one attempt at the question
771 $state->penalty = 1;
772
773 return true;
774 }
775
776
777 /**
778 * Includes configuration settings for the question type on the quiz admin
779 * page
780 *
781 * Returns an array of objects describing the options for the question type
782 * to be included on the quiz module admin page.
783 * Configuration options can be included by setting the following fields in
784 * the object:
785 * ->name The name of the option within this question type.
786 * The full option name will be constructed as
787 * "quiz_{$this->name()}_$name", the human readable name
788 * will be displayed with get_string($name, 'quiz').
789 * ->code The code to display the form element, help button, etc.
790 * i.e. the content for the central table cell. Be sure
791 * to name the element "quiz_{$this->name()}_$name" and
792 * set the value to $CFG->{"quiz_{$this->name()}_$name"}.
793 * ->help Name of the string from the quiz module language file
794 * to be used for the help message in the third column of
795 * the table. An empty string (or the field not set)
796 * means to leave the box empty.
797 * Links to custom settings pages can be included by setting the following
798 * fields in the object:
799 * ->name The name of the link text string.
800 * get_string($name, 'quiz') will be called.
801 * ->link The filename part of the URL for the link. The full URL
802 * is contructed as
803 * "$CFG->wwwroot/mod/quiz/questiontypes/{$this->name()}/$link?sesskey=$sesskey"
804 * [but with the relavant calls to the s and rawurlencode
805 * functions] where $sesskey is the sesskey for the user.
806 * @return array Array of objects describing the configuration options to
807 * be included on the quiz module admin page.
808 */
809 function get_config_options() {
810 // No options by default
811
812 return false;
813 }
814
815 /**
816 * Returns true if the editing wizard is finished, false otherwise. The
817 * default implementation returns true, which is suitable for all question-
818 * types that only use one editing form. This function is used in
819 * question.php to decide whether we can regrade any states of the edited
820 * question and redirect to edit.php.
821 *
822 * The dataset dependent question-type, which is extended by the calculated
823 * question-type, overwrites this method because it uses multiple pages (i.e.
824 * a wizard) to set up the question and associated datasets.
825 *
826 * @param object $form The data submitted by the previous page.
827 *
828 * @return boolean Whether the wizard's last page was submitted or not.
829 */
830 function finished_edit_wizard(&$form) {
831 //In the default case there is only one edit page.
832 return true;
833 }
834
835 function print_replacement_options($question, $course, $quizid='0') {
836 // This function is used near the end of the question edit forms in all question types
837 // It prints the table of quizzes in which the question is used
838 // containing checkboxes to allow the teacher to replace the old question version
839
840 // Disable until the versioning code has been fixed
841 // The $quizid argument will become a $cmid
842 return;
843
844 // no need to display replacement options if the question is new
845 if(empty($question->id)) {
846 return true;
847 }
848
849 // get quizzes using the question (using the question_instances table)
850 $quizlist = array();
851 if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) {
852 $instances = array();
853 }
854 foreach($instances as $instance) {
855 $quizlist[$instance->quiz] = $instance->quiz;
856 }
857 $quizlist = implode(',', $quizlist);
858 if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
859 $quizzes = array();
860 }
861
862 // do the printing
863 if(count($quizzes) > 0) {
864 // print the table
865 $strquizname = get_string('modulename', 'quiz');
866 $strdoreplace = get_string('replace', 'quiz');
867 $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
868 echo "<tr valign=\"top\">\n";
869 echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
870 echo "<td align=\"left\">\n";
871 echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
872 echo "<tr>\n";
873 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strquizname</th>\n";
874 echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strdoreplace</th>\n";
875 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$straffectedstudents</th>\n";
876 echo "</tr>\n";
877 foreach($quizzes as $quiz) {
878 // work out whethere it should be checked by default
879 $checked = '';
880 if((int)$quizid === (int)$quiz->id
881 or empty($quiz->usercount)) {
882 $checked = "checked=\"checked\"";
883 }
884
885 // find how many different students have already attempted this quiz
886 $students = array();
887 if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
888 foreach($attempts as $attempt) {
889 if (record_exists('quiz_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) {
890 $students[$attempt->userid] = 1;
891 }
892 }
893 }
894 $studentcount = count($students);
895
896 $strstudents = $studentcount === 1 ? $course->student : $course->students;
897 echo "<tr>\n";
898 echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name)."</td>\n";
899 echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
900 echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ? $studentcount.' '.$strstudents : '-')."</td>\n";
901 echo "</tr>\n";
902 }
903 echo "</table>\n";
904 }
905 echo "</td></tr>\n";
906 }
907
908 function print_question_form_end($question, $submitscript='') {
909 // This function is used at the end of the question edit forms in all question types
910 // It prints the submit, copy, and cancel buttons and the standard hidden form fields
911 global $USER;
912 echo '<tr valign="top">
913 <td colspan="2" align="center">
914 <input type="submit" '.$submitscript.' value="'.get_string('savechanges').'" /> ';
915 if ($question->id) {
916// Switched off until bug 3445 is fixed
917// echo '<input type="submit" name="makecopy" '.$submitscript.' value="'.get_string("makecopy", "quiz").'" /> ';
918 }
919 echo '<input type="submit" name="cancel" value="'.get_string("cancel").'" />
920 <input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />
921 <input type="hidden" name="id" value="'.$question->id.'" />
922 <input type="hidden" name="qtype" value="'.$question->qtype.'" />';
923 // The following hidden field indicates that the versioning code should be turned on, i.e.,
924 // that old versions should be kept if necessary
925 echo '<input type="hidden" name="versioning" value="on" />
926 </td></tr>';
927 }
928
929}
930
931?>