MDL-20636 Question import, support for files in hints.
[moodle.git] / question / format / gift / format.php
CommitLineData
aeb15530 1<?php
d3603157
TH
2
3// This file is part of Moodle - http://moodle.org/
f1abd39f 4//
d3603157
TH
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
84769fd8 9//
d3603157
TH
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
aeb15530 14//
d3603157
TH
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * GIFT format question importer/exporter.
20 *
21 * @package qformat
22 * @subpackage gift
23 * @copyright 2003 Paul Tsuchido Shew
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27
a17b297d
TH
28defined('MOODLE_INTERNAL') || die();
29
30
41a89a07 31/**
d3603157
TH
32 * The GIFT import filter was designed as an easy to use method
33 * for teachers writing questions as a text file. It supports most
34 * question types and the missing word format.
35 *
36 * Multiple Choice / Missing Word
37 * Who's buried in Grant's tomb?{~Grant ~Jefferson =no one}
38 * Grant is {~buried =entombed ~living} in Grant's tomb.
39 * True-False:
40 * Grant is buried in Grant's tomb.{FALSE}
41 * Short-Answer.
42 * Who's buried in Grant's tomb?{=no one =nobody}
43 * Numerical
44 * When was Ulysses S. Grant born?{#1822:5}
45 * Matching
46 * Match the following countries with their corresponding
47 * capitals.{=Canada->Ottawa =Italy->Rome =Japan->Tokyo}
48 *
49 * Comment lines start with a double backslash (//).
50 * Optional question names are enclosed in double colon(::).
51 * Answer feedback is indicated with hash mark (#).
52 * Percentage answer weights immediately follow the tilde (for
53 * multiple choice) or equal sign (for short answer and numerical),
54 * and are enclosed in percent signs (% %). See docs and examples.txt for more.
55 *
56 * This filter was written through the collaboration of numerous
57 * members of the Moodle community. It was originally based on
58 * the missingword format, which included code from Thomas Robb
59 * and others. Paul Tsuchido Shew wrote this filter in December 2003.
60 *
61 * @copyright 2003 Paul Tsuchido Shew
62 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41a89a07 63 */
f5565b69 64class qformat_gift extends qformat_default {
84769fd8 65
66 function provide_import() {
09db6da2 67 return true;
84769fd8 68 }
69
70 function provide_export() {
09db6da2 71 return true;
84769fd8 72 }
73
b80d424c
TH
74 function export_file_extension() {
75 return '.txt';
76 }
77
84769fd8 78 function answerweightparser(&$answer) {
79 $answer = substr($answer, 1); // removes initial %
80 $end_position = strpos($answer, "%");
81 $answer_weight = substr($answer, 0, $end_position); // gets weight as integer
82 $answer_weight = $answer_weight/100; // converts to percent
83 $answer = substr($answer, $end_position+1); // removes comment from answer
84 return $answer_weight;
85 }
86
5b744492
TH
87 function commentparser($answer, $defaultformat) {
88 $bits = explode('#', $answer, 2);
89 $ans = $this->parse_text_with_format(trim($bits[0]), $defaultformat);
90 if (count($bits) > 1) {
91 $feedback = $this->parse_text_with_format(trim($bits[1]), $defaultformat);
84769fd8 92 } else {
5b744492 93 $feedback = array('text' => '', 'format' => $defaultformat, 'files' => array());
84769fd8 94 }
5b744492 95 return array($ans, $feedback);
84769fd8 96 }
97
5b744492
TH
98 function split_truefalse_comment($answer, $defaultformat) {
99 $bits = explode('#', $answer, 3);
100 $ans = $this->parse_text_with_format(trim($bits[0]), $defaultformat);
101 if (count($bits) > 1) {
102 $wrongfeedback = $this->parse_text_with_format(trim($bits[1]), $defaultformat);
09db6da2 103 } else {
5b744492 104 $wrongfeedback = array('text' => '', 'format' => $defaultformat, 'files' => array());
09db6da2 105 }
5b744492
TH
106 if (count($bits) > 2) {
107 $rightfeedback = $this->parse_text_with_format(trim($bits[2]), $defaultformat);
108 } else {
109 $rightfeedback = array('text' => '', 'format' => $defaultformat, 'files' => array());
110 }
111 return array($ans, $wrongfeedback, $rightfeedback);
84769fd8 112 }
aeb15530 113
84769fd8 114 function escapedchar_pre($string) {
115 //Replaces escaped control characters with a placeholder BEFORE processing
aeb15530 116
13bb604e
TH
117 $escapedcharacters = array("\\:", "\\#", "\\=", "\\{", "\\}", "\\~", "\\n" ); //dlnsk
118 $placeholders = array("&&058;", "&&035;", "&&061;", "&&123;", "&&125;", "&&126;", "&&010"); //dlnsk
84769fd8 119
120 $string = str_replace("\\\\", "&&092;", $string);
121 $string = str_replace($escapedcharacters, $placeholders, $string);
122 $string = str_replace("&&092;", "\\", $string);
123 return $string;
124 }
125
126 function escapedchar_post($string) {
127 //Replaces placeholders with corresponding character AFTER processing is done
dfdce7fb 128 $placeholders = array("&&058;", "&&035;", "&&061;", "&&123;", "&&125;", "&&126;", "&&010"); //dlnsk
13bb604e 129 $characters = array(":", "#", "=", "{", "}", "~", "\n" ); //dlnsk
84769fd8 130 $string = str_replace($placeholders, $characters, $string);
131 return $string;
132 }
133
13bb604e 134 function check_answer_count($min, $answers, $text) {
09db6da2 135 $countanswers = count($answers);
136 if ($countanswers < $min) {
5e8a85aa 137 $this->error(get_string('importminerror', 'qformat_gift'), $text);
09db6da2 138 return false;
139 }
140
141 return true;
84769fd8 142 }
143
5b744492
TH
144 protected function parse_text_with_format($text, $defaultformat = FORMAT_MOODLE) {
145 $result = array(
146 'text' => $text,
147 'format' => $defaultformat,
148 'files' => array(),
149 );
150 if (strpos($text, '[') === 0) {
151 $formatend = strpos($text, ']');
152 $result['format'] = $this->format_name_to_const(substr($text, 1, $formatend - 1));
153 if ($result['format'] == -1) {
154 $result['format'] = $defaultformat;
155 } else {
156 $result['text'] = substr($text, $formatend + 1);
157 }
158 }
159 $result['text'] = trim($this->escapedchar_post($result['text']));
160 return $result;
161 }
84769fd8 162
163 function readquestion($lines) {
164 // Given an array of lines known to define a question in this format, this function
165 // converts it into a question object suitable for processing and insertion into Moodle.
166
167 $question = $this->defaultquestion();
168 $comment = NULL;
169 // define replaced by simple assignment, stop redefine notices
13bb604e 170 $gift_answerweight_regex = '/^%\-*([0-9]{1,2})\.?([0-9]*)%/';
84769fd8 171
172 // REMOVED COMMENTED LINES and IMPLODE
173 foreach ($lines as $key => $line) {
09db6da2 174 $line = trim($line);
13bb604e
TH
175 if (substr($line, 0, 2) == '//') {
176 $lines[$key] = ' ';
09db6da2 177 }
84769fd8 178 }
179
13bb604e 180 $text = trim(implode(' ', $lines));
84769fd8 181
13bb604e 182 if ($text == '') {
84769fd8 183 return false;
184 }
185
186 // Substitute escaped control characters with placeholders
187 $text = $this->escapedchar_pre($text);
188
b39c7aad 189 // Look for category modifier
13bb604e 190 if (preg_match('~^\$CATEGORY:~', $text)) {
5363b555 191 // $newcategory = $matches[1];
13bb604e 192 $newcategory = trim(substr($text, 10));
b39c7aad 193
194 // build fake question to contain category
195 $question->qtype = 'category';
196 $question->category = $newcategory;
197 return $question;
198 }
aeb15530 199
84769fd8 200 // QUESTION NAME parser
13bb604e 201 if (substr($text, 0, 2) == '::') {
84769fd8 202 $text = substr($text, 2);
203
13bb604e 204 $namefinish = strpos($text, '::');
84769fd8 205 if ($namefinish === false) {
206 $question->name = false;
207 // name will be assigned after processing question text below
09db6da2 208 } else {
84769fd8 209 $questionname = substr($text, 0, $namefinish);
294ce987 210 $question->name = trim($this->escapedchar_post($questionname));
84769fd8 211 $text = trim(substr($text, $namefinish+2)); // Remove name from text
212 }
213 } else {
214 $question->name = false;
215 }
216
217
218 // FIND ANSWER section
e8825e72 219 // no answer means its a description
13bb604e
TH
220 $answerstart = strpos($text, '{');
221 $answerfinish = strpos($text, '}');
e8825e72 222
223 $description = false;
224 if (($answerstart === false) and ($answerfinish === false)) {
225 $description = true;
226 $answertext = '';
227 $answerlength = 0;
13bb604e 228 } else if (!(($answerstart !== false) and ($answerfinish !== false))) {
5e8a85aa 229 $this->error(get_string('braceerror', 'qformat_gift'), $text);
84769fd8 230 return false;
13bb604e 231 } else {
e8825e72 232 $answerlength = $answerfinish - $answerstart;
233 $answertext = trim(substr($text, $answerstart + 1, $answerlength - 1));
234 }
84769fd8 235
236 // Format QUESTION TEXT without answer, inserting "_____" as necessary
e8825e72 237 if ($description) {
238 $questiontext = $text;
13bb604e 239 } else if (substr($text, -1) == "}") {
84769fd8 240 // no blank line if answers follow question, outside of closing punctuation
241 $questiontext = substr_replace($text, "", $answerstart, $answerlength+1);
242 } else {
243 // inserts blank line for missing word format
244 $questiontext = substr_replace($text, "_____", $answerstart, $answerlength+1);
245 }
246
13bb604e 247 // Get questiontext format from questiontext
5b744492
TH
248 $text = $this->parse_text_with_format($questiontext);
249 $question->questiontextformat = $text['format'];
250 $question->generalfeedbackformat = $text['format'];
251 $question->questiontext = $text['text'];
84769fd8 252
253 // set question name if not already set
254 if ($question->name === false) {
255 $question->name = $question->questiontext;
13bb604e 256 }
84769fd8 257
8daaaafc 258 // ensure name is not longer than 250 characters
13bb604e
TH
259 $question->name = shorten_text($question->name, 200);
260 $question->name = strip_tags(substr($question->name, 0, 250));
84769fd8 261
09db6da2 262 // determine QUESTION TYPE
84769fd8 263 $question->qtype = NULL;
264
4433fff5 265 // give plugins first try
266 // plugins must promise not to intercept standard qtypes
3ea69b8d 267 // MDL-12346, this could be called from lesson mod which has its own base class =(
13bb604e 268 if (method_exists($this, 'try_importing_using_qtypes') && ($try_question = $this->try_importing_using_qtypes($lines, $question, $answertext))) {
d510ec64 269 return $try_question;
4433fff5 270 }
271
e8825e72 272 if ($description) {
273 $question->qtype = DESCRIPTION;
13bb604e
TH
274
275 } else if ($answertext == '') {
e8825e72 276 $question->qtype = ESSAY;
13bb604e
TH
277
278 } else if ($answertext{0} == '#') {
84769fd8 279 $question->qtype = NUMERICAL;
280
13bb604e 281 } else if (strpos($answertext, '~') !== false) {
84769fd8 282 // only Multiplechoice questions contain tilde ~
283 $question->qtype = MULTICHOICE;
aeb15530 284
13bb604e
TH
285 } else if (strpos($answertext, '=') !== false
286 && strpos($answertext, '->') !== false) {
09db6da2 287 // only Matching contains both = and ->
84769fd8 288 $question->qtype = MATCH;
289
290 } else { // either TRUEFALSE or SHORTANSWER
aeb15530 291
84769fd8 292 // TRUEFALSE question check
293 $truefalse_check = $answertext;
13bb604e 294 if (strpos($answertext, '#') > 0) {
84769fd8 295 // strip comments to check for TrueFalse question
296 $truefalse_check = trim(substr($answertext, 0, strpos($answertext,"#")));
297 }
298
13bb604e 299 $valid_tf_answers = array('T', 'TRUE', 'F', 'FALSE');
84769fd8 300 if (in_array($truefalse_check, $valid_tf_answers)) {
301 $question->qtype = TRUEFALSE;
302
303 } else { // Must be SHORTANSWER
13bb604e 304 $question->qtype = SHORTANSWER;
84769fd8 305 }
306 }
307
308 if (!isset($question->qtype)) {
5e8a85aa 309 $giftqtypenotset = get_string('giftqtypenotset', 'qformat_gift');
13bb604e 310 $this->error($giftqtypenotset, $text);
84769fd8 311 return false;
312 }
313
314 switch ($question->qtype) {
e8825e72 315 case DESCRIPTION:
49e2bba7 316 $question->defaultmark = 0;
3f5633df 317 $question->length = 0;
e8825e72 318 return $question;
319 break;
320 case ESSAY:
e8825e72 321 $question->fraction = 0;
13bb604e 322 $question->feedback['text'] = '';
5b744492 323 $question->feedback['format'] = $question->questiontextformat;
13bb604e 324 $question->feedback['files'] = array();
e8825e72 325 return $question;
326 break;
84769fd8 327 case MULTICHOICE:
328 if (strpos($answertext,"=") === false) {
13bb604e 329 $question->single = 0; // multiple answers are enabled if no single answer is 100% correct
84769fd8 330 } else {
13bb604e 331 $question->single = 1; // only one answer allowed (the default)
84769fd8 332 }
13bb604e 333 $question->correctfeedback['text'] = '';
5b744492 334 $question->correctfeedback['format'] = $question->questiontextformat;
13bb604e
TH
335 $question->correctfeedback['files'] = array();
336 $question->partiallycorrectfeedback['text'] = '';
5b744492 337 $question->partiallycorrectfeedback['format'] = $question->questiontextformat;
13bb604e
TH
338 $question->partiallycorrectfeedback['files'] = array();
339 $question->incorrectfeedback['text'] = '';
5b744492 340 $question->incorrectfeedback['format'] = $question->questiontextformat;
13bb604e 341 $question->incorrectfeedback['files'] = array();
84769fd8 342
343 $answertext = str_replace("=", "~=", $answertext);
344 $answers = explode("~", $answertext);
345 if (isset($answers[0])) {
346 $answers[0] = trim($answers[0]);
347 }
348 if (empty($answers[0])) {
349 array_shift($answers);
350 }
aeb15530 351
84769fd8 352 $countanswers = count($answers);
aeb15530 353
13bb604e 354 if (!$this->check_answer_count(2, $answers, $text)) {
2befe778 355 return false;
356 break;
84769fd8 357 }
358
359 foreach ($answers as $key => $answer) {
360 $answer = trim($answer);
361
362 // determine answer weight
13bb604e 363 if ($answer[0] == '=') {
84769fd8 364 $answer_weight = 1;
365 $answer = substr($answer, 1);
aeb15530 366
13bb604e 367 } else if (preg_match($gift_answerweight_regex, $answer)) { // check for properly formatted answer weight
84769fd8 368 $answer_weight = $this->answerweightparser($answer);
aeb15530 369
84769fd8 370 } else { //default, i.e., wrong anwer
371 $answer_weight = 0;
372 }
5b744492
TH
373 list($question->answer[$key], $question->feedback[$key]) =
374 $this->commentparser($answer, $question->questiontextformat);
84769fd8 375 $question->fraction[$key] = $answer_weight;
84769fd8 376 } // end foreach answer
aeb15530 377
49e2bba7 378 //$question->defaultmark = 1;
84769fd8 379 //$question->image = ""; // No images with this format
380 return $question;
381 break;
382
383 case MATCH:
13bb604e 384 $answers = explode('=', $answertext);
84769fd8 385 if (isset($answers[0])) {
386 $answers[0] = trim($answers[0]);
387 }
388 if (empty($answers[0])) {
389 array_shift($answers);
390 }
aeb15530 391
13bb604e 392 if (!$this->check_answer_count(2,$answers,$text)) {
2befe778 393 return false;
394 break;
84769fd8 395 }
aeb15530 396
84769fd8 397 foreach ($answers as $key => $answer) {
398 $answer = trim($answer);
87ee4968 399 if (strpos($answer, "->") === false) {
5e8a85aa 400 $giftmatchingformat = get_string('giftmatchingformat','qformat_gift');
13bb604e 401 $this->error($giftmatchingformat, $answer);
84769fd8 402 return false;
403 break 2;
404 }
405
13bb604e 406 $marker = strpos($answer, '->');
5b744492
TH
407 $question->subquestions[$key] = $this->parse_text_with_format(
408 substr($answer, 0, $marker), $question->questiontextformat);
409 $question->subanswers[$key] = trim($this->escapedchar_post(
410 substr($answer, $marker + 2)));
411 }
aeb15530 412
84769fd8 413 return $question;
414 break;
aeb15530 415
84769fd8 416 case TRUEFALSE:
5b744492
TH
417 list($answer, $wrongfeedback, $rightfeedback) =
418 $this->split_truefalse_comment($answertext, $question->questiontextformat);
84769fd8 419
2c00fa16 420 if ($answer['text'] == "T" OR $answer['text'] == "TRUE") {
5b744492
TH
421 $question->correctanswer = 1;
422 $question->feedbacktrue = $rightfeedback;
423 $question->feedbackfalse = $wrongfeedback;
84769fd8 424 } else {
5b744492
TH
425 $question->correctanswer = 0;
426 $question->feedbacktrue = $wrongfeedback;
427 $question->feedbackfalse = $rightfeedback;
84769fd8 428 }
429
0d4c63d7 430 $question->penalty = 1;
7939a4a0 431
84769fd8 432 return $question;
433 break;
aeb15530 434
84769fd8 435 case SHORTANSWER:
436 // SHORTANSWER Question
437 $answers = explode("=", $answertext);
438 if (isset($answers[0])) {
439 $answers[0] = trim($answers[0]);
440 }
441 if (empty($answers[0])) {
442 array_shift($answers);
443 }
aeb15530 444
5b744492 445 if (!$this->check_answer_count(1, $answers, $text)) {
2befe778 446 return false;
447 break;
84769fd8 448 }
449
450 foreach ($answers as $key => $answer) {
451 $answer = trim($answer);
452
5b744492 453 // Answer weight
6dbcacee 454 if (preg_match($gift_answerweight_regex, $answer)) { // check for properly formatted answer weight
84769fd8 455 $answer_weight = $this->answerweightparser($answer);
456 } else { //default, i.e., full-credit anwer
457 $answer_weight = 1;
458 }
5b744492
TH
459
460 list($answer, $question->feedback[$key]) = $this->commentparser(
461 $answer, $question->questiontextformat);
462
463 $question->answer[$key] = $answer['text'];
13bb604e 464 $question->fraction[$key] = $answer_weight;
5b744492 465 }
84769fd8 466
84769fd8 467 return $question;
468 break;
469
470 case NUMERICAL:
471 // Note similarities to ShortAnswer
472 $answertext = substr($answertext, 1); // remove leading "#"
473
1fe641f7 474 // If there is feedback for a wrong answer, store it for now.
475 if (($pos = strpos($answertext, '~')) !== false) {
476 $wrongfeedback = substr($answertext, $pos);
477 $answertext = substr($answertext, 0, $pos);
478 } else {
479 $wrongfeedback = '';
480 }
481
84769fd8 482 $answers = explode("=", $answertext);
483 if (isset($answers[0])) {
484 $answers[0] = trim($answers[0]);
485 }
486 if (empty($answers[0])) {
487 array_shift($answers);
488 }
aeb15530 489
84769fd8 490 if (count($answers) == 0) {
491 // invalid question
5e8a85aa 492 $giftnonumericalanswers = get_string('giftnonumericalanswers','qformat_gift');
13bb604e 493 $this->error($giftnonumericalanswers, $text);
84769fd8 494 return false;
495 break;
496 }
497
498 foreach ($answers as $key => $answer) {
499 $answer = trim($answer);
500
501 // Answer weight
6dbcacee 502 if (preg_match($gift_answerweight_regex, $answer)) { // check for properly formatted answer weight
84769fd8 503 $answer_weight = $this->answerweightparser($answer);
504 } else { //default, i.e., full-credit anwer
505 $answer_weight = 1;
506 }
5b744492
TH
507
508 list($answer, $question->feedback[$key]) = $this->commentparser(
509 $answer, $question->questiontextformat);
84769fd8 510 $question->fraction[$key] = $answer_weight;
5b744492 511 $answer = $answer['text'];
84769fd8 512
513 //Calculate Answer and Min/Max values
514 if (strpos($answer,"..") > 0) { // optional [min]..[max] format
515 $marker = strpos($answer,"..");
516 $max = trim(substr($answer, $marker+2));
517 $min = trim(substr($answer, 0, $marker));
518 $ans = ($max + $min)/2;
519 $tol = $max - $ans;
13bb604e
TH
520 } else if (strpos($answer, ':') > 0) { // standard [answer]:[errormargin] format
521 $marker = strpos($answer, ':');
84769fd8 522 $tol = trim(substr($answer, $marker+1));
523 $ans = trim(substr($answer, 0, $marker));
524 } else { // only one valid answer (zero errormargin)
525 $tol = 0;
526 $ans = trim($answer);
527 }
aeb15530 528
09db6da2 529 if (!(is_numeric($ans) || $ans = '*') || !is_numeric($tol)) {
13bb604e
TH
530 $errornotnumbers = get_string('errornotnumbers');
531 $this->error($errornotnumbers, $text);
84769fd8 532 return false;
533 break;
534 }
aeb15530 535
84769fd8 536 // store results
537 $question->answer[$key] = $ans;
538 $question->tolerance[$key] = $tol;
5b744492 539 }
84769fd8 540
1fe641f7 541 if ($wrongfeedback) {
542 $key += 1;
543 $question->fraction[$key] = 0;
5b744492
TH
544 list($notused, $question->feedback[$key]) = $this->commentparser(
545 $wrongfeedback, $question->questiontextformat);
13bb604e 546 $question->answer[$key] = '*';
1fe641f7 547 $question->tolerance[$key] = '';
548 }
549
84769fd8 550 return $question;
551 break;
552
553 default:
5e8a85aa 554 $this->error(get_string('giftnovalidquestion', 'qformat_gift'), $text);
5b744492 555 return fale;
aeb15530
PS
556 break;
557
13bb604e 558 }
84769fd8 559
84769fd8 560 }
561
13bb604e
TH
562 function repchar($text, $notused = 0) {
563 // Escapes 'reserved' characters # = ~ {) :
564 // Removes new lines
565 $reserved = array( '#', '=', '~', '{', '}', ':', "\n", "\r");
566 $escaped = array('\#','\=','\~','\{','\}','\:', '\n', '' );
84769fd8 567
13bb604e
TH
568 $newtext = str_replace($reserved, $escaped, $text);
569 return $newtext;
84769fd8 570 }
571
13bb604e 572 /**
f7970e3c 573 * @param int $format one of the FORMAT_ constants.
13bb604e
TH
574 * @return string the corresponding name.
575 */
576 function format_const_to_name($format) {
577 if ($format == FORMAT_MOODLE) {
578 return 'moodle';
579 } else if ($format == FORMAT_HTML) {
580 return 'html';
581 } else if ($format == FORMAT_PLAIN) {
582 return 'plain';
583 } else if ($format == FORMAT_MARKDOWN) {
584 return 'markdown';
09db6da2 585 } else {
13bb604e 586 return 'moodle';
84769fd8 587 }
13bb604e 588 }
36e2232e 589
13bb604e 590 /**
f7970e3c 591 * @param int $format one of the FORMAT_ constants.
13bb604e
TH
592 * @return string the corresponding name.
593 */
594 function format_name_to_const($format) {
595 if ($format == 'moodle') {
596 return FORMAT_MOODLE;
597 } else if ($format == 'html') {
5b744492 598 return FORMAT_HTML;
13bb604e
TH
599 } else if ($format == 'plain') {
600 return FORMAT_PLAIN;
601 } else if ($format == 'markdown') {
602 return FORMAT_MARKDOWN;
603 } else {
604 return -1;
84769fd8 605 }
13bb604e
TH
606 }
607
608 public function write_name($name) {
609 return '::' . $this->repchar($name) . '::';
610 }
611
5b744492 612 public function write_questiontext($text, $format, $defaultformat = FORMAT_MOODLE) {
13bb604e 613 $output = '';
5b744492 614 if ($text != '' && $format != $defaultformat) {
13bb604e 615 $output .= '[' . $this->format_const_to_name($format) . ']';
84769fd8 616 }
13bb604e
TH
617 $output .= $this->repchar($text, $format);
618 return $output;
619 }
620
621 function writequestion($question) {
d649fb02 622 global $OUTPUT;
13bb604e
TH
623
624 // Start with a comment
5b744492 625 $expout = "// question: $question->id name: $question->name\n";
13bb604e
TH
626
627 // output depends on question type
628 switch($question->qtype) {
629
630 case 'category':
631 // not a real question, used to insert category switch
632 $expout .= "\$CATEGORY: $question->category\n";
633 break;
634
635 case DESCRIPTION:
636 $expout .= $this->write_name($question->name);
637 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
638 break;
639
640 case ESSAY:
641 $expout .= $this->write_name($question->name);
642 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
643 $expout .= "{}\n";
644 break;
645
646 case TRUEFALSE:
647 $trueanswer = $question->options->answers[$question->options->trueanswer];
648 $falseanswer = $question->options->answers[$question->options->falseanswer];
649 if ($trueanswer->fraction == 1) {
650 $answertext = 'TRUE';
5b744492
TH
651 $rightfeedback = $this->write_questiontext($trueanswer->feedback,
652 $trueanswer->feedbackformat, $question->questiontextformat);
653 $wrongfeedback = $this->write_questiontext($falseanswer->feedback,
654 $falseanswer->feedbackformat, $question->questiontextformat);
13bb604e
TH
655 } else {
656 $answertext = 'FALSE';
5b744492
TH
657 $rightfeedback = $this->write_questiontext($falseanswer->feedback,
658 $falseanswer->feedbackformat, $question->questiontextformat);
659 $wrongfeedback = $this->write_questiontext($trueanswer->feedback,
660 $trueanswer->feedbackformat, $question->questiontextformat);
13bb604e
TH
661 }
662
13bb604e
TH
663 $expout .= $this->write_name($question->name);
664 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
665 $expout .= '{' . $this->repchar($answertext);
5b744492
TH
666 if ($wrongfeedback) {
667 $expout .= '#' . $wrongfeedback;
668 } else if ($rightfeedback) {
13bb604e 669 $expout .= '#';
84769fd8 670 }
5b744492
TH
671 if ($rightfeedback) {
672 $expout .= '#' . $rightfeedback;
84769fd8 673 }
13bb604e
TH
674 $expout .= "}\n";
675 break;
676
677 case MULTICHOICE:
678 $expout .= $this->write_name($question->name);
679 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
680 $expout .= "{\n";
681 foreach($question->options->answers as $answer) {
682 if ($answer->fraction == 1) {
683 $answertext = '=';
684 } else if ($answer->fraction == 0) {
685 $answertext = '~';
686 } else {
687 $weight = $answer->fraction * 100;
688 $answertext = '~%' . $weight . '%';
689 }
5b744492
TH
690 $expout .= "\t" . $answertext . $this->write_questiontext($answer->answer,
691 $answer->answerformat, $question->questiontextformat);
13bb604e 692 if ($answer->feedback != '') {
5b744492
TH
693 $expout .= '#' . $this->write_questiontext($answer->feedback,
694 $answer->feedbackformat, $question->questiontextformat);
13bb604e
TH
695 }
696 $expout .= "\n";
84769fd8 697 }
13bb604e
TH
698 $expout .= "}\n";
699 break;
700
701 case SHORTANSWER:
702 $expout .= $this->write_name($question->name);
703 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
704 $expout .= "{\n";
705 foreach($question->options->answers as $answer) {
706 $weight = 100 * $answer->fraction;
707 $expout .= "\t=%" . $weight . '%' . $this->repchar($answer->answer) .
5b744492
TH
708 '#' . $this->write_questiontext($answer->feedback,
709 $answer->feedbackformat, $question->questiontextformat) . "\n";
84769fd8 710 }
13bb604e
TH
711 $expout .= "}\n";
712 break;
713
714 case NUMERICAL:
715 $expout .= $this->write_name($question->name);
716 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
717 $expout .= "{#\n";
718 foreach ($question->options->answers as $answer) {
719 if ($answer->answer != '' && $answer->answer != '*') {
720 $weight = 100 * $answer->fraction;
721 $expout .= "\t=%" . $weight . '%' . $answer->answer . ':' .
5b744492
TH
722 (float)$answer->tolerance . '#' . $this->write_questiontext($answer->feedback,
723 $answer->feedbackformat, $question->questiontextformat) . "\n";
13bb604e 724 } else {
5b744492
TH
725 $expout .= "\t~#" . $this->write_questiontext($answer->feedback,
726 $answer->feedbackformat, $question->questiontextformat) . "\n";
13e88db4 727 }
13bb604e
TH
728 }
729 $expout .= "}\n";
730 break;
731
732 case MATCH:
733 $expout .= $this->write_name($question->name);
734 $expout .= $this->write_questiontext($question->questiontext, $question->questiontextformat);
735 $expout .= "{\n";
736 foreach($question->options->subquestions as $subquestion) {
5b744492 737 $expout .= "\t=" . $this->repchar($this->write_questiontext($subquestion->questiontext, $subquestion->questiontextformat, $question->questiontextformat)) .
13bb604e
TH
738 ' -> ' . $this->repchar($subquestion->answertext) . "\n";
739 }
740 $expout .= "}\n";
741 break;
742
743 default:
744 // Check for plugins
745 if ($out = $this->try_exporting_using_qtypes($question->qtype, $question)) {
746 $expout .= $out;
1fe641f7 747 } else {
13bb604e
TH
748 $expout .= "Question type $question->qtype is not supported\n";
749 echo $OUTPUT->notification(get_string('nohandler', 'qformat_gift',
d649fb02 750 question_bank::get_qtype_name($question->qtype)));
1fe641f7 751 }
752 }
13bb604e
TH
753
754 // Add empty line to delimit questions
755 $expout .= "\n";
756 return $expout;
84769fd8 757 }
84769fd8 758}