New param type: PARAM_NUMBER, for floating point numbers.
[moodle.git] / question / type / 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
8d205441 12*//** */
516cf3eb 13
8d205441 14require_once($CFG->libdir . '/questionlib.php');
516cf3eb 15
32b0adfa 16/**
17 * This is the base class for Moodle question types.
18 *
19 * There are detailed comments on each method, explaining what the method is
20 * for, and the circumstances under which you might need to override it.
21 *
22 * Note: the questiontype API should NOT be considered stable yet. Very few
23 * question tyeps have been produced yet, so we do not yet know all the places
24 * where the current API is insufficient. I would rather learn from the
25 * experiences of the first few question type implementors, and improve the
26 * interface to meet their needs, rather the freeze the API prematurely and
27 * condem everyone to working round a clunky interface for ever afterwards.
28 */
af3830ee 29class default_questiontype {
516cf3eb 30
31 /**
a2156789 32 * Name of the question type
33 *
34 * The name returned should coincide with the name of the directory
35 * in which this questiontype is located
36 *
32b0adfa 37 * @return string the name of this question type.
a2156789 38 */
516cf3eb 39 function name() {
40 return 'default';
41 }
42
a2156789 43 /**
44 * The name this question should appear as in the create new question
45 * dropdown.
46 *
47 * @return mixed the desired string, or false to hide this question type in the menu.
48 */
49 function menu_name() {
50 $name = $this->name();
51 $menu_name = get_string($name, 'qtype_' . $name);
52 if ($menu_name[0] == '[') {
53 // Legacy behavior, if the string was not in the proper qtype_name
54 // language file, look it up in the quiz one.
55 $menu_name = get_string($this->name(), 'quiz');
56 }
57 return $menu_name;
58 }
59
60 /**
61 * @return boolean true if this question can only be graded manually.
62 */
63 function is_manual_graded() {
64 return false;
65 }
66
67 /**
68 * @return boolean true if this question type can be used by the random question type.
69 */
70 function is_usable_by_random() {
71 return true;
72 }
73
516cf3eb 74 /**
75 * Saves or updates a question after editing by a teacher
76 *
77 * Given some question info and some data about the answers
78 * this function parses, organises and saves the question
79 * It is used by {@link question.php} when saving new data from
80 * a form, and also by {@link import.php} when importing questions
81 * This function in turn calls {@link save_question_options}
82 * to save question-type specific options
32b0adfa 83 * @param object $question the question object which should be updated
84 * @param object $form the form submitted by the teacher
85 * @param object $course the course we are in
695d225c 86 * @return object On success, return the new question object. On failure,
87 * return an object as follows. If the error object has an errors field,
32b0adfa 88 * display that as an error message. Otherwise, the editing form will be
695d225c 89 * redisplayed with validation errors, from validation_errors field, which
90 * is itself an object, shown next to the form fields.
516cf3eb 91 */
92 function save_question($question, $form, $course) {
93 // This default implementation is suitable for most
94 // question types.
695d225c 95
516cf3eb 96 // First, save the basic question itself
516cf3eb 97 $question->name = trim($form->name);
98 $question->questiontext = trim($form->questiontext);
99 $question->questiontextformat = $form->questiontextformat;
100 $question->parent = isset($form->parent)? $form->parent : 0;
101 $question->length = $this->actual_number_of_questions($question);
102 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
103
104 if (empty($form->image)) {
105 $question->image = "";
106 } else {
107 $question->image = $form->image;
108 }
109
a4514d91 110 if (empty($form->generalfeedback)) {
111 $question->generalfeedback = '';
1b8a7434 112 } else {
a4514d91 113 $question->generalfeedback = trim($form->generalfeedback);
1b8a7434 114 }
115
516cf3eb 116 if (empty($question->name)) {
5433ee83 117 $question->name = substr(strip_tags($question->questiontext), 0, 15);
516cf3eb 118 if (empty($question->name)) {
119 $question->name = '-';
120 }
121 }
122
123 if ($question->penalty > 1 or $question->penalty < 0) {
124 $question->errors['penalty'] = get_string('invalidpenalty', 'quiz');
125 }
126
127 if (isset($form->defaultgrade)) {
128 $question->defaultgrade = $form->defaultgrade;
129 }
130
516cf3eb 131 if (!empty($question->id)) { // Question already exists
cbe20043 132 // keep existing unique stamp code
133 $question->stamp = get_field('question', 'stamp', 'id', $question->id);
4f48fb42 134 if (!update_record("question", $question)) {
516cf3eb 135 error("Could not update question!");
136 }
137 } else { // Question is a new one
cbe20043 138 // Set the unique code
139 $question->stamp = make_unique_id_code();
4f48fb42 140 if (!$question->id = insert_record("question", $question)) {
516cf3eb 141 error("Could not insert new question!");
142 }
143 }
144
145 // Now to save all the answers and type-specific options
146
6459b8fc 147 $form->id = $question->id;
148 $form->qtype = $question->qtype;
516cf3eb 149 $form->category = $question->category;
6459b8fc 150 $form->questiontext = $question->questiontext;
516cf3eb 151
152 $result = $this->save_question_options($form);
153
154 if (!empty($result->error)) {
155 error($result->error);
156 }
157
158 if (!empty($result->notice)) {
159 notice($result->notice, "question.php?id=$question->id");
160 }
161
162 if (!empty($result->noticeyesno)) {
25ee4157 163 notice_yesno($result->noticeyesno, "question.php?id=$question->id&amp;courseid={$course->id}",
164 "edit.php?courseid={$course->id}");
516cf3eb 165 print_footer($course);
166 exit;
167 }
168
cbe20043 169 // Give the question a unique version stamp determined by question_hash()
170 if (!set_field('question', 'version', question_hash($question), 'id', $question->id)) {
171 error('Could not update question version field');
172 }
173
516cf3eb 174 return $question;
175 }
695d225c 176
516cf3eb 177 /**
178 * Saves question-type specific options
179 *
180 * This is called by {@link save_question()} to save the question-type specific data
181 * @return object $result->error or $result->noticeyesno or $result->notice
182 * @param object $question This holds the information from the editing form,
183 * it is not a standard question object.
184 */
185 function save_question_options($question) {
4eda4eec 186 return null;
516cf3eb 187 }
188
189 /**
190 * Changes all states for the given attempts over to a new question
191 *
192 * This is used by the versioning code if the teacher requests that a question
193 * gets replaced by the new version. In order for the attempts to be regraded
194 * properly all data in the states referring to the old question need to be
195 * changed to refer to the new version instead. In particular for question types
196 * that use the answers table the answers belonging to the old question have to
197 * be changed to those belonging to the new version.
198 *
199 * @param integer $oldquestionid The id of the old question
200 * @param object $newquestion The new question
201 * @param array $attempts An array of all attempt objects in whose states
202 * replacement should take place
203 */
204 function replace_question_in_attempts($oldquestionid, $newquestion, $attemtps) {
205 echo 'Not yet implemented';
206 return;
207 }
208
209 /**
210 * Loads the question type specific options for the question.
211 *
212 * This function loads any question type specific options for the
213 * question from the database into the question object. This information
214 * is placed in the $question->options field. A question type is
215 * free, however, to decide on a internal structure of the options field.
216 * @return bool Indicates success or failure.
217 * @param object $question The question object for the question. This object
218 * should be updated to include the question type
219 * specific information (it is passed by reference).
220 */
221 function get_question_options(&$question) {
222 if (!isset($question->options)) {
223 $question->options = new object;
224 }
225 // The default implementation attaches all answers for this question
ed28abca 226 $question->options->answers = get_records('question_answers', 'question',
227 $question->id);
516cf3eb 228 return true;
229 }
230
231 /**
0429cd86 232 * Deletes states from the question-type specific tables
233 *
234 * @param string $stateslist Comma separated list of state ids to be deleted
235 */
236 function delete_states($stateslist) {
237 /// The default question type does not have any tables of its own
238 // therefore there is nothing to delete
239
240 return true;
241 }
242
243 /**
244 * Deletes a question from the question-type specific tables
516cf3eb 245 *
246 * @return boolean Success/Failure
247 * @param object $question The question being deleted
248 */
90c3f310 249 function delete_question($questionid) {
516cf3eb 250 /// The default question type does not have any tables of its own
251 // therefore there is nothing to delete
252
253 return true;
254 }
255
256 /**
257 * Returns the number of question numbers which are used by the question
258 *
259 * This function returns the number of question numbers to be assigned
260 * to the question. Most question types will have length one; they will be
dfa47f96 261 * assigned one number. The 'description' type, however does not use up a
516cf3eb 262 * number and so has a length of zero. Other question types may wish to
263 * handle a bundle of questions and hence return a number greater than one.
264 * @return integer The number of question numbers which should be
265 * assigned to the question.
266 * @param object $question The question whose length is to be determined.
267 * Question type specific information is included.
268 */
269 function actual_number_of_questions($question) {
270 // By default, each question is given one number
271 return 1;
272 }
273
274 /**
275 * Creates empty session and response information for the question
276 *
277 * This function is called to start a question session. Empty question type
278 * specific session data (if any) and empty response data will be added to the
279 * state object. Session data is any data which must persist throughout the
280 * attempt possibly with updates as the user interacts with the
281 * question. This function does NOT create new entries in the database for
282 * the session; a call to the {@link save_session_and_responses} member will
283 * occur to do this.
284 * @return bool Indicates success or failure.
285 * @param object $question The question for which the session is to be
286 * created. Question type specific information is
287 * included.
288 * @param object $state The state to create the session for. Note that
289 * this will not have been saved in the database so
290 * there will be no id. This object will be updated
291 * to include the question type specific information
292 * (it is passed by reference). In particular, empty
293 * responses will be created in the ->responses
294 * field.
295 * @param object $cmoptions
296 * @param object $attempt The attempt for which the session is to be
297 * started. Questions may wish to initialize the
298 * session in different ways depending on the user id
299 * or time available for the attempt.
300 */
301 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
302 // The default implementation should work for the legacy question types.
303 // Most question types with only a single form field for the student's response
304 // will use the empty string '' as the index for that one response. This will
305 // automatically be stored in and restored from the answer field in the
4f48fb42 306 // question_states table.
5a14d563 307 $state->responses = array(
308 '' => '',
309 );
516cf3eb 310 return true;
311 }
312
313 /**
314 * Restores the session data and most recent responses for the given state
315 *
316 * This function loads any session data associated with the question
317 * session in the given state from the database into the state object.
318 * In particular it loads the responses that have been saved for the given
319 * state into the ->responses member of the state object.
320 *
321 * Question types with only a single form field for the student's response
322 * will not need not restore the responses; the value of the answer
4f48fb42 323 * field in the question_states table is restored to ->responses['']
516cf3eb 324 * before this function is called. Question types with more response fields
325 * should override this method and set the ->responses field to an
326 * associative array of responses.
327 * @return bool Indicates success or failure.
328 * @param object $question The question object for the question including any
329 * question type specific information.
330 * @param object $state The saved state to load the session for. This
331 * object should be updated to include the question
332 * type specific session information and responses
333 * (it is passed by reference).
334 */
335 function restore_session_and_responses(&$question, &$state) {
336 // The default implementation does nothing (successfully)
337 return true;
338 }
339
340 /**
341 * Saves the session data and responses for the given question and state
342 *
343 * This function saves the question type specific session data from the
344 * state object to the database. In particular for most question types it saves the
345 * responses from the ->responses member of the state object. The question type
4f48fb42 346 * non-specific data for the state has already been saved in the question_states
516cf3eb 347 * table and the state object contains the corresponding id and
348 * sequence number which may be used to index a question type specific table.
349 *
350 * Question types with only a single form field for the student's response
351 * which is contained in ->responses[''] will not have to save this response,
4f48fb42 352 * it will already have been saved to the answer field of the question_states table.
516cf3eb 353 * Question types with more response fields should override this method and save
354 * the responses in their own database tables.
355 * @return bool Indicates success or failure.
356 * @param object $question The question object for the question including
357 * the question type specific information.
358 * @param object $state The state for which the question type specific
359 * data and responses should be saved.
360 */
361 function save_session_and_responses(&$question, &$state) {
362 // The default implementation does nothing (successfully)
363 return true;
364 }
365
366 /**
367 * Returns an array of values which will give full marks if graded as
368 * the $state->responses field
369 *
370 * The correct answer to the question in the given state, or an example of
371 * a correct answer if there are many, is returned. This is used by some question
372 * types in the {@link grade_responses()} function but it is also used by the
373 * question preview screen to fill in correct responses.
374 * @return mixed A response array giving the responses corresponding
375 * to the (or a) correct answer to the question. If there is
376 * no correct answer that scores 100% then null is returned.
377 * @param object $question The question for which the correct answer is to
378 * be retrieved. Question type specific information is
379 * available.
380 * @param object $state The state of the question, for which a correct answer is
381 * needed. Question type specific information is included.
382 */
383 function get_correct_responses(&$question, &$state) {
384 /* The default implementation returns the response for the first answer
385 that gives full marks. */
4eda4eec 386 if ($question->options->answers) {
387 foreach ($question->options->answers as $answer) {
388 if (((int) $answer->fraction) === 1) {
389 return array('' => $answer->answer);
390 }
516cf3eb 391 }
392 }
393 return null;
394 }
395
396 /**
397 * Return an array of values with the texts for all possible responses stored
398 * for the question
399 *
400 * All answers are found and their text values isolated
401 * @return object A mixed object
402 * ->id question id. Needed to manage random questions:
403 * it's the id of the actual question presented to user in a given attempt
404 * ->responses An array of values giving the responses corresponding
405 * to all answers to the question. Answer ids are used as keys.
406 * The text and partial credit are the object components
407 * @param object $question The question for which the answers are to
408 * be retrieved. Question type specific information is
409 * available.
410 */
411 // ULPGC ecastro
412 function get_all_responses(&$question, &$state) {
7baff8aa 413 if (isset($question->options->answers) && is_array($question->options->answers)) {
414 $answers = array();
516cf3eb 415 foreach ($question->options->answers as $aid=>$answer) {
7baff8aa 416 $r = new stdClass;
516cf3eb 417 $r->answer = $answer->answer;
418 $r->credit = $answer->fraction;
419 $answers[$aid] = $r;
420 }
7baff8aa 421 $result = new stdClass;
422 $result->id = $question->id;
423 $result->responses = $answers;
424 return $result;
516cf3eb 425 } else {
7baff8aa 426 return null;
516cf3eb 427 }
516cf3eb 428 }
429
430 /**
431 * Return the actual response to the question in a given state
432 * for the question
433 *
434 * @return mixed An array containing the response or reponses (multiple answer, match)
435 * given by the user in a particular attempt.
436 * @param object $question The question for which the correct answer is to
437 * be retrieved. Question type specific information is
438 * available.
439 * @param object $state The state object that corresponds to the question,
440 * for which a correct answer is needed. Question
441 * type specific information is included.
442 */
443 // ULPGC ecastro
8cc274de 444 function get_actual_response($question, $state) {
445 // change length to truncate responses here if you want
446 $lmax = 40;
447 if (!empty($state->responses)) {
448 $responses[] = (strlen($state->responses['']) > $lmax) ?
449 substr($state->responses[''], 0, $lmax).'...' : $state->responses[''];
450 } else {
451 $responses[] = '';
452 }
453 return $responses;
516cf3eb 454 }
455
456 // ULPGC ecastro
457 function get_fractional_grade(&$question, &$state) {
458 $maxgrade = $question->maxgrade;
459 $grade = $state->grade;
460 if ($maxgrade) {
461 return (float)($grade/$maxgrade);
462 } else {
463 return (float)$grade;
464 }
465 }
466
467
468 /**
469 * Checks if the response given is correct and returns the id
470 *
471 * @return int The ide number for the stored answer that matches the response
472 * given by the user in a particular attempt.
473 * @param object $question The question for which the correct answer is to
474 * be retrieved. Question type specific information is
475 * available.
476 * @param object $state The state object that corresponds to the question,
477 * for which a correct answer is needed. Question
478 * type specific information is included.
479 */
480 // ULPGC ecastro
481 function check_response(&$question, &$state){
482 return false;
483 }
484
485 /**
486 * Prints the question including the number, grading details, content,
487 * feedback and interactions
488 *
489 * This function prints the question including the question number,
490 * grading details, content for the question, any feedback for the previously
491 * submitted responses and the interactions. The default implementation calls
492 * various other methods to print each of these parts and most question types
493 * will just override those methods.
516cf3eb 494 * @param object $question The question to be rendered. Question type
495 * specific information is included. The
496 * maximum possible grade is in ->maxgrade. The name
497 * prefix for any named elements is in ->name_prefix.
498 * @param object $state The state to render the question in. The grading
499 * information is in ->grade, ->raw_grade and
500 * ->penalty. The current responses are in
501 * ->responses. This is an associative array (or the
502 * empty string or null in the case of no responses
503 * submitted). The last graded state is in
504 * ->last_graded (hence the most recently graded
505 * responses are in ->last_graded->responses). The
506 * question type specific information is also
507 * included.
508 * @param integer $number The number for this question.
509 * @param object $cmoptions
510 * @param object $options An object describing the rendering options.
511 */
512 function print_question(&$question, &$state, $number, $cmoptions, $options) {
513 /* The default implementation should work for most question types
514 provided the member functions it calls are overridden where required.
37a12367 515 The layout is determined by the template question.html */
1b8a7434 516
516cf3eb 517 global $CFG;
1b8a7434 518 $isgraded = question_state_is_graded($state->last_graded);
516cf3eb 519
647bcd41 520 // If this question is being shown in the context of a quiz
521 // get the context so we can determine whether some extra links
522 // should be shown. (Don't show these links during question preview.)
d758f1e2 523 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
647bcd41 524 if (!empty($cm->id)) {
525 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
ec6adca0 526 } else if (!empty($cm->course)) {
527 $context = get_context_instance(CONTEXT_COURSE, $cm->course);
647bcd41 528 } else {
ec6adca0 529 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
647bcd41 530 }
d758f1e2 531
516cf3eb 532 // For editing teachers print a link to an editing popup window
533 $editlink = '';
ec6adca0 534 if ($context && has_capability('moodle/question:manage', $context)) {
516cf3eb 535 $stredit = get_string('edit');
536 $linktext = '<img src="'.$CFG->pixpath.'/t/edit.gif" border="0" alt="'.$stredit.'" />';
ee6c9355 537 $editlink = link_to_popup_window('/question/question.php?inpopup=1&amp;id='.$question->id, 'editquestion', $linktext, 450, 550, $stredit, '', true);
516cf3eb 538 }
539
a4514d91 540 $generalfeedback = '';
541 if ($isgraded && $options->generalfeedback) {
542 $generalfeedback = $this->format_text($question->generalfeedback,
1b8a7434 543 $question->questiontextformat, $cmoptions);
544 }
545
516cf3eb 546 $grade = '';
547 if ($question->maxgrade and $options->scores) {
6b11a0e8 548 if ($cmoptions->optionflags & QUESTION_ADAPTIVE) {
1b8a7434 549 $grade = !$isgraded ? '--/' : round($state->last_graded->grade, $cmoptions->decimalpoints).'/';
516cf3eb 550 }
551 $grade .= $question->maxgrade;
552 }
b6e907a2 553
3e3e5a40 554 $comment = stripslashes($state->manualcomment);
b6e907a2 555 $commentlink = '';
5cf38a57 556
647bcd41 557 if (isset($options->questioncommentlink) && $context && has_capability('mod/quiz:grade', $context)) {
b6e907a2 558 $strcomment = get_string('commentorgrade', 'quiz');
097bd3f5 559 $commentlink = '<div class="commentlink">'.link_to_popup_window ($options->questioncommentlink.'?attempt='.$state->attempt.'&amp;question='.$question->id,
560 'commentquestion', $strcomment, 450, 650, $strcomment, 'none', true).'</div>';
b6e907a2 561 }
516cf3eb 562
fe9b5cfd 563 $history = $this->history($question, $state, $number, $cmoptions, $options);
564
aaae75b0 565 include "$CFG->dirroot/question/type/question.html";
fe9b5cfd 566 }
567
568 /*
569 * Print history of responses
570 *
571 * Used by print_question()
572 */
573 function history($question, $state, $number, $cmoptions, $options) {
516cf3eb 574 $history = '';
575 if(isset($options->history) and $options->history) {
576 if ($options->history == 'all') {
577 // show all states
755bddf1 578 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number ASC');
516cf3eb 579 } else {
580 // show only graded states
755bddf1 581 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event IN (".QUESTION_EVENTGRADE.','.QUESTION_EVENTCLOSEANDGRADE.")", 'seq_number ASC');
516cf3eb 582 }
583 if (count($states) > 1) {
584 $strreviewquestion = get_string('reviewresponse', 'quiz');
1b8a7434 585 $table = new stdClass;
516cf3eb 586 $table->width = '100%';
d57cf4c1 587 if ($options->scores) {
588 $table->head = array (
589 get_string('numberabbr', 'quiz'),
590 get_string('action', 'quiz'),
591 get_string('response', 'quiz'),
592 get_string('time'),
593 get_string('score', 'quiz'),
594 //get_string('penalty', 'quiz'),
595 get_string('grade', 'quiz'),
596 );
597 } else {
598 $table->head = array (
599 get_string('numberabbr', 'quiz'),
600 get_string('action', 'quiz'),
601 get_string('response', 'quiz'),
602 get_string('time'),
603 );
3925a20a 604 }
605
516cf3eb 606 foreach ($states as $st) {
0a5b58af 607 $st->responses[''] = $st->answer;
608 $this->restore_session_and_responses($question, $st);
516cf3eb 609 $b = ($state->id == $st->id) ? '<b>' : '';
610 $be = ($state->id == $st->id) ? '</b>' : '';
fe9b5cfd 611 if ($state->id == $st->id) {
612 $link = '<b>'.$st->seq_number.'</b>';
613 } else {
614 if(isset($options->questionreviewlink)) {
615 $link = link_to_popup_window ($options->questionreviewlink.'?state='.$st->id.'&amp;number='.$number,
616 'reviewquestion', $st->seq_number, 450, 650, $strreviewquestion, 'none', true);
617 } else {
618 $link = $st->seq_number;
619 }
620 }
d57cf4c1 621 if ($options->scores) {
622 $table->data[] = array (
623 $link,
624 $b.get_string('event'.$st->event, 'quiz').$be,
625 $b.$this->response_summary($question, $st).$be,
626 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
627 $b.round($st->raw_grade, $cmoptions->decimalpoints).$be,
628 //$b.round($st->penalty, $cmoptions->decimalpoints).$be,
629 $b.round($st->grade, $cmoptions->decimalpoints).$be
630 );
631 } else {
632 $table->data[] = array (
633 $link,
634 $b.get_string('event'.$st->event, 'quiz').$be,
635 $b.$this->response_summary($question, $st).$be,
636 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
637 );
638 }
516cf3eb 639 }
640 $history = make_table($table);
641 }
642 }
fe9b5cfd 643 return $history;
516cf3eb 644 }
645
646
647 /**
648 * Prints the score obtained and maximum score available plus any penalty
649 * information
650 *
651 * This function prints a summary of the scoring in the most recently
652 * graded state (the question may not have been submitted for marking at
653 * the current state). The default implementation should be suitable for most
654 * question types.
655 * @param object $question The question for which the grading details are
656 * to be rendered. Question type specific information
657 * is included. The maximum possible grade is in
658 * ->maxgrade.
659 * @param object $state The state. In particular the grading information
660 * is in ->grade, ->raw_grade and ->penalty.
661 * @param object $cmoptions
662 * @param object $options An object describing the rendering options.
663 */
664 function print_question_grading_details(&$question, &$state, $cmoptions, $options) {
665 /* The default implementation prints the number of marks if no attempt
666 has been made. Otherwise it displays the grade obtained out of the
667 maximum grade available and a warning if a penalty was applied for the
668 attempt and displays the overall grade obtained counting all previous
669 responses (and penalties) */
670
f30bbcaf 671 if (QUESTION_EVENTDUPLICATE == $state->event) {
516cf3eb 672 echo ' ';
673 print_string('duplicateresponse', 'quiz');
674 }
675 if (!empty($question->maxgrade) && $options->scores) {
f30bbcaf 676 if (question_state_is_graded($state->last_graded)) {
516cf3eb 677 // Display the grading details from the last graded state
1b8a7434 678 $grade = new stdClass;
516cf3eb 679 $grade->cur = round($state->last_graded->grade, $cmoptions->decimalpoints);
680 $grade->max = $question->maxgrade;
681 $grade->raw = round($state->last_graded->raw_grade, $cmoptions->decimalpoints);
682
683 // let student know wether the answer was correct
684 echo '<div class="correctness ';
685 if ($state->last_graded->raw_grade >= $question->maxgrade/1.01) { // We divide by 1.01 so that rounding errors dont matter.
686 echo ' correct">';
687 print_string('correct', 'quiz');
688 } else if ($state->last_graded->raw_grade > 0) {
689 echo ' partiallycorrect">';
690 print_string('partiallycorrect', 'quiz');
691 } else {
692 echo ' incorrect">';
693 print_string('incorrect', 'quiz');
694 }
695 echo '</div>';
696
697 echo '<div class="gradingdetails">';
698 // print grade for this submission
699 print_string('gradingdetails', 'quiz', $grade);
700 if ($cmoptions->penaltyscheme) {
701 // print details of grade adjustment due to penalties
702 if ($state->last_graded->raw_grade > $state->last_graded->grade){
2962ad61 703 echo ' ';
516cf3eb 704 print_string('gradingdetailsadjustment', 'quiz', $grade);
705 }
706 // print info about new penalty
707 // penalty is relevant only if the answer is not correct and further attempts are possible
f30bbcaf 708 if (($state->last_graded->raw_grade < $question->maxgrade) and (QUESTION_EVENTCLOSEANDGRADE !== $state->event)) {
516cf3eb 709 if ('' !== $state->last_graded->penalty && ((float)$state->last_graded->penalty) > 0.0) {
710 // A penalty was applied so display it
2962ad61 711 echo ' ';
516cf3eb 712 print_string('gradingdetailspenalty', 'quiz', $state->last_graded->penalty);
713 } else {
714 /* No penalty was applied even though the answer was
715 not correct (eg. a syntax error) so tell the student
716 that they were not penalised for the attempt */
2962ad61 717 echo ' ';
516cf3eb 718 print_string('gradingdetailszeropenalty', 'quiz');
719 }
720 }
721 }
722 echo '</div>';
723 }
724 }
725 }
726
727 /**
728 * Prints the main content of the question including any interactions
729 *
730 * This function prints the main content of the question including the
731 * interactions for the question in the state given. The last graded responses
732 * are printed or indicated and the current responses are selected or filled in.
733 * Any names (eg. for any form elements) are prefixed with $question->name_prefix.
734 * This method is called from the print_question method.
735 * @param object $question The question to be rendered. Question type
736 * specific information is included. The name
737 * prefix for any named elements is in ->name_prefix.
738 * @param object $state The state to render the question in. The grading
739 * information is in ->grade, ->raw_grade and
740 * ->penalty. The current responses are in
741 * ->responses. This is an associative array (or the
742 * empty string or null in the case of no responses
743 * submitted). The last graded state is in
744 * ->last_graded (hence the most recently graded
745 * responses are in ->last_graded->responses). The
746 * question type specific information is also
747 * included.
748 * The state is passed by reference because some adaptive
749 * questions may want to update it during rendering
750 * @param object $cmoptions
751 * @param object $options An object describing the rendering options.
752 */
753 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
754 /* This default implementation prints an error and must be overridden
755 by all question type implementations, unless the default implementation
756 of print_question has been overridden. */
757
758 notify('Error: Question formulation and input controls has not'
759 .' been implemented for question type '.$this->name());
760 }
761
762 /**
763 * Prints the submit button(s) for the question in the given state
764 *
765 * This function prints the submit button(s) for the question in the
766 * given state. The name of any button created will be prefixed with the
767 * unique prefix for the question in $question->name_prefix. The suffix
4dca7e51 768 * 'submit' is reserved for the single question submit button and the suffix
516cf3eb 769 * 'validate' is reserved for the single question validate button (for
770 * question types which support it). Other suffixes will result in a response
771 * of that name in $state->responses which the printing and grading methods
772 * can then use.
773 * @param object $question The question for which the submit button(s) are to
774 * be rendered. Question type specific information is
775 * included. The name prefix for any
776 * named elements is in ->name_prefix.
777 * @param object $state The state to render the buttons for. The
778 * question type specific information is also
779 * included.
780 * @param object $cmoptions
781 * @param object $options An object describing the rendering options.
782 */
783 function print_question_submit_buttons(&$question, &$state, $cmoptions, $options) {
784 /* The default implementation should be suitable for most question
785 types. It prints a mark button in the case where individual marking is
786 allowed. */
787
6b11a0e8 788 if (($cmoptions->optionflags & QUESTION_ADAPTIVE) and !$options->readonly) {
516cf3eb 789 echo '<input type="submit" name="';
790 echo $question->name_prefix;
4dca7e51 791 echo 'submit" value="';
516cf3eb 792 print_string('mark', 'quiz');
5bc57211 793 echo '" class="submit btn"';
794 echo ' />';
516cf3eb 795 }
796 }
797
798
799 /**
800 * Return a summary of the student response
801 *
802 * This function returns a short string of no more than a given length that
803 * summarizes the student's response in the given $state. This is used for
804 * example in the response history table
805 * @return string The summary of the student response
0a5b58af 806 * @param object $question
516cf3eb 807 * @param object $state The state whose responses are to be summarized
808 * @param int $length The maximum length of the returned string
809 */
0a5b58af 810 function response_summary($question, $state, $length=80) {
516cf3eb 811 // This should almost certainly be overridden
879caa51 812 $responses = $this->get_actual_response($question, $state);
813 if (empty($responses) || !is_array($responses)) {
814 $responses = array();
815 }
816 if (is_array($responses)) {
817 $responses = implode(',', $responses);
818 }
819 return substr($responses, 0, $length);
516cf3eb 820 }
821
822 /**
823 * Renders the question for printing and returns the LaTeX source produced
824 *
825 * This function should render the question suitable for a printed problem
826 * or solution sheet in LaTeX and return the rendered output.
827 * @return string The LaTeX output.
828 * @param object $question The question to be rendered. Question type
829 * specific information is included.
830 * @param object $state The state to render the question in. The
831 * question type specific information is also
832 * included.
833 * @param object $cmoptions
834 * @param string $type Indicates if the question or the solution is to be
835 * rendered with the values 'question' and
836 * 'solution'.
837 */
838 function get_texsource(&$question, &$state, $cmoptions, $type) {
839 // The default implementation simply returns a string stating that
840 // the question is only available online.
841
842 return get_string('onlineonly', 'texsheet');
843 }
844
845 /**
846 * Compares two question states for equivalence of the student's responses
847 *
848 * The responses for the two states must be examined to see if they represent
849 * equivalent answers to the question by the student. This method will be
850 * invoked for each of the previous states of the question before grading
851 * occurs. If the student is found to have already attempted the question
852 * with equivalent responses then the attempt at the question is ignored;
853 * grading does not occur and the state does not change. Thus they are not
854 * penalized for this case.
855 * @return boolean
856 * @param object $question The question for which the states are to be
857 * compared. Question type specific information is
858 * included.
859 * @param object $state The state of the question. The responses are in
ac249da5 860 * ->responses. This is the only field of $state
861 * that it is safe to use.
516cf3eb 862 * @param object $teststate The state whose responses are to be
863 * compared. The state will be of the same age or
bb080d20 864 * older than $state. If possible, the method should
865 * only use the field $teststate->responses, however
866 * any field that is set up by restore_session_and_responses
867 * can be used.
516cf3eb 868 */
869 function compare_responses(&$question, $state, $teststate) {
870 // The default implementation performs a comparison of the response
871 // arrays. The ordering of the arrays does not matter.
872 // Question types may wish to override this (eg. to ignore trailing
873 // white space or to make "7.0" and "7" compare equal).
6459b8fc 874
c82f76d0 875 return $state->responses === $teststate->responses;
516cf3eb 876 }
877
37a12367 878 /**
879 * Checks whether a response matches a given answer
880 *
881 * This method only applies to questions that use teacher-defined answers
882 *
883 * @return boolean
884 */
885 function test_response(&$question, &$state, $answer) {
886 $response = isset($state->responses['']) ? $state->responses[''] : '';
887 return ($response == $answer->answer);
888 }
889
516cf3eb 890 /**
891 * Performs response processing and grading
892 *
893 * This function performs response processing and grading and updates
894 * the state accordingly.
895 * @return boolean Indicates success or failure.
896 * @param object $question The question to be graded. Question type
897 * specific information is included.
898 * @param object $state The state of the question to grade. The current
899 * responses are in ->responses. The last graded state
900 * is in ->last_graded (hence the most recently graded
901 * responses are in ->last_graded->responses). The
902 * question type specific information is also
903 * included. The ->raw_grade and ->penalty fields
904 * must be updated. The method is able to
905 * close the question session (preventing any further
906 * attempts at this question) by setting
f30bbcaf 907 * $state->event to QUESTION_EVENTCLOSEANDGRADE
516cf3eb 908 * @param object $cmoptions
909 */
910 function grade_responses(&$question, &$state, $cmoptions) {
5a14d563 911 // The default implementation uses the test_response method to
912 // compare what the student entered against each of the possible
913 // answers stored in the question, and uses the grade from the
914 // first one that matches. It also sets the marks and penalty.
915 // This should be good enought for most simple question types.
516cf3eb 916
5a14d563 917 $state->raw_grade = 0;
516cf3eb 918 foreach($question->options->answers as $answer) {
5a14d563 919 if($this->test_response($question, $state, $answer)) {
920 $state->raw_grade = $answer->fraction;
516cf3eb 921 break;
922 }
923 }
5a14d563 924
925 // Make sure we don't assign negative or too high marks.
926 $state->raw_grade = min(max((float) $state->raw_grade,
927 0.0), 1.0) * $question->maxgrade;
928
929 // Update the penalty.
930 $state->penalty = $question->penalty * $question->maxgrade;
516cf3eb 931
f30bbcaf 932 // mark the state as graded
933 $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
934
516cf3eb 935 return true;
936 }
937
938
939 /**
940 * Includes configuration settings for the question type on the quiz admin
941 * page
942 *
7518b645 943 * TODO: It makes no sense any longer to do the admin for question types
944 * from the quiz admin page. This should be changed.
516cf3eb 945 * Returns an array of objects describing the options for the question type
946 * to be included on the quiz module admin page.
947 * Configuration options can be included by setting the following fields in
948 * the object:
949 * ->name The name of the option within this question type.
950 * The full option name will be constructed as
951 * "quiz_{$this->name()}_$name", the human readable name
952 * will be displayed with get_string($name, 'quiz').
953 * ->code The code to display the form element, help button, etc.
954 * i.e. the content for the central table cell. Be sure
955 * to name the element "quiz_{$this->name()}_$name" and
956 * set the value to $CFG->{"quiz_{$this->name()}_$name"}.
957 * ->help Name of the string from the quiz module language file
958 * to be used for the help message in the third column of
959 * the table. An empty string (or the field not set)
960 * means to leave the box empty.
961 * Links to custom settings pages can be included by setting the following
962 * fields in the object:
963 * ->name The name of the link text string.
964 * get_string($name, 'quiz') will be called.
965 * ->link The filename part of the URL for the link. The full URL
966 * is contructed as
aaae75b0 967 * "$CFG->wwwroot/question/type/{$this->name()}/$link?sesskey=$sesskey"
516cf3eb 968 * [but with the relavant calls to the s and rawurlencode
969 * functions] where $sesskey is the sesskey for the user.
970 * @return array Array of objects describing the configuration options to
971 * be included on the quiz module admin page.
972 */
973 function get_config_options() {
974 // No options by default
975
976 return false;
977 }
978
979 /**
dc1f00de 980 * Returns true if the editing wizard is finished, false otherwise.
981 *
982 * The default implementation returns true, which is suitable for all question-
516cf3eb 983 * types that only use one editing form. This function is used in
984 * question.php to decide whether we can regrade any states of the edited
985 * question and redirect to edit.php.
986 *
987 * The dataset dependent question-type, which is extended by the calculated
988 * question-type, overwrites this method because it uses multiple pages (i.e.
989 * a wizard) to set up the question and associated datasets.
990 *
991 * @param object $form The data submitted by the previous page.
992 *
993 * @return boolean Whether the wizard's last page was submitted or not.
994 */
995 function finished_edit_wizard(&$form) {
996 //In the default case there is only one edit page.
997 return true;
998 }
999
dc1f00de 1000 /**
1001 * Prints a table of course modules in which the question is used
1002 *
7518b645 1003 * TODO: This should be made quiz-independent
1004 *
dc1f00de 1005 * This function is used near the end of the question edit forms in all question types
1006 * It prints the table of quizzes in which the question is used
1007 * containing checkboxes to allow the teacher to replace the old question version
1008 *
1009 * @param object $question
1010 * @param object $course
1011 * @param integer $cmid optional The id of the course module currently being edited
1012 */
1013 function print_replacement_options($question, $course, $cmid='0') {
516cf3eb 1014
1015 // Disable until the versioning code has been fixed
20808266 1016 if (true) {
1017 return;
1018 }
1019
516cf3eb 1020 // no need to display replacement options if the question is new
1021 if(empty($question->id)) {
1022 return true;
1023 }
1024
1025 // get quizzes using the question (using the question_instances table)
1026 $quizlist = array();
1027 if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) {
1028 $instances = array();
1029 }
1030 foreach($instances as $instance) {
1031 $quizlist[$instance->quiz] = $instance->quiz;
1032 }
1033 $quizlist = implode(',', $quizlist);
1034 if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
1035 $quizzes = array();
1036 }
1037
1038 // do the printing
1039 if(count($quizzes) > 0) {
1040 // print the table
1041 $strquizname = get_string('modulename', 'quiz');
1042 $strdoreplace = get_string('replace', 'quiz');
1043 $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
1044 echo "<tr valign=\"top\">\n";
1045 echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
1046 echo "<td align=\"left\">\n";
1047 echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
1048 echo "<tr>\n";
077f3814 1049 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strquizname</th>\n";
1050 echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strdoreplace</th>\n";
1051 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$straffectedstudents</th>\n";
516cf3eb 1052 echo "</tr>\n";
1053 foreach($quizzes as $quiz) {
1054 // work out whethere it should be checked by default
1055 $checked = '';
dc1f00de 1056 if((int)$cmid === (int)$quiz->id
516cf3eb 1057 or empty($quiz->usercount)) {
1058 $checked = "checked=\"checked\"";
1059 }
1060
1061 // find how many different students have already attempted this quiz
1062 $students = array();
1063 if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
1064 foreach($attempts as $attempt) {
4f48fb42 1065 if (record_exists('question_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) {
516cf3eb 1066 $students[$attempt->userid] = 1;
1067 }
1068 }
1069 }
1070 $studentcount = count($students);
1071
1072 $strstudents = $studentcount === 1 ? $course->student : $course->students;
1073 echo "<tr>\n";
1074 echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name)."</td>\n";
1075 echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
1076 echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ? $studentcount.' '.$strstudents : '-')."</td>\n";
1077 echo "</tr>\n";
1078 }
1079 echo "</table>\n";
1080 }
1081 echo "</td></tr>\n";
1082 }
1083
1b8a7434 1084 /**
1085 * Print the start of the question editing form, including the question category,
a4514d91 1086 * questionname, questiontext, image, defaultgrade, penalty and generalfeedback fields.
1b8a7434 1087 *
1088 * Three of the fields, image, defaultgrade, penalty, are optional, and
1089 * can be removed from the from using the $hidefields argument.
1090 *
1091 * @param object $question The question object that the form we are printing is for.
1092 * @param array $err Array of optional error messages to display by each field.
1093 * Used when the form is being redisplayed after validation failed.
1094 * @param object $course The course object for the course this question belongs to.
1095 * @param boolean $usehtmleditor Whether the html editor should be used.
1096 * @param array $hidefields An array which may contain the strings,
1097 * 'image', 'defaultgrade' or 'penalty' to remove the corresponding field.
1098 */
1099 function print_question_form_start($question, $err, $course, $usehtmleditor, $hidefields = array()) {
1100 global $CFG;
1101
1102 // If you edit this function, you also need to edit random/editquestion.html.
1103
1104 if (!in_array('image', $hidefields)) {
1105 make_upload_directory("$course->id"); // Just in case
1106 $coursefiles = get_directory_list("$CFG->dataroot/$course->id", $CFG->moddata);
1107 foreach ($coursefiles as $filename) {
1108 if (mimeinfo("icon", $filename) == "image.gif") {
1109 $images["$filename"] = $filename;
1110 }
1111 }
516cf3eb 1112 }
1b8a7434 1113
1114 include('editquestionstart.html');
1115 }
1116
1117 /**
1118 * Print the end of the question editing form, including the submit, copy,
1119 * and cancel button, and the standard hidden fields like the sesskey and
1120 * the question type.
1121 *
1122 * @param object $question The question object that the form we are printing is for.
1123 * @param string $submitscript Extra attributes, for example 'onsubmit="myfunction"',
1124 * that is added to the HTML of the submit button.
1125 * @param string $hiddenfields Extra hidden fields (actually any HTML)
1126 * to be added at the end of the form.
1127 */
1128 function print_question_form_end($question, $submitscript = '', $hiddenfields = '') {
1129 global $USER;
1130
1131 // If you edit this function, you also need to edit random/editquestion.html.
1132
1133 include('editquestionend.html');
1134 }
1135
1136 /**
1137 * Call format_text from weblib.php with the options appropriate to question types.
1138 *
1139 * @param string $text the text to format.
1140 * @param integer $text the type of text. Normally $question->questiontextformat.
1141 * @param object $cmoptions the context the string is being displayed in. Only $cmoptions->course is used.
1142 * @return string the formatted text.
1143 */
1144 function format_text($text, $textformat, $cmoptions) {
1145 $formatoptions = new stdClass;
1146 $formatoptions->noclean = true;
1147 $formatoptions->para = false;
1148 return format_text($text, $textformat, $formatoptions, $cmoptions->course);
516cf3eb 1149 }
c5d94c41 1150
1151/// BACKUP FUNCTIONS ////////////////////////////
1152
1153 /*
1154 * Backup the data in the question
1155 *
1156 * This is used in question/backuplib.php
1157 */
1158 function backup($bf,$preferences,$question,$level=6) {
1159 // The default type has nothing to back up
1160 return true;
1161 }
1162
315559d3 1163/// RESTORE FUNCTIONS /////////////////
1164
1165 /*
1166 * Restores the data in the question
1167 *
1168 * This is used in question/restorelib.php
1169 */
1170 function restore($old_question_id,$new_question_id,$info,$restore) {
1171 // The default question type has nothing to restore
1172 return true;
1173 }
1174
1175 function restore_map($old_question_id,$new_question_id,$info,$restore) {
1176 // There is nothing to decode
1177 return true;
1178 }
1179
1180 function restore_recode_answer($state, $restore) {
1181 // There is nothing to decode
ba8f7ff0 1182 return $state->answer;
315559d3 1183 }
1184
1185 //This function restores the question_rqp_states
1186 function restore_state($state_id,$info,$restore) {
1187 // The default question type does not keep its own state information
1188 return true;
1189 }
516cf3eb 1190
1191}
1192
20808266 1193?>