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