MDL-10515 - Change HTML to make it easier to style multiple choice questions. Merged...
[moodle-pu.git] / question / type / multichoice / questiontype.php
blob5dd0910d125e3953c31b01058bfb5a575f802d8f
1 <?php // $Id$
2 /**
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 {
13 function name() {
14 return 'multichoice';
17 function has_html_answers() {
18 return true;
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',
25 $question->id)) {
26 notify('Error: Missing question options for multichoice question'.$question->id.'!');
27 return false;
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.'!');
32 return false;
35 return true;
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
46 $answercount = 0;
47 foreach ($question->answer as $key=>$dataanswer) {
48 if ($dataanswer != "") {
49 $answercount++;
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");
55 return $result;
58 // Insert all the new answers
60 $totalfraction = 0;
61 $maxfraction = -1;
63 $answers = array();
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)";
73 return $result;
75 } else {
76 unset($answer);
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! ";
83 return $result;
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];
97 $update = true;
98 $options = get_record("question_multichoice", "question", $question->id);
99 if (!$options) {
100 $update = false;
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);
112 if ($update) {
113 if (!update_record("question_multichoice", $options)) {
114 $result->error = "Could not update quiz multichoice options! (id=$options->id)";
115 return $result;
117 } else {
118 if (!insert_record("question_multichoice", $options)) {
119 $result->error = "Could not insert quiz multichoice options!";
120 return $result;
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);
136 return $result;
138 } else {
139 $totalfraction = round($totalfraction,2);
140 if ($totalfraction != 1) {
141 $totalfraction = $totalfraction * 100;
142 $result->noticeyesno = get_string("fractionsaddwrong", "qtype_multichoice", $totalfraction);
143 return $result;
146 return true;
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);
157 return true;
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('' => '');
172 } else {
173 $state->responses = array();
175 return true;
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
184 // ticked.
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,
193 $pos));
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('' => '');
205 } else {
206 $state->responses = array();
208 } else {
209 if ($question->options->single) {
210 $state->responses = array('' => $state->responses['']);
211 } else {
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',
218 '$a = $b;'));
221 return true;
224 function save_session_and_responses(&$question, &$state) {
225 // Bundle the answer order and the responses into the legacy answer
226 // field.
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
231 // ticked.
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',
239 $state->id)) {
240 return false;
242 return true;
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);
252 return null;
253 } else {
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) {
265 global $CFG;
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;
275 // Print formulation
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];
286 $checked = '';
287 $chosen = false;
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"';
294 $chosen = true;
296 } else {
297 $type = ' type="checkbox" ';
298 $name = "name=\"{$question->name_prefix}{$aid}\"";
299 if (isset($state->responses[$aid])) {
300 $checked = 'checked="checked"';
301 $chosen = true;
305 $a = new stdClass;
306 $a->id = $question->name_prefix . $aid;
307 $a->class = '';
308 $a->feedbackimg = '';
310 // Print the control
311 $a->control = "<input $readonly id=\"$a->id\" $name $checked $type value=\"$aid\" />";
313 if ($options->correct_responses && $answer->fraction > 0) {
314 $a->class = question_get_feedback_class(1);
316 if (($options->feedback && $chosen) || $options->correct_responses) {
317 $a->feedbackimg = question_get_feedback_image($answer->fraction > 0 ? 1 : 0, $chosen && $options->feedback);
320 // Print the answer text
321 $a->text = $this->number_in_style($key, $question->options->answernumbering) .
322 format_text($answer->answer, FORMAT_MOODLE, $formatoptions, $cmoptions->course);
324 // Print feedback if feedback is on
325 if (($options->feedback || $options->correct_responses) && $checked) {
326 $a->feedback = format_text($answer->feedback, true, $formatoptions, $cmoptions->course);
327 } else {
328 $a->feedback = '';
331 $anss[] = clone($a);
334 $feedback = '';
335 if ($options->feedback) {
336 if ($state->raw_grade >= $question->maxgrade/1.01) {
337 $feedback = $question->options->correctfeedback;
338 } else if ($state->raw_grade > 0) {
339 $feedback = $question->options->partiallycorrectfeedback;
340 } else {
341 $feedback = $question->options->incorrectfeedback;
343 $feedback = format_text($feedback,
344 $question->questiontextformat,
345 $formatoptions, $cmoptions->course);
348 include("$CFG->dirroot/question/type/multichoice/display.html");
351 function grade_responses(&$question, &$state, $cmoptions) {
352 $state->raw_grade = 0;
353 if($question->options->single) {
354 $response = reset($state->responses);
355 if ($response) {
356 $state->raw_grade = $question->options->answers[$response]->fraction;
358 } else {
359 foreach ($state->responses as $response) {
360 if ($response) {
361 $state->raw_grade += $question->options->answers[$response]->fraction;
366 // Make sure we don't assign negative or too high marks
367 $state->raw_grade = min(max((float) $state->raw_grade,
368 0.0), 1.0) * $question->maxgrade;
370 // Apply the penalty for this attempt
371 $state->penalty = $question->penalty * $question->maxgrade;
373 // mark the state as graded
374 $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
376 return true;
379 // ULPGC ecastro
380 function get_actual_response($question, $state) {
381 $answers = $question->options->answers;
382 $responses = array();
383 if (!empty($state->responses)) {
384 foreach ($state->responses as $aid =>$rid){
385 if (!empty($answers[$rid])) {
386 $responses[] = $this->format_text($answers[$rid]->answer, $question->questiontextformat);
389 } else {
390 $responses[] = '';
392 return $responses;
395 function response_summary($question, $state, $length = 80) {
396 return implode(',', $this->get_actual_response($question, $state));
399 /// BACKUP FUNCTIONS ////////////////////////////
402 * Backup the data in the question
404 * This is used in question/backuplib.php
406 function backup($bf,$preferences,$question,$level=6) {
408 $status = true;
410 $multichoices = get_records("question_multichoice","question",$question,"id");
411 //If there are multichoices
412 if ($multichoices) {
413 //Iterate over each multichoice
414 foreach ($multichoices as $multichoice) {
415 $status = fwrite ($bf,start_tag("MULTICHOICE",$level,true));
416 //Print multichoice contents
417 fwrite ($bf,full_tag("LAYOUT",$level+1,false,$multichoice->layout));
418 fwrite ($bf,full_tag("ANSWERS",$level+1,false,$multichoice->answers));
419 fwrite ($bf,full_tag("SINGLE",$level+1,false,$multichoice->single));
420 fwrite ($bf,full_tag("SHUFFLEANSWERS",$level+1,false,$multichoice->shuffleanswers));
421 fwrite ($bf,full_tag("CORRECTFEEDBACK",$level+1,false,$multichoice->correctfeedback));
422 fwrite ($bf,full_tag("PARTIALLYCORRECTFEEDBACK",$level+1,false,$multichoice->partiallycorrectfeedback));
423 fwrite ($bf,full_tag("INCORRECTFEEDBACK",$level+1,false,$multichoice->incorrectfeedback));
424 $status = fwrite ($bf,end_tag("MULTICHOICE",$level,true));
427 //Now print question_answers
428 $status = question_backup_answers($bf,$preferences,$question);
430 return $status;
433 /// RESTORE FUNCTIONS /////////////////
436 * Restores the data in the question
438 * This is used in question/restorelib.php
440 function restore($old_question_id,$new_question_id,$info,$restore) {
442 $status = true;
444 //Get the multichoices array
445 $multichoices = $info['#']['MULTICHOICE'];
447 //Iterate over multichoices
448 for($i = 0; $i < sizeof($multichoices); $i++) {
449 $mul_info = $multichoices[$i];
451 //Now, build the question_multichoice record structure
452 $multichoice = new stdClass;
453 $multichoice->question = $new_question_id;
454 $multichoice->layout = backup_todb($mul_info['#']['LAYOUT']['0']['#']);
455 $multichoice->answers = backup_todb($mul_info['#']['ANSWERS']['0']['#']);
456 $multichoice->single = backup_todb($mul_info['#']['SINGLE']['0']['#']);
457 $multichoice->shuffleanswers = isset($mul_info['#']['SHUFFLEANSWERS']['0']['#'])?backup_todb($mul_info['#']['SHUFFLEANSWERS']['0']['#']):'';
458 if (array_key_exists("CORRECTFEEDBACK", $mul_info['#'])) {
459 $multichoice->correctfeedback = backup_todb($mul_info['#']['CORRECTFEEDBACK']['0']['#']);
460 } else {
461 $multichoice->correctfeedback = '';
463 if (array_key_exists("PARTIALLYCORRECTFEEDBACK", $mul_info['#'])) {
464 $multichoice->partiallycorrectfeedback = backup_todb($mul_info['#']['PARTIALLYCORRECTFEEDBACK']['0']['#']);
465 } else {
466 $multichoice->partiallycorrectfeedback = '';
468 if (array_key_exists("INCORRECTFEEDBACK", $mul_info['#'])) {
469 $multichoice->incorrectfeedback = backup_todb($mul_info['#']['INCORRECTFEEDBACK']['0']['#']);
470 } else {
471 $multichoice->incorrectfeedback = '';
474 //We have to recode the answers field (a list of answers id)
475 //Extracts answer id from sequence
476 $answers_field = "";
477 $in_first = true;
478 $tok = strtok($multichoice->answers,",");
479 while ($tok) {
480 //Get the answer from backup_ids
481 $answer = backup_getid($restore->backup_unique_code,"question_answers",$tok);
482 if ($answer) {
483 if ($in_first) {
484 $answers_field .= $answer->new_id;
485 $in_first = false;
486 } else {
487 $answers_field .= ",".$answer->new_id;
490 //check for next
491 $tok = strtok(",");
493 //We have the answers field recoded to its new ids
494 $multichoice->answers = $answers_field;
496 //The structure is equal to the db, so insert the question_shortanswer
497 $newid = insert_record ("question_multichoice",$multichoice);
499 //Do some output
500 if (($i+1) % 50 == 0) {
501 if (!defined('RESTORE_SILENTLY')) {
502 echo ".";
503 if (($i+1) % 1000 == 0) {
504 echo "<br />";
507 backup_flush(300);
510 if (!$newid) {
511 $status = false;
515 return $status;
518 function restore_recode_answer($state, $restore) {
519 $pos = strpos($state->answer, ':');
520 $order = array();
521 $responses = array();
522 if (false === $pos) { // No order of answers is given, so use the default
523 if ($state->answer) {
524 $responses = explode(',', $state->answer);
526 } else {
527 $order = explode(',', substr($state->answer, 0, $pos));
528 if ($responsestring = substr($state->answer, $pos + 1)) {
529 $responses = explode(',', $responsestring);
532 if ($order) {
533 foreach ($order as $key => $oldansid) {
534 $answer = backup_getid($restore->backup_unique_code,"question_answers",$oldansid);
535 if ($answer) {
536 $order[$key] = $answer->new_id;
537 } else {
538 echo 'Could not recode multichoice answer id '.$oldansid.' for state '.$state->oldid.'<br />';
542 if ($responses) {
543 foreach ($responses as $key => $oldansid) {
544 $answer = backup_getid($restore->backup_unique_code,"question_answers",$oldansid);
545 if ($answer) {
546 $responses[$key] = $answer->new_id;
547 } else {
548 echo 'Could not recode multichoice response answer id '.$oldansid.' for state '.$state->oldid.'<br />';
552 return implode(',', $order).':'.implode(',', $responses);
556 * Decode links in question type specific tables.
557 * @return bool success or failure.
559 function decode_content_links_caller($questionids, $restore, &$i) {
560 $status = true;
562 // Decode links in the question_multichoice table.
563 if ($multichoices = get_records_list('question_multichoice', 'question',
564 implode(',', $questionids), '', 'id, correctfeedback, partiallycorrectfeedback, incorrectfeedback')) {
566 foreach ($multichoices as $multichoice) {
567 $correctfeedback = restore_decode_content_links_worker($multichoice->correctfeedback, $restore);
568 $partiallycorrectfeedback = restore_decode_content_links_worker($multichoice->partiallycorrectfeedback, $restore);
569 $incorrectfeedback = restore_decode_content_links_worker($multichoice->incorrectfeedback, $restore);
570 if ($correctfeedback != $multichoice->correctfeedback ||
571 $partiallycorrectfeedback != $multichoice->partiallycorrectfeedback ||
572 $incorrectfeedback != $multichoice->incorrectfeedback) {
573 $subquestion->correctfeedback = addslashes($correctfeedback);
574 $subquestion->partiallycorrectfeedback = addslashes($partiallycorrectfeedback);
575 $subquestion->incorrectfeedback = addslashes($incorrectfeedback);
576 if (!update_record('question_multichoice', $multichoice)) {
577 $status = false;
581 // Do some output.
582 if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
583 echo ".";
584 if ($i % 100 == 0) {
585 echo "<br />";
587 backup_flush(300);
592 return $status;
596 * @return array of the numbering styles supported. For each one, there
597 * should be a lang string answernumberingxxx in teh qtype_multichoice
598 * language file, and a case in the switch statement in number_in_style,
599 * and it should be listed in the definition of this column in install.xml.
601 function get_numbering_styles() {
602 return array('abc', 'ABC', '123', 'none');
605 function number_html($qnum) {
606 return '<span class="anun">' . $qnum . '<span class="anumsep">.</span></span> ';
610 * @param int $num The number, starting at 0.
611 * @param string $style The style to render the number in. One of the ones returned by $numberingoptions.
612 * @return string the number $num in the requested style.
614 function number_in_style($num, $style) {
615 switch($style) {
616 case 'abc':
617 return $this->number_html(chr(ord('a') + $num));
618 case 'ABC':
619 return $this->number_html(chr(ord('A') + $num));
620 case '123':
621 return $this->number_html(($num + 1));
622 case 'none':
623 return '';
624 default:
625 return 'ERR';
630 // Register this question type with the question bank.
631 question_register_questiontype(new question_multichoice_qtype());