2 ////////////////////////////////////////////////////////////////////////////
3 /// Hotpotatoes 5.0 and 6.0 Format
5 /// This Moodle class provides all functions necessary to import
6 /// (export is not implemented ... yet)
8 ////////////////////////////////////////////////////////////////////////////
10 // Based on default.php, included by ../import.php
12 * @package questionbank
13 * @subpackage importexport
16 class qformat_hotpot
extends qformat_default
{
18 function provide_import() {
22 function readquestions ($lines) {
23 /// Parses an array of lines into an array of questions,
24 /// where each item is a question object as defined by
27 // set courseid and baseurl
28 global $CFG, $COURSE, $course;
30 case isset($this->course
->id
):
31 // import to quiz module
32 $courseid = $this->course
->id
;
34 case isset($course->id
):
35 // import to lesson module
36 $courseid = $course->id
;
38 case isset($COURSE->id
):
40 $courseid = $COURSE->id
;
43 // shouldn't happen !!
46 require_once($CFG->libdir
.'/filelib.php');
47 $baseurl = get_file_url($courseid).'/';
49 // get import file name
51 if (isset($params) && !empty($params->choosefile
)) {
52 // course file (Moodle >=1.6+)
53 $filename = $params->choosefile
;
55 // uploaded file (all Moodles)
56 $filename = basename($_FILES['newfile']['tmp_name']);
59 // get hotpot file source
60 $source = implode($lines, " ");
61 $source = hotpot_convert_relative_urls($source, $baseurl, $filename);
63 // create xml tree for this hotpot
64 $xml = new hotpot_xml_tree($source);
66 // determine the quiz type
68 $keys = array_keys($xml->xml
);
69 foreach ($keys as $key) {
70 if (preg_match('/^(hotpot|textoys)-(\w+)-file$/i', $key, $matches)) {
71 $xml->quiztype
= strtolower($matches[2]);
72 $xml->xml_root
= "['$key']['#']";
77 // convert xml to questions array
79 switch ($xml->quiztype
) {
81 $this->process_jcloze($xml, $questions);
84 $this->process_jcross($xml, $questions);
87 $this->process_jmatch($xml, $questions);
90 $this->process_jmix($xml, $questions);
94 $this->process_jquiz($xml, $questions);
97 if (empty($xml->quiztype
)) {
98 notice("Input file not recognized as a Hot Potatoes XML file");
100 notice("Unknown quiz type '$xml->quiztype'");
106 function process_jcloze(&$xml, &$questions) {
107 // define default grade (per cloze gap)
111 // detect old Moodles (1.4 and earlier)
114 if ($columns = $db->MetaColumns("{$CFG->prefix}question_multianswer")) {
115 foreach ($columns as $column) {
116 if ($column->name
=='answers' ||
$column->name
=='positionkey' ||
$column->name
=='answertype' ||
$column->name
=='norm') {
122 // xml tags for the start of the gap-fill exercise
123 $tags = 'data,gap-fill';
126 while (($exercise = "[$x]['#']") && $xml->xml_value($tags, $exercise)) {
127 // there is usually only one exercise in a file
129 if (method_exists($this, 'defaultquestion')) {
130 $question = $this->defaultquestion();
132 $question = new stdClass();
133 $question->usecase
= 0; // Ignore case
134 $question->image
= ""; // No images with this format
136 $question->qtype
= MULTIANSWER
;
138 $question->name
= $this->hotpot_get_title($xml, $x);
139 $question->questiontext
= $this->hotpot_get_reading($xml);
141 // setup answer arrays
143 $question->answers
= array();
145 global $COURSE; // initialized in questions/import.php
146 $question->course
= $COURSE->id
;
147 $question->options
= new stdClass();
148 $question->options
->questions
= array(); // one for each gap
152 while ($text = $xml->xml_value($tags, $exercise."[$q]")) {
153 // add next bit of text
154 $question->questiontext
.= $this->hotpot_prepare_str($text);
157 $question_record = $exercise."['question-record'][$q]['#']";
158 if ($xml->xml_value($tags, $question_record)) {
163 $question->questiontext
.= '{#'.$positionkey.'}';
165 // initialize answer settings
167 $question->answers
[$q]->positionkey
= $positionkey;
168 $question->answers
[$q]->answertype
= SHORTANSWER
;
169 $question->answers
[$q]->norm
= $defaultgrade;
170 $question->answers
[$q]->alternatives
= array();
172 $wrapped = new stdClass();
173 $wrapped->qtype
= SHORTANSWER
;
174 $wrapped->usecase
= 0;
175 $wrapped->defaultgrade
= $defaultgrade;
176 $wrapped->questiontextformat
= 0;
177 $wrapped->answer
= array();
178 $wrapped->fraction
= array();
179 $wrapped->feedback
= array();
185 while (($answer=$question_record."['answer'][$a]['#']") && $xml->xml_value($tags, $answer)) {
186 $text = $this->hotpot_prepare_str($xml->xml_value($tags, $answer."['text'][0]['#']"));
187 $correct = $xml->xml_value($tags, $answer."['correct'][0]['#']");
188 $feedback = $this->hotpot_prepare_str($xml->xml_value($tags, $answer."['feedback'][0]['#']"));
190 // set score (0=0%, 1=100%)
191 $fraction = empty($correct) ?
0 : 1;
194 $question->answers
[$q]->alternatives
[$a] = new stdClass();
195 $question->answers
[$q]->alternatives
[$a]->answer
= $text;
196 $question->answers
[$q]->alternatives
[$a]->fraction
= $fraction;
197 $question->answers
[$q]->alternatives
[$a]->feedback
= $feedback;
199 $wrapped->answer
[] = $text;
200 $wrapped->fraction
[] = $fraction;
201 $wrapped->feedback
[] = $feedback;
202 $answers[] = (empty($fraction) ?
'' : '=').$text.(empty($feedback) ?
'' : ('#'.$feedback));
207 // compile answers into question text, if necessary
211 $wrapped->questiontext
= '{'.$defaultgrade.':SHORTANSWER:'.implode('~', $answers).'}';
212 $question->options
->questions
[] = $wrapped;
218 // define total grade for this exercise
219 $question->defaultgrade
= $gap_count * $defaultgrade;
221 $questions[] = $question;
223 } // end while $exercise
226 function process_jcross(&$xml, &$questions) {
227 // xml tags to the start of the crossword exercise clue items
228 $tags = 'data,crossword,clues,item';
231 while (($item = "[$x]['#']") && $xml->xml_value($tags, $item)) {
233 $text = $xml->xml_value($tags, $item."['def'][0]['#']");
234 $answer = $xml->xml_value($tags, $item."['word'][0]['#']");
236 if ($text && $answer) {
237 if (method_exists($this, 'defaultquestion')) {
238 $question = $this->defaultquestion();
240 $question = new stdClass();
241 $question->usecase
= 0; // Ignore case
242 $question->image
= ""; // No images with this format
244 $question->qtype
= SHORTANSWER
;
245 $question->name
= $this->hotpot_get_title($xml, $x, true);
247 $question->questiontext
= $this->hotpot_prepare_str($text);
248 $question->answer
= array($this->hotpot_prepare_str($answer));
249 $question->fraction
= array(1);
250 $question->feedback
= array('');
252 $questions[] = $question;
258 function process_jmatch(&$xml, &$questions) {
259 // define default grade (per matched pair)
263 // xml tags to the start of the matching exercise
264 $tags = 'data,matching-exercise';
267 while (($exercise = "[$x]['#']") && $xml->xml_value($tags, $exercise)) {
268 // there is usually only one exercise in a file
270 if (method_exists($this, 'defaultquestion')) {
271 $question = $this->defaultquestion();
273 $question = new stdClass();
274 $question->usecase
= 0; // Ignore case
275 $question->image
= ""; // No images with this format
277 $question->qtype
= MATCH
;
278 $question->name
= $this->hotpot_get_title($xml, $x);
280 $question->questiontext
= $this->hotpot_get_reading($xml);
281 $question->questiontext
.= $this->hotpot_get_instructions($xml);
283 $question->subquestions
= array();
284 $question->subanswers
= array();
286 while (($pair = $exercise."['pair'][$p]['#']") && $xml->xml_value($tags, $pair)) {
287 $left = $xml->xml_value($tags, $pair."['left-item'][0]['#']['text'][0]['#']");
288 $right = $xml->xml_value($tags, $pair."['right-item'][0]['#']['text'][0]['#']");
289 if ($left && $right) {
291 $question->subquestions
[$p] = $this->hotpot_prepare_str($left);
292 $question->subanswers
[$p] = $this->hotpot_prepare_str($right);
296 $question->defaultgrade
= $match_count * $defaultgrade;
297 $questions[] = $question;
302 function process_jmix(&$xml, &$questions) {
303 // define default grade (per segment)
307 // xml tags to the start of the jumbled order exercise
308 $tags = 'data,jumbled-order-exercise';
311 while (($exercise = "[$x]['#']") && $xml->xml_value($tags, $exercise)) {
312 // there is usually only one exercise in a file
314 if (method_exists($this, 'defaultquestion')) {
315 $question = $this->defaultquestion();
317 $question = new stdClass();
318 $question->usecase
= 0; // Ignore case
319 $question->image
= ""; // No images with this format
321 $question->qtype
= SHORTANSWER
;
322 $question->name
= $this->hotpot_get_title($xml, $x);
324 $question->answer
= array();
325 $question->fraction
= array();
326 $question->feedback
= array();
330 while ($segment = $xml->xml_value($tags, $exercise."['main-order'][0]['#']['segment'][$i]['#']")) {
331 $segments[] = $this->hotpot_prepare_str($segment);
335 $answer = implode(' ', $segments);
337 $this->hotpot_seed_RNG();
340 $question->questiontext
= $this->hotpot_get_reading($xml);
341 $question->questiontext
.= $this->hotpot_get_instructions($xml);
342 $question->questiontext
.= ' <NOBR><B>[ '.implode(' ', $segments).' ]</B></NOBR>';
345 while (!empty($answer)) {
346 $question->answer
[$a] = $answer;
347 $question->fraction
[$a] = 1;
348 $question->feedback
[$a] = '';
349 $answer = $this->hotpot_prepare_str($xml->xml_value($tags, $exercise."['alternate'][$a]['#']"));
352 $question->defaultgrade
= $segment_count * $defaultgrade;
353 $questions[] = $question;
357 function process_jquiz(&$xml, &$questions) {
358 // define default grade (per question)
361 // xml tags to the start of the questions
362 $tags = 'data,questions';
365 while (($exercise = "[$x]['#']") && $xml->xml_value($tags, $exercise)) {
366 // there is usually only one 'questions' object in a single exercise
369 while (($question_record = $exercise."['question-record'][$q]['#']") && $xml->xml_value($tags, $question_record)) {
371 if (method_exists($this, 'defaultquestion')) {
372 $question = $this->defaultquestion();
374 $question = new stdClass();
375 $question->usecase
= 0; // Ignore case
376 $question->image
= ""; // No images with this format
378 $question->defaultgrade
= $defaultgrade;
379 $question->name
= $this->hotpot_get_title($xml, $q, true);
381 $text = $xml->xml_value($tags, $question_record."['question'][0]['#']");
382 $question->questiontext
= $this->hotpot_prepare_str($text);
384 if ($xml->xml_value($tags, $question_record."['answers']")) {
386 $answers = $question_record."['answers'][0]['#']";
389 $answers = $question_record;
391 if($xml->xml_value($tags, $question_record."['question-type']")) {
393 $type = $xml->xml_value($tags, $question_record."['question-type'][0]['#']");
394 // 1 : multiple choice
397 // 4 : multiple select
400 switch ($xml->quiztype
) {
402 $must_select_all = $xml->xml_value($tags, $question_record."['must-select-all'][0]['#']");
403 if (empty($must_select_all)) {
404 $type = 1; // multichoice
406 $type = 4; // multiselect
410 $type = 2; // shortanswer
413 $type = 0; // unknown
416 $question->qtype
= ($type==2 ? SHORTANSWER
: MULTICHOICE
);
417 $question->single
= ($type==4 ?
0 : 1);
419 // workaround required to calculate scores for multiple select answers
420 $no_of_correct_answers = 0;
423 while (($answer = $answers."['answer'][$a]['#']") && $xml->xml_value($tags, $answer)) {
424 $correct = $xml->xml_value($tags, $answer."['correct'][0]['#']");
425 if (empty($correct)) {
428 $no_of_correct_answers++
;
434 $question->answer
= array();
435 $question->fraction
= array();
436 $question->feedback
= array();
438 $correct_answers = array();
439 $correct_answers_all_zero = true;
440 while (($answer = $answers."['answer'][$a]['#']") && $xml->xml_value($tags, $answer)) {
441 $correct = $xml->xml_value($tags, $answer."['correct'][0]['#']");
442 if (empty($correct)) {
444 } else if ($type==4) { // multiple select
445 // strange behavior if the $fraction isn't exact to 5 decimal places
446 $fraction = round(1/$no_of_correct_answers, 5);
448 if ($xml->xml_value($tags, $answer."['percent-correct']")) {
450 $percent = $xml->xml_value($tags, $answer."['percent-correct'][0]['#']");
451 $fraction = $percent/100;
457 $answertext = $this->hotpot_prepare_str($xml->xml_value($tags, $answer."['text'][0]['#']"));
458 if ($answertext!='') {
459 $question->answer
[$aa] = $answertext;
460 $question->fraction
[$aa] = $fraction;
461 $question->feedback
[$aa] = $this->hotpot_prepare_str($xml->xml_value($tags, $answer."['feedback'][0]['#']"));
464 $correct_answers_all_zero = false;
466 $correct_answers[] = $aa;
472 if ($correct_answers_all_zero) {
473 // correct answers all have score of 0%,
474 // so reset score for correct answers 100%
475 foreach ($correct_answers as $aa) {
476 $question->fraction
[$aa] = 1;
479 $questions[] = $question;
486 function hotpot_seed_RNG() {
487 // seed the random number generator
488 static $HOTPOT_SEEDED_RNG = FALSE;
489 if (!$HOTPOT_SEEDED_RNG) {
490 srand((double) microtime() * 1000000);
491 $HOTPOT_SEEDED_RNG = TRUE;
494 function hotpot_get_title(&$xml, $x, $flag=false) {
495 $title = $xml->xml_value('data,title');
497 $title .= ' ('.($x+
1).')';
499 return $this->hotpot_prepare_str($title);
501 function hotpot_get_instructions(&$xml) {
502 $text = $xml->xml_value('hotpot-config-file,instructions');
504 $text = "Hot Potatoes $xml->quiztype";
506 return $this->hotpot_prepare_str($text);
508 function hotpot_get_reading(&$xml) {
510 $tags = 'data,reading';
511 if ($xml->xml_value("$tags,include-reading")) {
512 if ($title = $xml->xml_value("$tags,reading-title")) {
513 $str .= "<H3>$title</H3>";
515 if ($text = $xml->xml_value("$tags,reading-text")) {
516 $str .= "<P>$text</P>";
519 return $this->hotpot_prepare_str($str);
521 function hotpot_prepare_str($str) {
522 // convert html entities to unicode and add slashes
523 $str = preg_replace('/&#x([0-9a-f]+);/ie', "hotpot_charcode_to_utf8(hexdec('\\1'))", $str);
524 $str = preg_replace('/&#([0-9]+);/e', "hotpot_charcode_to_utf8(\\1)", $str);
525 return addslashes($str);
529 // get the standard XML parser supplied with Moodle
530 require_once("$CFG->libdir/xmlize.php");
532 class hotpot_xml_tree
{
533 function hotpot_xml_tree($str, $xml_root='') {
535 $this->xml
= array();
537 // encode htmlentities in JCloze
538 $this->encode_cdata($str, 'gap-fill');
539 // xmlize (=convert xml to tree)
540 $this->xml
= xmlize($str, 0);
542 $this->xml_root
= $xml_root;
544 function xml_value($tags, $more_tags="[0]['#']") {
546 $tags = empty($tags) ?
'' : "['".str_replace(",", "'][0]['#']['", $tags)."']";
547 eval('$value = &$this->xml'.$this->xml_root
.$tags.$more_tags.';');
549 if (is_string($value)) {
551 // decode angle brackets and ampersands
552 $value = strtr($value, array('<'=>'<', '>'=>'>', '&'=>'&'));
554 // remove white space between <table>, <ul|OL|DL> and <OBJECT|EMBED> parts
555 // (so it doesn't get converted to <br />)
557 . 'TABLE|/?CAPTION|/?COL|/?COLGROUP|/?TBODY|/?TFOOT|/?THEAD|/?TD|/?TH|/?TR'
560 . '|EMBED|OBJECT|APPLET|/?PARAM'
561 //. '|SELECT|/?OPTION'
562 //. '|FIELDSET|/?LEGEND'
563 //. '|FRAMESET|/?FRAME'
566 $search = '#(<'.$htmltags.'[^>]*'.'>)\s+'.'(?='.'<'.')#is';
567 $value = preg_replace($search, '\\1', $value);
569 // replace remaining newlines with <br />
570 $value = str_replace("\n", '<br />', $value);
572 // encode unicode characters as HTML entities
573 // (in particular, accented charaters that have not been encoded by HP)
575 // multibyte unicode characters can be detected by checking the hex value of the first character
576 // 00 - 7F : ascii char (roman alphabet + punctuation)
577 // 80 - BF : byte 2, 3 or 4 of a unicode char
578 // C0 - DF : 1st byte of 2-byte char
579 // E0 - EF : 1st byte of 3-byte char
580 // F0 - FF : 1st byte of 4-byte char
581 // if the string doesn't match the above, it might be
582 // 80 - FF : single-byte, non-ascii char
583 $search = '#('.'[\xc0-\xdf][\x80-\xbf]'.'|'.'[\xe0-\xef][\x80-\xbf]{2}'.'|'.'[\xf0-\xff][\x80-\xbf]{3}'.'|'.'[\x80-\xff]'.')#se';
584 $value = preg_replace($search, "hotpot_utf8_to_html_entity('\\1')", $value);
588 function encode_cdata(&$str, $tag) {
591 static $HTML_ENTITIES = array(
598 static $ILLEGAL_STRINGS = array(
600 "\n" => '<br />',
601 ']]>' => ']]>',
604 // extract the $tag from the $str(ing), if possible
605 $pattern = '|(^.*<'.$tag.'[^>]*)(>.*<)(/'.$tag.'>.*$)|is';
606 if (preg_match($pattern, $str, $matches)) {
608 // encode problematic CDATA chars and strings
609 $matches[2] = strtr($matches[2], $ILLEGAL_STRINGS);
612 // if there are any ampersands in "open text"
613 // surround them by CDATA start and end markers
614 // (and convert HTML entities to plain text)
615 $search = '/>([^<]*&[^<]*)</e';
616 $replace = '"><![CDATA[".strtr("$1", $HTML_ENTITIES)."]]><"';
617 $matches[2] = preg_replace($search, $replace, $matches[2]);
619 $str = $matches[1].$matches[2].$matches[3];
624 function hotpot_charcode_to_utf8($charcode) {
625 if ($charcode <= 0x7F) {
626 // ascii char (roman alphabet + punctuation)
627 return chr($charcode);
629 if ($charcode <= 0x7FF) {
631 return chr(($charcode >> 0x06) +
0xC0).chr(($charcode & 0x3F) +
128);
633 if ($charcode <= 0xFFFF) {
635 return chr(($charcode >> 0x0C) +
0xE0).chr((($charcode >> 0x06) & 0x3F) +
0x80).chr(($charcode & 0x3F) +
0x80);
637 if ($charcode <= 0x1FFFFF) {
639 return chr(($charcode >> 0x12) +
0xF0).chr((($charcode >> 0x0C) & 0x3F) +
0x80).chr((($charcode >> 0x06) & 0x3F) +
0x80).chr(($charcode & 0x3F) +
0x80);
641 // unidentified char code !!
645 function hotpot_utf8_to_html_entity($char) {
646 // http://www.zend.com/codex.php?id=835&single=1
648 // array used to figure what number to decrement from character order value
649 // according to number of characters used to map unicode to ascii by utf-8
650 static $HOTPOT_UTF8_DECREMENT = array(
651 1=>0, 2=>192, 3=>224, 4=>240
654 // the number of bits to shift each character by
655 static $HOTPOT_UTF8_SHIFT = array(
657 2=>array(0=>6, 1=>0),
658 3=>array(0=>12, 1=>6, 2=>0),
659 4=>array(0=>18, 1=>12, 2=>6, 3=>0)
663 $len = strlen($char);
664 for ($pos=0; $pos<$len; $pos++
) {
665 $ord = ord ($char{$pos});
666 $ord -= ($pos ?
128 : $HOTPOT_UTF8_DECREMENT[$len]);
667 $dec +
= ($ord << $HOTPOT_UTF8_SHIFT[$len][$pos]);
669 return '&#x'.sprintf('%04X', $dec).';';
672 function hotpot_convert_relative_urls($str, $baseurl, $filename) {
673 $tagopen = '(?:(<)|(<)|(&#x003C;))'; // left angle bracket
674 $tagclose = '(?(2)>|(?(3)>|(?(4)&#x003E;)))'; // right angle bracket (to match left angle bracket)
676 $space = '\s+'; // at least one space
677 $anychar = '(?:[^>]*?)'; // any character
679 $quoteopen = '("|"|&quot;)'; // open quote
680 $quoteclose = '\\5'; // close quote (to match open quote)
682 $replace = "hotpot_convert_relative_url('".$baseurl."', '".$filename."', '\\1', '\\6', '\\7')";
684 $tags = array('script'=>'src', 'link'=>'href', 'a'=>'href','img'=>'src','param'=>'value', 'object'=>'data', 'embed'=>'src');
685 foreach ($tags as $tag=>$attribute) {
687 $url = '\S+?\.\S+?'; // must include a filename and have no spaces
691 $search = "%($tagopen$tag$space$anychar$attribute=$quoteopen)($url)($quoteclose$anychar$tagclose)%ise";
692 $str = preg_replace($search, $replace, $str);
698 function hotpot_convert_relative_url($baseurl, $filename, $opentag, $url, $closetag, $stripslashes=true) {
700 $opentag = stripslashes($opentag);
701 $url = stripslashes($url);
702 $closetag = stripslashes($closetag);
705 // catch <PARAM name="FlashVars" value="TheSound=soundfile.mp3">
706 // ampersands can appear as "&", "&" or "&#x0026;amp;"
707 if (preg_match('|^'.'\w+=[^&]+'.'('.'&((amp;#x0026;)?amp;)?'.'\w+=[^&]+)*'.'$|', $url)) {
712 // parse the $url into $matches
714 // [2] query string, if any
715 // [3] anchor fragment, if any
716 } else if (preg_match('|^'.'([^?]*)'.'((?:\\?[^#]*)?)'.'((?:#.*)?)'.'$|', $url, $matches)) {
718 $query = $matches[2];
719 $fragment = $matches[3];
721 // there appears to be no query or fragment in this url
728 $url = hotpot_convert_url($baseurl, $filename, $url, false);
732 $search = '#'.'(file|src|thesound)='."([^&]+)".'#ise';
733 $replace = "'\\1='.hotpot_convert_url('".$baseurl."','".$filename."','\\2')";
734 $query = preg_replace($search, $replace, $query);
737 $url = $opentag.$url.$query.$fragment.$closetag;
742 function hotpot_convert_url($baseurl, $filename, $url, $stripslashes=true) {
743 // maintain a cache of converted urls
744 static $HOTPOT_RELATIVE_URLS = array();
747 $url = stripslashes($url);
750 // is this an absolute url? (or javascript pseudo url)
751 if (preg_match('%^(http://|/|javascript:)%i', $url)) {
754 // has this relative url already been converted?
755 } else if (isset($HOTPOT_RELATIVE_URLS[$url])) {
756 $url = $HOTPOT_RELATIVE_URLS[$url];
761 // get the subdirectory, $dir, of the quiz $filename
762 $dir = dirname($filename);
764 // allow for leading "./" and "../"
765 while (preg_match('|^(\.{1,2})/(.*)$|', $url, $matches)) {
766 if ($matches[1]=='..') {
767 $dir = dirname($dir);
772 // add subdirectory, $dir, to $baseurl, if necessary
773 if ($dir && $dir<>'.') {
777 // prefix $url with $baseurl
778 $url = "$baseurl$url";
781 $HOTPOT_RELATIVE_URLS[$relativeurl] = $url;
786 // allow importing in Moodle v1.4 (and less)
787 // same core functions but different class name
788 if (!class_exists("quiz_file_format")) {
789 class quiz_file_format
extends qformat_default
{
790 function readquestions ($lines) {
791 $format = new qformat_hotpot();
792 return $format->readquestions($lines);