3 * The questiontype class for the multiple choice question type.
5 * Note, This class contains some special features in order to make the
6 * question type embeddable within a multianswer (cloze) question
8 * @package questionbank
9 * @subpackage questiontypes
11 class question_multichoice_qtype
extends default_questiontype
{
17 function has_html_answers() {
21 function get_question_options(&$question) {
22 // Get additional information from database
23 // and attach it to the question object
24 if (!$question->options
= get_record('question_multichoice', 'question',
26 notify('Error: Missing question options for multichoice question'.$question->id
.'!');
30 if (!$question->options
->answers
= get_records_select('question_answers', 'id IN ('.$question->options
->answers
.')', 'id')) {
31 notify('Error: Missing question answers for multichoice question'.$question->id
.'!');
38 function save_question_options($question) {
39 $result = new stdClass
;
40 if (!$oldanswers = get_records("question_answers", "question",
41 $question->id
, "id ASC")) {
42 $oldanswers = array();
45 // following hack to check at least two answers exist
47 foreach ($question->answer
as $key=>$dataanswer) {
48 if ($dataanswer != "") {
52 $answercount +
= count($oldanswers);
53 if ($answercount < 2) { // check there are at lest 2 answers for multiple choice
54 $result->notice
= get_string("notenoughanswers", "qtype_multichoice", "2");
58 // Insert all the new answers
65 foreach ($question->answer
as $key => $dataanswer) {
66 if ($dataanswer != "") {
67 if ($answer = array_shift($oldanswers)) { // Existing answer, so reuse it
68 $answer->answer
= $dataanswer;
69 $answer->fraction
= $question->fraction
[$key];
70 $answer->feedback
= $question->feedback
[$key];
71 if (!update_record("question_answers", $answer)) {
72 $result->error
= "Could not update quiz answer! (id=$answer->id)";
77 $answer->answer
= $dataanswer;
78 $answer->question
= $question->id
;
79 $answer->fraction
= $question->fraction
[$key];
80 $answer->feedback
= $question->feedback
[$key];
81 if (!$answer->id
= insert_record("question_answers", $answer)) {
82 $result->error
= "Could not insert quiz answer! ";
86 $answers[] = $answer->id
;
88 if ($question->fraction
[$key] > 0) { // Sanity checks
89 $totalfraction +
= $question->fraction
[$key];
91 if ($question->fraction
[$key] > $maxfraction) {
92 $maxfraction = $question->fraction
[$key];
98 $options = get_record("question_multichoice", "question", $question->id
);
101 $options = new stdClass
;
102 $options->question
= $question->id
;
105 $options->answers
= implode(",",$answers);
106 $options->single
= $question->single
;
107 $options->answernumbering
= $question->answernumbering
;
108 $options->shuffleanswers
= $question->shuffleanswers
;
109 $options->correctfeedback
= trim($question->correctfeedback
);
110 $options->partiallycorrectfeedback
= trim($question->partiallycorrectfeedback
);
111 $options->incorrectfeedback
= trim($question->incorrectfeedback
);
113 if (!update_record("question_multichoice", $options)) {
114 $result->error
= "Could not update quiz multichoice options! (id=$options->id)";
118 if (!insert_record("question_multichoice", $options)) {
119 $result->error
= "Could not insert quiz multichoice options!";
124 // delete old answer records
125 if (!empty($oldanswers)) {
126 foreach($oldanswers as $oa) {
127 delete_records('question_answers', 'id', $oa->id
);
131 /// Perform sanity checks on fractional grades
132 if ($options->single
) {
133 if ($maxfraction != 1) {
134 $maxfraction = $maxfraction * 100;
135 $result->noticeyesno
= get_string("fractionsnomax", "qtype_multichoice", $maxfraction);
139 $totalfraction = round($totalfraction,2);
140 if ($totalfraction != 1) {
141 $totalfraction = $totalfraction * 100;
142 $result->noticeyesno
= get_string("fractionsaddwrong", "qtype_multichoice", $totalfraction);
150 * Deletes question from the question-type specific tables
152 * @return boolean Success/Failure
153 * @param object $question The question being deleted
155 function delete_question($questionid) {
156 delete_records("question_multichoice", "question", $questionid);
160 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
161 // create an array of answerids ??? why so complicated ???
162 $answerids = array_values(array_map(create_function('$val',
163 'return $val->id;'), $question->options
->answers
));
164 // Shuffle the answers if required
165 if ($cmoptions->shuffleanswers
and $question->options
->shuffleanswers
) {
166 $answerids = swapshuffle($answerids);
168 $state->options
->order
= $answerids;
169 // Create empty responses
170 if ($question->options
->single
) {
171 $state->responses
= array('' => '');
173 $state->responses
= array();
179 function restore_session_and_responses(&$question, &$state) {
180 // The serialized format for multiple choice quetsions
181 // is an optional comma separated list of answer ids (the order of the
182 // answers) followed by a colon, followed by another comma separated
183 // list of answer ids, which are the radio/checkboxes that were
185 // E.g. 1,3,2,4:2,4 means that the answers were shown in the order
186 // 1, 3, 2 and then 4 and the answers 2 and 4 were checked.
188 $pos = strpos($state->responses
[''], ':');
189 if (false === $pos) { // No order of answers is given, so use the default
190 $state->options
->order
= array_keys($question->options
->answers
);
191 } else { // Restore the order of the answers
192 $state->options
->order
= explode(',', substr($state->responses
[''], 0,
194 $state->responses
[''] = substr($state->responses
[''], $pos +
1);
196 // Restore the responses
197 // This is done in different ways if only a single answer is allowed or
198 // if multiple answers are allowed. For single answers the answer id is
199 // saved in $state->responses[''], whereas for the multiple answers case
200 // the $state->responses array is indexed by the answer ids and the
201 // values are also the answer ids (i.e. key = value).
202 if (empty($state->responses
[''])) { // No previous responses
203 if ($question->options
->single
) {
204 $state->responses
= array('' => '');
206 $state->responses
= array();
209 if ($question->options
->single
) {
210 $state->responses
= array('' => $state->responses
['']);
212 // Get array of answer ids
213 $state->responses
= explode(',', $state->responses
['']);
214 // Create an array indexed by these answer ids
215 $state->responses
= array_flip($state->responses
);
216 // Set the value of each element to be equal to the index
217 array_walk($state->responses
, create_function('&$a, $b',
224 function save_session_and_responses(&$question, &$state) {
225 // Bundle the answer order and the responses into the legacy answer
227 // The serialized format for multiple choice quetsions
228 // is (optionally) a comma separated list of answer ids
229 // followed by a colon, followed by another comma separated
230 // list of answer ids, which are the radio/checkboxes that were
232 // E.g. 1,3,2,4:2,4 means that the answers were shown in the order
233 // 1, 3, 2 and then 4 and the answers 2 and 4 were checked.
234 $responses = implode(',', $state->options
->order
) . ':';
235 $responses .= implode(',', $state->responses
);
237 // Set the legacy answer field
238 if (!set_field('question_states', 'answer', $responses, 'id',
245 function get_correct_responses(&$question, &$state) {
246 if ($question->options
->single
) {
247 foreach ($question->options
->answers
as $answer) {
248 if (((int) $answer->fraction
) === 1) {
249 return array('' => $answer->id
);
254 $responses = array();
255 foreach ($question->options
->answers
as $answer) {
256 if (((float) $answer->fraction
) > 0.0) {
257 $responses[$answer->id
] = (string) $answer->id
;
260 return empty($responses) ?
null : $responses;
264 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
267 $answers = &$question->options
->answers
;
268 $correctanswers = $this->get_correct_responses($question, $state);
269 $readonly = empty($options->readonly
) ?
'' : 'disabled="disabled"';
271 $formatoptions = new stdClass
;
272 $formatoptions->noclean
= true;
273 $formatoptions->para
= false;
276 $questiontext = format_text($question->questiontext
,
277 $question->questiontextformat
,
278 $formatoptions, $cmoptions->course
);
279 $image = get_question_image($question, $cmoptions->course
);
280 $answerprompt = ($question->options
->single
) ?
get_string('singleanswer', 'quiz') :
281 get_string('multipleanswers', 'quiz');
283 // Print each answer in a separate row
284 foreach ($state->options
->order
as $key => $aid) {
285 $answer = &$answers[$aid];
289 if ($question->options
->single
) {
290 $type = 'type="radio"';
291 $name = "name=\"{$question->name_prefix}\"";
292 if (isset($state->responses
['']) and $aid == $state->responses
['']) {
293 $checked = 'checked="checked"';
297 $type = ' type="checkbox" ';
298 $name = "name=\"{$question->name_prefix}{$aid}\"";
299 if (isset($state->responses
[$aid])) {
300 $checked = 'checked="checked"';
306 $a->id
= $question->name_prefix
. $aid;
308 $a->feedbackimg
= '';
311 $a->control
= "<input $readonly id=\"$a->id\" $name $checked $type value=\"$aid\"" .
312 " alt=\"" . s($answer->answer
) . '" />';
314 if ($options->correct_responses
&& $answer->fraction
> 0) {
315 $a->class = question_get_feedback_class(1);
317 if (($options->feedback
&& $chosen) ||
$options->correct_responses
) {
318 $a->feedbackimg
= question_get_feedback_image($answer->fraction
> 0 ?
1 : 0, $chosen && $options->feedback
);
321 // Print the answer text
322 $a->text
= format_text($this->number_in_style($key, $question->options
->answernumbering
) . $answer->answer
,
323 FORMAT_MOODLE
, $formatoptions, $cmoptions->course
);
325 // Print feedback if feedback is on
326 if (($options->feedback ||
$options->correct_responses
) && $checked) {
327 $a->feedback
= format_text($answer->feedback
, true, $formatoptions, $cmoptions->course
);
336 if ($options->feedback
) {
337 if ($state->raw_grade
>= $question->maxgrade
/1.01) {
338 $feedback = $question->options
->correctfeedback
;
339 } else if ($state->raw_grade
> 0) {
340 $feedback = $question->options
->partiallycorrectfeedback
;
342 $feedback = $question->options
->incorrectfeedback
;
344 $feedback = format_text($feedback,
345 $question->questiontextformat
,
346 $formatoptions, $cmoptions->course
);
349 include("$CFG->dirroot/question/type/multichoice/display.html");
352 function grade_responses(&$question, &$state, $cmoptions) {
353 $state->raw_grade
= 0;
354 if($question->options
->single
) {
355 $response = reset($state->responses
);
357 $state->raw_grade
= $question->options
->answers
[$response]->fraction
;
360 foreach ($state->responses
as $response) {
362 $state->raw_grade +
= $question->options
->answers
[$response]->fraction
;
367 // Make sure we don't assign negative or too high marks
368 $state->raw_grade
= min(max((float) $state->raw_grade
,
369 0.0), 1.0) * $question->maxgrade
;
371 // Apply the penalty for this attempt
372 $state->penalty
= $question->penalty
* $question->maxgrade
;
374 // mark the state as graded
375 $state->event
= ($state->event
== QUESTION_EVENTCLOSE
) ? QUESTION_EVENTCLOSEANDGRADE
: QUESTION_EVENTGRADE
;
381 function get_actual_response($question, $state) {
382 $answers = $question->options
->answers
;
383 $responses = array();
384 if (!empty($state->responses
)) {
385 foreach ($state->responses
as $aid =>$rid){
386 if (!empty($answers[$rid])) {
387 $responses[] = $this->format_text($answers[$rid]->answer
, $question->questiontextformat
);
396 function response_summary($question, $state, $length = 80) {
397 return implode(',', $this->get_actual_response($question, $state));
400 /// BACKUP FUNCTIONS ////////////////////////////
403 * Backup the data in the question
405 * This is used in question/backuplib.php
407 function backup($bf,$preferences,$question,$level=6) {
411 $multichoices = get_records("question_multichoice","question",$question,"id");
412 //If there are multichoices
414 //Iterate over each multichoice
415 foreach ($multichoices as $multichoice) {
416 $status = fwrite ($bf,start_tag("MULTICHOICE",$level,true));
417 //Print multichoice contents
418 fwrite ($bf,full_tag("LAYOUT",$level+
1,false,$multichoice->layout
));
419 fwrite ($bf,full_tag("ANSWERS",$level+
1,false,$multichoice->answers
));
420 fwrite ($bf,full_tag("SINGLE",$level+
1,false,$multichoice->single
));
421 fwrite ($bf,full_tag("SHUFFLEANSWERS",$level+
1,false,$multichoice->shuffleanswers
));
422 fwrite ($bf,full_tag("CORRECTFEEDBACK",$level+
1,false,$multichoice->correctfeedback
));
423 fwrite ($bf,full_tag("PARTIALLYCORRECTFEEDBACK",$level+
1,false,$multichoice->partiallycorrectfeedback
));
424 fwrite ($bf,full_tag("INCORRECTFEEDBACK",$level+
1,false,$multichoice->incorrectfeedback
));
425 $status = fwrite ($bf,end_tag("MULTICHOICE",$level,true));
428 //Now print question_answers
429 $status = question_backup_answers($bf,$preferences,$question);
434 /// RESTORE FUNCTIONS /////////////////
437 * Restores the data in the question
439 * This is used in question/restorelib.php
441 function restore($old_question_id,$new_question_id,$info,$restore) {
445 //Get the multichoices array
446 $multichoices = $info['#']['MULTICHOICE'];
448 //Iterate over multichoices
449 for($i = 0; $i < sizeof($multichoices); $i++
) {
450 $mul_info = $multichoices[$i];
452 //Now, build the question_multichoice record structure
453 $multichoice = new stdClass
;
454 $multichoice->question
= $new_question_id;
455 $multichoice->layout
= backup_todb($mul_info['#']['LAYOUT']['0']['#']);
456 $multichoice->answers
= backup_todb($mul_info['#']['ANSWERS']['0']['#']);
457 $multichoice->single
= backup_todb($mul_info['#']['SINGLE']['0']['#']);
458 $multichoice->shuffleanswers
= isset($mul_info['#']['SHUFFLEANSWERS']['0']['#'])?
backup_todb($mul_info['#']['SHUFFLEANSWERS']['0']['#']):'';
459 if (array_key_exists("CORRECTFEEDBACK", $mul_info['#'])) {
460 $multichoice->correctfeedback
= backup_todb($mul_info['#']['CORRECTFEEDBACK']['0']['#']);
462 $multichoice->correctfeedback
= '';
464 if (array_key_exists("PARTIALLYCORRECTFEEDBACK", $mul_info['#'])) {
465 $multichoice->partiallycorrectfeedback
= backup_todb($mul_info['#']['PARTIALLYCORRECTFEEDBACK']['0']['#']);
467 $multichoice->partiallycorrectfeedback
= '';
469 if (array_key_exists("INCORRECTFEEDBACK", $mul_info['#'])) {
470 $multichoice->incorrectfeedback
= backup_todb($mul_info['#']['INCORRECTFEEDBACK']['0']['#']);
472 $multichoice->incorrectfeedback
= '';
475 //We have to recode the answers field (a list of answers id)
476 //Extracts answer id from sequence
479 $tok = strtok($multichoice->answers
,",");
481 //Get the answer from backup_ids
482 $answer = backup_getid($restore->backup_unique_code
,"question_answers",$tok);
485 $answers_field .= $answer->new_id
;
488 $answers_field .= ",".$answer->new_id
;
494 //We have the answers field recoded to its new ids
495 $multichoice->answers
= $answers_field;
497 //The structure is equal to the db, so insert the question_shortanswer
498 $newid = insert_record ("question_multichoice",$multichoice);
501 if (($i+
1) %
50 == 0) {
502 if (!defined('RESTORE_SILENTLY')) {
504 if (($i+
1) %
1000 == 0) {
519 function restore_recode_answer($state, $restore) {
520 $pos = strpos($state->answer
, ':');
522 $responses = array();
523 if (false === $pos) { // No order of answers is given, so use the default
524 if ($state->answer
) {
525 $responses = explode(',', $state->answer
);
528 $order = explode(',', substr($state->answer
, 0, $pos));
529 if ($responsestring = substr($state->answer
, $pos +
1)) {
530 $responses = explode(',', $responsestring);
534 foreach ($order as $key => $oldansid) {
535 $answer = backup_getid($restore->backup_unique_code
,"question_answers",$oldansid);
537 $order[$key] = $answer->new_id
;
539 echo 'Could not recode multichoice answer id '.$oldansid.' for state '.$state->oldid
.'<br />';
544 foreach ($responses as $key => $oldansid) {
545 $answer = backup_getid($restore->backup_unique_code
,"question_answers",$oldansid);
547 $responses[$key] = $answer->new_id
;
549 echo 'Could not recode multichoice response answer id '.$oldansid.' for state '.$state->oldid
.'<br />';
553 return implode(',', $order).':'.implode(',', $responses);
557 * Decode links in question type specific tables.
558 * @return bool success or failure.
560 function decode_content_links_caller($questionids, $restore, &$i) {
563 // Decode links in the question_multichoice table.
564 if ($multichoices = get_records_list('question_multichoice', 'question',
565 implode(',', $questionids), '', 'id, correctfeedback, partiallycorrectfeedback, incorrectfeedback')) {
567 foreach ($multichoices as $multichoice) {
568 $correctfeedback = restore_decode_content_links_worker($multichoice->correctfeedback
, $restore);
569 $partiallycorrectfeedback = restore_decode_content_links_worker($multichoice->partiallycorrectfeedback
, $restore);
570 $incorrectfeedback = restore_decode_content_links_worker($multichoice->incorrectfeedback
, $restore);
571 if ($correctfeedback != $multichoice->correctfeedback ||
572 $partiallycorrectfeedback != $multichoice->partiallycorrectfeedback ||
573 $incorrectfeedback != $multichoice->incorrectfeedback
) {
574 $subquestion->correctfeedback
= addslashes($correctfeedback);
575 $subquestion->partiallycorrectfeedback
= addslashes($partiallycorrectfeedback);
576 $subquestion->incorrectfeedback
= addslashes($incorrectfeedback);
577 if (!update_record('question_multichoice', $multichoice)) {
583 if (++
$i %
5 == 0 && !defined('RESTORE_SILENTLY')) {
597 * @return array of the numbering styles supported. For each one, there
598 * should be a lang string answernumberingxxx in teh qtype_multichoice
599 * language file, and a case in the switch statement in number_in_style,
600 * and it should be listed in the definition of this column in install.xml.
602 function get_numbering_styles() {
603 return array('abc', 'ABC', '123', 'none');
607 * @param int $num The number, starting at 0.
608 * @param string $style The style to render the number in. One of the ones returned by $numberingoptions.
609 * @return string the number $num in the requested style.
611 function number_in_style($num, $style) {
614 return chr(ord('a') +
$num) . '. ';
616 return chr(ord('A') +
$num) . '. ';
618 return ($num +
1) . '. ';
627 // Register this question type with the question bank.
628 question_register_questiontype(new question_multichoice_qtype());