MDL-9716
[moodle-linuxchix.git] / question / type / multichoice / questiontype.php
blob18af0e19bef8c812b87a84df5ab7181d3ad59327
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\"" .
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);
328 } else {
329 $a->feedback = '';
332 $anss[] = clone($a);
335 $feedback = '';
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;
341 } else {
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);
356 if ($response) {
357 $state->raw_grade = $question->options->answers[$response]->fraction;
359 } else {
360 foreach ($state->responses as $response) {
361 if ($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;
377 return true;
380 // ULPGC ecastro
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);
390 } else {
391 $responses[] = '';
393 return $responses;
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) {
409 $status = true;
411 $multichoices = get_records("question_multichoice","question",$question,"id");
412 //If there are multichoices
413 if ($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);
431 return $status;
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) {
443 $status = true;
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']['#']);
461 } else {
462 $multichoice->correctfeedback = '';
464 if (array_key_exists("PARTIALLYCORRECTFEEDBACK", $mul_info['#'])) {
465 $multichoice->partiallycorrectfeedback = backup_todb($mul_info['#']['PARTIALLYCORRECTFEEDBACK']['0']['#']);
466 } else {
467 $multichoice->partiallycorrectfeedback = '';
469 if (array_key_exists("INCORRECTFEEDBACK", $mul_info['#'])) {
470 $multichoice->incorrectfeedback = backup_todb($mul_info['#']['INCORRECTFEEDBACK']['0']['#']);
471 } else {
472 $multichoice->incorrectfeedback = '';
475 //We have to recode the answers field (a list of answers id)
476 //Extracts answer id from sequence
477 $answers_field = "";
478 $in_first = true;
479 $tok = strtok($multichoice->answers,",");
480 while ($tok) {
481 //Get the answer from backup_ids
482 $answer = backup_getid($restore->backup_unique_code,"question_answers",$tok);
483 if ($answer) {
484 if ($in_first) {
485 $answers_field .= $answer->new_id;
486 $in_first = false;
487 } else {
488 $answers_field .= ",".$answer->new_id;
491 //check for next
492 $tok = strtok(",");
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);
500 //Do some output
501 if (($i+1) % 50 == 0) {
502 if (!defined('RESTORE_SILENTLY')) {
503 echo ".";
504 if (($i+1) % 1000 == 0) {
505 echo "<br />";
508 backup_flush(300);
511 if (!$newid) {
512 $status = false;
516 return $status;
519 function restore_recode_answer($state, $restore) {
520 $pos = strpos($state->answer, ':');
521 $order = array();
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);
527 } else {
528 $order = explode(',', substr($state->answer, 0, $pos));
529 if ($responsestring = substr($state->answer, $pos + 1)) {
530 $responses = explode(',', $responsestring);
533 if ($order) {
534 foreach ($order as $key => $oldansid) {
535 $answer = backup_getid($restore->backup_unique_code,"question_answers",$oldansid);
536 if ($answer) {
537 $order[$key] = $answer->new_id;
538 } else {
539 echo 'Could not recode multichoice answer id '.$oldansid.' for state '.$state->oldid.'<br />';
543 if ($responses) {
544 foreach ($responses as $key => $oldansid) {
545 $answer = backup_getid($restore->backup_unique_code,"question_answers",$oldansid);
546 if ($answer) {
547 $responses[$key] = $answer->new_id;
548 } else {
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) {
561 $status = true;
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)) {
578 $status = false;
582 // Do some output.
583 if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
584 echo ".";
585 if ($i % 100 == 0) {
586 echo "<br />";
588 backup_flush(300);
593 return $status;
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) {
612 switch($style) {
613 case 'abc':
614 return chr(ord('a') + $num) . '. ';
615 case 'ABC':
616 return chr(ord('A') + $num) . '. ';
617 case '123':
618 return ($num + 1) . '. ';
619 case 'none':
620 return '';
621 default:
622 return 'ERR';
627 // Register this question type with the question bank.
628 question_register_questiontype(new question_multichoice_qtype());