Added a new entry to this file for Essay question type. I followed the format of...
[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
af3830ee 16class default_questiontype {
516cf3eb 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)) {
5433ee83 63 $question->name = substr(strip_tags($question->questiontext), 0, 15);
516cf3eb 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
4f48fb42 85 if (!update_record("question", $question)) {
516cf3eb 86 error("Could not update question!");
87 }
88 } else { // Question is a new one
89 $question->version = 1;
4f48fb42 90 if (!$question->id = insert_record("question", $question)) {
516cf3eb 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
dc1f00de 172 if (!$question->options->answers = get_records('question_answers', 'question',
516cf3eb 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 */
90c3f310 186 function delete_question($questionid) {
516cf3eb 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
dfa47f96 198 * assigned one number. The 'description' type, however does not use up a
516cf3eb 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
4f48fb42 243 // question_states table.
516cf3eb 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
4f48fb42 258 * field in the question_states table is restored to ->responses['']
516cf3eb 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
4f48fb42 281 * non-specific data for the state has already been saved in the question_states
516cf3eb 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,
4f48fb42 287 * it will already have been saved to the answer field of the question_states table.
516cf3eb 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.
516cf3eb 425 * @param object $question The question to be rendered. Question type
426 * specific information is included. The
427 * maximum possible grade is in ->maxgrade. The name
428 * prefix for any named elements is in ->name_prefix.
429 * @param object $state The state to render the question in. The grading
430 * information is in ->grade, ->raw_grade and
431 * ->penalty. The current responses are in
432 * ->responses. This is an associative array (or the
433 * empty string or null in the case of no responses
434 * submitted). The last graded state is in
435 * ->last_graded (hence the most recently graded
436 * responses are in ->last_graded->responses). The
437 * question type specific information is also
438 * included.
439 * @param integer $number The number for this question.
440 * @param object $cmoptions
441 * @param object $options An object describing the rendering options.
442 */
443 function print_question(&$question, &$state, $number, $cmoptions, $options) {
444 /* The default implementation should work for most question types
445 provided the member functions it calls are overridden where required.
37a12367 446 The layout is determined by the template question.html */
516cf3eb 447 global $CFG;
448
449 // For editing teachers print a link to an editing popup window
450 $editlink = '';
451 if (isteacheredit($cmoptions->course)) {
452 $stredit = get_string('edit');
453 $linktext = '<img src="'.$CFG->pixpath.'/t/edit.gif" border="0" alt="'.$stredit.'" />';
e586cfb4 454 $editlink = link_to_popup_window('/question/question.php?id='.$question->id, $stredit, $linktext, 450, 550, $stredit, '', true);
516cf3eb 455 }
456
457 $grade = '';
458 if ($question->maxgrade and $options->scores) {
6b11a0e8 459 if ($cmoptions->optionflags & QUESTION_ADAPTIVE) {
f30bbcaf 460 $grade = (!question_state_is_graded($state->last_graded)) ? '--/' : round($state->last_graded->grade, $cmoptions->decimalpoints).'/';
516cf3eb 461 }
462 $grade .= $question->maxgrade;
463 }
464
465 $history = '';
466 if(isset($options->history) and $options->history) {
467 if ($options->history == 'all') {
468 // show all states
4f48fb42 469 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number DESC');
516cf3eb 470 } else {
471 // show only graded states
f30bbcaf 472 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event IN (".QUESTION_EVENTGRADE.','.QUESTION_EVENTCLOSEANDGRADE.")", 'seq_number DESC');
516cf3eb 473 }
474 if (count($states) > 1) {
475 $strreviewquestion = get_string('reviewresponse', 'quiz');
476 unset($table);
477 $table->head = array (
478 get_string('numberabbr', 'quiz'),
479 get_string('action', 'quiz'),
480 get_string('response', 'quiz'),
481 get_string('time'),
482 get_string('score', 'quiz'),
483 get_string('penalty', 'quiz'),
484 get_string('grade', 'quiz'),
485 );
486 $table->align = array ('center', 'center', 'left', 'left', 'left', 'left', 'left');
487 $table->size = array ('', '', '', '', '', '', '');
488 $table->width = '100%';
489 foreach ($states as $st) {
490 $b = ($state->id == $st->id) ? '<b>' : '';
491 $be = ($state->id == $st->id) ? '</b>' : '';
492 $table->data[] = array (
e586cfb4 493 ($state->id == $st->id) ? '<b>'.$st->seq_number.'</b>' : link_to_popup_window ('/question/reviewquestion.php?state='.$st->id.'&amp;number='.$number, 'reviewquestion', $st->seq_number, 450, 650, $strreviewquestion, 'none', true),
516cf3eb 494 $b.get_string('event'.$st->event, 'quiz').$be,
495 $b.$this->response_summary($st).$be,
496 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
497 $b.round($st->raw_grade, $cmoptions->decimalpoints).$be,
498 $b.round($st->penalty, $cmoptions->decimalpoints).$be,
499 $b.round($st->grade, $cmoptions->decimalpoints).$be
500 );
501 }
502 $history = make_table($table);
503 }
504 }
e586cfb4 505 include "$CFG->dirroot/question/questiontypes/question.html";
516cf3eb 506 }
507
508
509 /**
510 * Prints the score obtained and maximum score available plus any penalty
511 * information
512 *
513 * This function prints a summary of the scoring in the most recently
514 * graded state (the question may not have been submitted for marking at
515 * the current state). The default implementation should be suitable for most
516 * question types.
517 * @param object $question The question for which the grading details are
518 * to be rendered. Question type specific information
519 * is included. The maximum possible grade is in
520 * ->maxgrade.
521 * @param object $state The state. In particular the grading information
522 * is in ->grade, ->raw_grade and ->penalty.
523 * @param object $cmoptions
524 * @param object $options An object describing the rendering options.
525 */
526 function print_question_grading_details(&$question, &$state, $cmoptions, $options) {
527 /* The default implementation prints the number of marks if no attempt
528 has been made. Otherwise it displays the grade obtained out of the
529 maximum grade available and a warning if a penalty was applied for the
530 attempt and displays the overall grade obtained counting all previous
531 responses (and penalties) */
532
f30bbcaf 533 if (QUESTION_EVENTDUPLICATE == $state->event) {
516cf3eb 534 echo ' ';
535 print_string('duplicateresponse', 'quiz');
536 }
537 if (!empty($question->maxgrade) && $options->scores) {
f30bbcaf 538 if (question_state_is_graded($state->last_graded)) {
516cf3eb 539 // Display the grading details from the last graded state
540 $grade->cur = round($state->last_graded->grade, $cmoptions->decimalpoints);
541 $grade->max = $question->maxgrade;
542 $grade->raw = round($state->last_graded->raw_grade, $cmoptions->decimalpoints);
543
544 // let student know wether the answer was correct
545 echo '<div class="correctness ';
546 if ($state->last_graded->raw_grade >= $question->maxgrade/1.01) { // We divide by 1.01 so that rounding errors dont matter.
547 echo ' correct">';
548 print_string('correct', 'quiz');
549 } else if ($state->last_graded->raw_grade > 0) {
550 echo ' partiallycorrect">';
551 print_string('partiallycorrect', 'quiz');
552 } else {
553 echo ' incorrect">';
554 print_string('incorrect', 'quiz');
555 }
556 echo '</div>';
557
558 echo '<div class="gradingdetails">';
559 // print grade for this submission
560 print_string('gradingdetails', 'quiz', $grade);
561 if ($cmoptions->penaltyscheme) {
562 // print details of grade adjustment due to penalties
563 if ($state->last_graded->raw_grade > $state->last_graded->grade){
564 print_string('gradingdetailsadjustment', 'quiz', $grade);
565 }
566 // print info about new penalty
567 // penalty is relevant only if the answer is not correct and further attempts are possible
f30bbcaf 568 if (($state->last_graded->raw_grade < $question->maxgrade) and (QUESTION_EVENTCLOSEANDGRADE !== $state->event)) {
516cf3eb 569 if ('' !== $state->last_graded->penalty && ((float)$state->last_graded->penalty) > 0.0) {
570 // A penalty was applied so display it
571 print_string('gradingdetailspenalty', 'quiz', $state->last_graded->penalty);
572 } else {
573 /* No penalty was applied even though the answer was
574 not correct (eg. a syntax error) so tell the student
575 that they were not penalised for the attempt */
576 print_string('gradingdetailszeropenalty', 'quiz');
577 }
578 }
579 }
580 echo '</div>';
581 }
582 }
583 }
584
585 /**
586 * Prints the main content of the question including any interactions
587 *
588 * This function prints the main content of the question including the
589 * interactions for the question in the state given. The last graded responses
590 * are printed or indicated and the current responses are selected or filled in.
591 * Any names (eg. for any form elements) are prefixed with $question->name_prefix.
592 * This method is called from the print_question method.
593 * @param object $question The question to be rendered. Question type
594 * specific information is included. The name
595 * prefix for any named elements is in ->name_prefix.
596 * @param object $state The state to render the question in. The grading
597 * information is in ->grade, ->raw_grade and
598 * ->penalty. The current responses are in
599 * ->responses. This is an associative array (or the
600 * empty string or null in the case of no responses
601 * submitted). The last graded state is in
602 * ->last_graded (hence the most recently graded
603 * responses are in ->last_graded->responses). The
604 * question type specific information is also
605 * included.
606 * The state is passed by reference because some adaptive
607 * questions may want to update it during rendering
608 * @param object $cmoptions
609 * @param object $options An object describing the rendering options.
610 */
611 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
612 /* This default implementation prints an error and must be overridden
613 by all question type implementations, unless the default implementation
614 of print_question has been overridden. */
615
616 notify('Error: Question formulation and input controls has not'
617 .' been implemented for question type '.$this->name());
618 }
619
620 /**
621 * Prints the submit button(s) for the question in the given state
622 *
623 * This function prints the submit button(s) for the question in the
624 * given state. The name of any button created will be prefixed with the
625 * unique prefix for the question in $question->name_prefix. The suffix
4dca7e51 626 * 'submit' is reserved for the single question submit button and the suffix
516cf3eb 627 * 'validate' is reserved for the single question validate button (for
628 * question types which support it). Other suffixes will result in a response
629 * of that name in $state->responses which the printing and grading methods
630 * can then use.
631 * @param object $question The question for which the submit button(s) are to
632 * be rendered. Question type specific information is
633 * included. The name prefix for any
634 * named elements is in ->name_prefix.
635 * @param object $state The state to render the buttons for. The
636 * question type specific information is also
637 * included.
638 * @param object $cmoptions
639 * @param object $options An object describing the rendering options.
640 */
641 function print_question_submit_buttons(&$question, &$state, $cmoptions, $options) {
642 /* The default implementation should be suitable for most question
643 types. It prints a mark button in the case where individual marking is
644 allowed. */
645
6b11a0e8 646 if (($cmoptions->optionflags & QUESTION_ADAPTIVE) and !$options->readonly) {
516cf3eb 647 echo '<input type="submit" name="';
648 echo $question->name_prefix;
4dca7e51 649 echo 'submit" value="';
516cf3eb 650 print_string('mark', 'quiz');
5bc57211 651 echo '" class="submit btn"';
652 echo ' />';
516cf3eb 653 }
654 }
655
656
657 /**
658 * Return a summary of the student response
659 *
660 * This function returns a short string of no more than a given length that
661 * summarizes the student's response in the given $state. This is used for
662 * example in the response history table
663 * @return string The summary of the student response
664 * @param object $state The state whose responses are to be summarized
665 * @param int $length The maximum length of the returned string
666 */
667 function response_summary($state, $length=80) {
668 // This should almost certainly be overridden
669 return substr($state->answer, 0, $length);
670 }
671
672 /**
673 * Renders the question for printing and returns the LaTeX source produced
674 *
675 * This function should render the question suitable for a printed problem
676 * or solution sheet in LaTeX and return the rendered output.
677 * @return string The LaTeX output.
678 * @param object $question The question to be rendered. Question type
679 * specific information is included.
680 * @param object $state The state to render the question in. The
681 * question type specific information is also
682 * included.
683 * @param object $cmoptions
684 * @param string $type Indicates if the question or the solution is to be
685 * rendered with the values 'question' and
686 * 'solution'.
687 */
688 function get_texsource(&$question, &$state, $cmoptions, $type) {
689 // The default implementation simply returns a string stating that
690 // the question is only available online.
691
692 return get_string('onlineonly', 'texsheet');
693 }
694
695 /**
696 * Compares two question states for equivalence of the student's responses
697 *
698 * The responses for the two states must be examined to see if they represent
699 * equivalent answers to the question by the student. This method will be
700 * invoked for each of the previous states of the question before grading
701 * occurs. If the student is found to have already attempted the question
702 * with equivalent responses then the attempt at the question is ignored;
703 * grading does not occur and the state does not change. Thus they are not
704 * penalized for this case.
705 * @return boolean
706 * @param object $question The question for which the states are to be
707 * compared. Question type specific information is
708 * included.
709 * @param object $state The state of the question. The responses are in
710 * ->responses.
711 * @param object $teststate The state whose responses are to be
712 * compared. The state will be of the same age or
713 * older than $state.
714 */
715 function compare_responses(&$question, $state, $teststate) {
716 // The default implementation performs a comparison of the response
717 // arrays. The ordering of the arrays does not matter.
718 // Question types may wish to override this (eg. to ignore trailing
719 // white space or to make "7.0" and "7" compare equal).
720 return $state->responses == $teststate->responses;
721 }
722
37a12367 723 /**
724 * Checks whether a response matches a given answer
725 *
726 * This method only applies to questions that use teacher-defined answers
727 *
728 * @return boolean
729 */
730 function test_response(&$question, &$state, $answer) {
731 $response = isset($state->responses['']) ? $state->responses[''] : '';
732 return ($response == $answer->answer);
733 }
734
516cf3eb 735 /**
736 * Performs response processing and grading
737 *
738 * This function performs response processing and grading and updates
739 * the state accordingly.
740 * @return boolean Indicates success or failure.
741 * @param object $question The question to be graded. Question type
742 * specific information is included.
743 * @param object $state The state of the question to grade. The current
744 * responses are in ->responses. The last graded state
745 * is in ->last_graded (hence the most recently graded
746 * responses are in ->last_graded->responses). The
747 * question type specific information is also
748 * included. The ->raw_grade and ->penalty fields
749 * must be updated. The method is able to
750 * close the question session (preventing any further
751 * attempts at this question) by setting
f30bbcaf 752 * $state->event to QUESTION_EVENTCLOSEANDGRADE
516cf3eb 753 * @param object $cmoptions
754 */
755 function grade_responses(&$question, &$state, $cmoptions) {
756 /* The default implementation uses the comparison method to check if
757 the responses given are equivalent to the responses for each answer
758 in turn and sets the marks and penalty accordingly. This works for the
759 most simple question types. */
760
761 $teststate = clone($state);
762 $teststate->raw_grade = 0;
763 foreach($question->options->answers as $answer) {
764 $teststate->responses[''] = $answer->answer;
765
766 if($this->compare_responses($question, $state, $teststate)) {
767 $state->raw_grade = min(max((float) $answer->fraction,
768 0.0), 1.0) * $question->maxgrade;
769 break;
770 }
771 }
772 if (empty($state->raw_grade)) {
773 $state->raw_grade = 0.0;
774 }
775 // Only allow one attempt at the question
776 $state->penalty = 1;
777
f30bbcaf 778 // mark the state as graded
779 $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
780
516cf3eb 781 return true;
782 }
783
784
785 /**
786 * Includes configuration settings for the question type on the quiz admin
787 * page
788 *
789 * Returns an array of objects describing the options for the question type
790 * to be included on the quiz module admin page.
791 * Configuration options can be included by setting the following fields in
792 * the object:
793 * ->name The name of the option within this question type.
794 * The full option name will be constructed as
795 * "quiz_{$this->name()}_$name", the human readable name
796 * will be displayed with get_string($name, 'quiz').
797 * ->code The code to display the form element, help button, etc.
798 * i.e. the content for the central table cell. Be sure
799 * to name the element "quiz_{$this->name()}_$name" and
800 * set the value to $CFG->{"quiz_{$this->name()}_$name"}.
801 * ->help Name of the string from the quiz module language file
802 * to be used for the help message in the third column of
803 * the table. An empty string (or the field not set)
804 * means to leave the box empty.
805 * Links to custom settings pages can be included by setting the following
806 * fields in the object:
807 * ->name The name of the link text string.
808 * get_string($name, 'quiz') will be called.
809 * ->link The filename part of the URL for the link. The full URL
810 * is contructed as
e586cfb4 811 * "$CFG->wwwroot/question/questiontypes/{$this->name()}/$link?sesskey=$sesskey"
516cf3eb 812 * [but with the relavant calls to the s and rawurlencode
813 * functions] where $sesskey is the sesskey for the user.
814 * @return array Array of objects describing the configuration options to
815 * be included on the quiz module admin page.
816 */
817 function get_config_options() {
818 // No options by default
819
820 return false;
821 }
822
823 /**
dc1f00de 824 * Returns true if the editing wizard is finished, false otherwise.
825 *
826 * The default implementation returns true, which is suitable for all question-
516cf3eb 827 * types that only use one editing form. This function is used in
828 * question.php to decide whether we can regrade any states of the edited
829 * question and redirect to edit.php.
830 *
831 * The dataset dependent question-type, which is extended by the calculated
832 * question-type, overwrites this method because it uses multiple pages (i.e.
833 * a wizard) to set up the question and associated datasets.
834 *
835 * @param object $form The data submitted by the previous page.
836 *
837 * @return boolean Whether the wizard's last page was submitted or not.
838 */
839 function finished_edit_wizard(&$form) {
840 //In the default case there is only one edit page.
841 return true;
842 }
843
dc1f00de 844 /**
845 * Prints a table of course modules in which the question is used
846 *
847 * This function is used near the end of the question edit forms in all question types
848 * It prints the table of quizzes in which the question is used
849 * containing checkboxes to allow the teacher to replace the old question version
850 *
851 * @param object $question
852 * @param object $course
853 * @param integer $cmid optional The id of the course module currently being edited
854 */
855 function print_replacement_options($question, $course, $cmid='0') {
516cf3eb 856
857 // Disable until the versioning code has been fixed
516cf3eb 858 return;
859
860 // no need to display replacement options if the question is new
861 if(empty($question->id)) {
862 return true;
863 }
864
865 // get quizzes using the question (using the question_instances table)
866 $quizlist = array();
867 if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) {
868 $instances = array();
869 }
870 foreach($instances as $instance) {
871 $quizlist[$instance->quiz] = $instance->quiz;
872 }
873 $quizlist = implode(',', $quizlist);
874 if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
875 $quizzes = array();
876 }
877
878 // do the printing
879 if(count($quizzes) > 0) {
880 // print the table
881 $strquizname = get_string('modulename', 'quiz');
882 $strdoreplace = get_string('replace', 'quiz');
883 $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
884 echo "<tr valign=\"top\">\n";
885 echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
886 echo "<td align=\"left\">\n";
887 echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
888 echo "<tr>\n";
889 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strquizname</th>\n";
890 echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$strdoreplace</th>\n";
891 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\">$straffectedstudents</th>\n";
892 echo "</tr>\n";
893 foreach($quizzes as $quiz) {
894 // work out whethere it should be checked by default
895 $checked = '';
dc1f00de 896 if((int)$cmid === (int)$quiz->id
516cf3eb 897 or empty($quiz->usercount)) {
898 $checked = "checked=\"checked\"";
899 }
900
901 // find how many different students have already attempted this quiz
902 $students = array();
903 if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
904 foreach($attempts as $attempt) {
4f48fb42 905 if (record_exists('question_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) {
516cf3eb 906 $students[$attempt->userid] = 1;
907 }
908 }
909 }
910 $studentcount = count($students);
911
912 $strstudents = $studentcount === 1 ? $course->student : $course->students;
913 echo "<tr>\n";
914 echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name)."</td>\n";
915 echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
916 echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ? $studentcount.' '.$strstudents : '-')."</td>\n";
917 echo "</tr>\n";
918 }
919 echo "</table>\n";
920 }
921 echo "</td></tr>\n";
922 }
923
924 function print_question_form_end($question, $submitscript='') {
925 // This function is used at the end of the question edit forms in all question types
926 // It prints the submit, copy, and cancel buttons and the standard hidden form fields
927 global $USER;
928 echo '<tr valign="top">
929 <td colspan="2" align="center">
930 <input type="submit" '.$submitscript.' value="'.get_string('savechanges').'" /> ';
931 if ($question->id) {
932// Switched off until bug 3445 is fixed
933// echo '<input type="submit" name="makecopy" '.$submitscript.' value="'.get_string("makecopy", "quiz").'" /> ';
934 }
935 echo '<input type="submit" name="cancel" value="'.get_string("cancel").'" />
936 <input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />
937 <input type="hidden" name="id" value="'.$question->id.'" />
938 <input type="hidden" name="qtype" value="'.$question->qtype.'" />';
939 // The following hidden field indicates that the versioning code should be turned on, i.e.,
940 // that old versions should be kept if necessary
941 echo '<input type="hidden" name="versioning" value="on" />
942 </td></tr>';
943 }
c5d94c41 944
945/// BACKUP FUNCTIONS ////////////////////////////
946
947 /*
948 * Backup the data in the question
949 *
950 * This is used in question/backuplib.php
951 */
952 function backup($bf,$preferences,$question,$level=6) {
953 // The default type has nothing to back up
954 return true;
955 }
956
315559d3 957/// RESTORE FUNCTIONS /////////////////
958
959 /*
960 * Restores the data in the question
961 *
962 * This is used in question/restorelib.php
963 */
964 function restore($old_question_id,$new_question_id,$info,$restore) {
965 // The default question type has nothing to restore
966 return true;
967 }
968
969 function restore_map($old_question_id,$new_question_id,$info,$restore) {
970 // There is nothing to decode
971 return true;
972 }
973
974 function restore_recode_answer($state, $restore) {
975 // There is nothing to decode
ba8f7ff0 976 return $state->answer;
315559d3 977 }
978
979 //This function restores the question_rqp_states
980 function restore_state($state_id,$info,$restore) {
981 // The default question type does not keep its own state information
982 return true;
983 }
516cf3eb 984
985}
986
987?>