Merge branch 'install_master' of git://git.moodle.org/moodle-install
[moodle.git] / question / format.php
blob7dfe33056a940b7ec49a41c0a2b648bee7336749
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.
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 * Defines the base class for question import and export formats.
20 * @package moodlecore
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 /**
31 * Base class for question import and export formats.
33 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class qformat_default {
38 public $displayerrors = true;
39 public $category = null;
40 public $questions = array();
41 public $course = null;
42 public $filename = '';
43 public $realfilename = '';
44 public $matchgrades = 'error';
45 public $catfromfile = 0;
46 public $contextfromfile = 0;
47 public $cattofile = 0;
48 public $contexttofile = 0;
49 public $questionids = array();
50 public $importerrors = 0;
51 public $stoponerror = true;
52 public $translator = null;
53 public $canaccessbackupdata = true;
55 protected $importcontext = null;
57 // functions to indicate import/export functionality
58 // override to return true if implemented
60 /** @return bool whether this plugin provides import functionality. */
61 public function provide_import() {
62 return false;
65 /** @return bool whether this plugin provides export functionality. */
66 public function provide_export() {
67 return false;
70 /** The string mime-type of the files that this plugin reads or writes. */
71 public function mime_type() {
72 return mimeinfo('type', $this->export_file_extension());
75 /**
76 * @return string the file extension (including .) that is normally used for
77 * files handled by this plugin.
79 public function export_file_extension() {
80 return '.txt';
83 /**
84 * Check if the given file is capable of being imported by this plugin.
86 * Note that expensive or detailed integrity checks on the file should
87 * not be performed by this method. Simple file type or magic-number tests
88 * would be suitable.
90 * @param stored_file $file the file to check
91 * @return bool whether this plugin can import the file
93 public function can_import_file($file) {
94 return ($file->get_mimetype() == $this->mime_type());
97 // Accessor methods
99 /**
100 * set the category
101 * @param object category the category object
103 public function setCategory($category) {
104 if (count($this->questions)) {
105 debugging('You shouldn\'t call setCategory after setQuestions');
107 $this->category = $category;
108 $this->importcontext = context::instance_by_id($this->category->contextid);
112 * Set the specific questions to export. Should not include questions with
113 * parents (sub questions of cloze question type).
114 * Only used for question export.
115 * @param array of question objects
117 public function setQuestions($questions) {
118 if ($this->category !== null) {
119 debugging('You shouldn\'t call setQuestions after setCategory');
121 $this->questions = $questions;
125 * set the course class variable
126 * @param course object Moodle course variable
128 public function setCourse($course) {
129 $this->course = $course;
133 * set an array of contexts.
134 * @param array $contexts Moodle course variable
136 public function setContexts($contexts) {
137 $this->contexts = $contexts;
138 $this->translator = new context_to_string_translator($this->contexts);
142 * set the filename
143 * @param string filename name of file to import/export
145 public function setFilename($filename) {
146 $this->filename = $filename;
150 * set the "real" filename
151 * (this is what the user typed, regardless of wha happened next)
152 * @param string realfilename name of file as typed by user
154 public function setRealfilename($realfilename) {
155 $this->realfilename = $realfilename;
159 * set matchgrades
160 * @param string matchgrades error or nearest for grades
162 public function setMatchgrades($matchgrades) {
163 $this->matchgrades = $matchgrades;
167 * set catfromfile
168 * @param bool catfromfile allow categories embedded in import file
170 public function setCatfromfile($catfromfile) {
171 $this->catfromfile = $catfromfile;
175 * set contextfromfile
176 * @param bool $contextfromfile allow contexts embedded in import file
178 public function setContextfromfile($contextfromfile) {
179 $this->contextfromfile = $contextfromfile;
183 * set cattofile
184 * @param bool cattofile exports categories within export file
186 public function setCattofile($cattofile) {
187 $this->cattofile = $cattofile;
191 * set contexttofile
192 * @param bool cattofile exports categories within export file
194 public function setContexttofile($contexttofile) {
195 $this->contexttofile = $contexttofile;
199 * set stoponerror
200 * @param bool stoponerror stops database write if any errors reported
202 public function setStoponerror($stoponerror) {
203 $this->stoponerror = $stoponerror;
207 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
208 * where export files are saved.
210 public function set_can_access_backupdata($canaccess) {
211 $this->canaccessbackupdata = $canaccess;
214 /***********************
215 * IMPORTING FUNCTIONS
216 ***********************/
219 * Handle parsing error
221 protected function error($message, $text='', $questionname='') {
222 $importerrorquestion = get_string('importerrorquestion', 'question');
224 echo "<div class=\"importerror\">\n";
225 echo "<strong>$importerrorquestion $questionname</strong>";
226 if (!empty($text)) {
227 $text = s($text);
228 echo "<blockquote>$text</blockquote>\n";
230 echo "<strong>$message</strong>\n";
231 echo "</div>";
233 $this->importerrors++;
237 * Import for questiontype plugins
238 * Do not override.
239 * @param data mixed The segment of data containing the question
240 * @param question object processed (so far) by standard import code if appropriate
241 * @param extra mixed any additional format specific data that may be passed by the format
242 * @param qtypehint hint about a question type from format
243 * @return object question object suitable for save_options() or false if cannot handle
245 public function try_importing_using_qtypes($data, $question = null, $extra = null,
246 $qtypehint = '') {
248 // work out what format we are using
249 $formatname = substr(get_class($this), strlen('qformat_'));
250 $methodname = "import_from_$formatname";
252 //first try importing using a hint from format
253 if (!empty($qtypehint)) {
254 $qtype = question_bank::get_qtype($qtypehint, false);
255 if (is_object($qtype) && method_exists($qtype, $methodname)) {
256 $question = $qtype->$methodname($data, $question, $this, $extra);
257 if ($question) {
258 return $question;
263 // loop through installed questiontypes checking for
264 // function to handle this question
265 foreach (question_bank::get_all_qtypes() as $qtype) {
266 if (method_exists($qtype, $methodname)) {
267 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
268 return $question;
272 return false;
276 * Perform any required pre-processing
277 * @return bool success
279 public function importpreprocess() {
280 return true;
284 * Process the file
285 * This method should not normally be overidden
286 * @param object $category
287 * @return bool success
289 public function importprocess($category) {
290 global $USER, $CFG, $DB, $OUTPUT;
292 // reset the timer in case file upload was slow
293 set_time_limit(0);
295 // STAGE 1: Parse the file
296 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
298 if (! $lines = $this->readdata($this->filename)) {
299 echo $OUTPUT->notification(get_string('cannotread', 'question'));
300 return false;
303 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
304 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
305 return false;
308 // STAGE 2: Write data to database
309 echo $OUTPUT->notification(get_string('importingquestions', 'question',
310 $this->count_questions($questions)), 'notifysuccess');
312 // check for errors before we continue
313 if ($this->stoponerror and ($this->importerrors>0)) {
314 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
315 return true;
318 // get list of valid answer grades
319 $gradeoptionsfull = question_bank::fraction_options_full();
321 // check answer grades are valid
322 // (now need to do this here because of 'stop on error': MDL-10689)
323 $gradeerrors = 0;
324 $goodquestions = array();
325 foreach ($questions as $question) {
326 if (!empty($question->fraction) and (is_array($question->fraction))) {
327 $fractions = $question->fraction;
328 $invalidfractions = array();
329 foreach ($fractions as $key => $fraction) {
330 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
331 $this->matchgrades);
332 if ($newfraction === false) {
333 $invalidfractions[] = $fraction;
334 } else {
335 $fractions[$key] = $newfraction;
338 if ($invalidfractions) {
339 echo $OUTPUT->notification(get_string('invalidgrade', 'question',
340 implode(', ', $invalidfractions)));
341 ++$gradeerrors;
342 continue;
343 } else {
344 $question->fraction = $fractions;
347 $goodquestions[] = $question;
349 $questions = $goodquestions;
351 // check for errors before we continue
352 if ($this->stoponerror && $gradeerrors > 0) {
353 return false;
356 // count number of questions processed
357 $count = 0;
359 foreach ($questions as $question) { // Process and store each question
361 // reset the php timeout
362 set_time_limit(0);
364 // check for category modifiers
365 if ($question->qtype == 'category') {
366 if ($this->catfromfile) {
367 // find/create category object
368 $catpath = $question->category;
369 $newcategory = $this->create_category_path($catpath);
370 if (!empty($newcategory)) {
371 $this->category = $newcategory;
374 continue;
376 $question->context = $this->importcontext;
378 $count++;
380 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
382 $question->category = $this->category->id;
383 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
385 $question->createdby = $USER->id;
386 $question->timecreated = time();
387 $question->modifiedby = $USER->id;
388 $question->timemodified = time();
389 $fileoptions = array(
390 'subdirs' => false,
391 'maxfiles' => -1,
392 'maxbytes' => 0,
395 $question->id = $DB->insert_record('question', $question);
397 if (isset($question->questiontextitemid)) {
398 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
399 $this->importcontext->id, 'question', 'questiontext', $question->id,
400 $fileoptions, $question->questiontext);
401 } else if (isset($question->questiontextfiles)) {
402 foreach ($question->questiontextfiles as $file) {
403 question_bank::get_qtype($question->qtype)->import_file(
404 $this->importcontext, 'question', 'questiontext', $question->id, $file);
407 if (isset($question->generalfeedbackitemid)) {
408 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
409 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
410 $fileoptions, $question->generalfeedback);
411 } else if (isset($question->generalfeedbackfiles)) {
412 foreach ($question->generalfeedbackfiles as $file) {
413 question_bank::get_qtype($question->qtype)->import_file(
414 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
417 $DB->update_record('question', $question);
419 $this->questionids[] = $question->id;
421 // Now to save all the answers and type-specific options
423 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
425 if (!empty($CFG->usetags) && isset($question->tags)) {
426 require_once($CFG->dirroot . '/tag/lib.php');
427 tag_set('question', $question->id, $question->tags);
430 if (!empty($result->error)) {
431 echo $OUTPUT->notification($result->error);
432 return false;
435 if (!empty($result->notice)) {
436 echo $OUTPUT->notification($result->notice);
437 return true;
440 // Give the question a unique version stamp determined by question_hash()
441 $DB->set_field('question', 'version', question_hash($question),
442 array('id' => $question->id));
444 return true;
448 * Count all non-category questions in the questions array.
450 * @param array questions An array of question objects.
451 * @return int The count.
454 protected function count_questions($questions) {
455 $count = 0;
456 if (!is_array($questions)) {
457 return $count;
459 foreach ($questions as $question) {
460 if (!is_object($question) || !isset($question->qtype) ||
461 ($question->qtype == 'category')) {
462 continue;
464 $count++;
466 return $count;
470 * find and/or create the category described by a delimited list
471 * e.g. $course$/tom/dick/harry or tom/dick/harry
473 * removes any context string no matter whether $getcontext is set
474 * but if $getcontext is set then ignore the context and use selected category context.
476 * @param string catpath delimited category path
477 * @param int courseid course to search for categories
478 * @return mixed category object or null if fails
480 protected function create_category_path($catpath) {
481 global $DB;
482 $catnames = $this->split_category_path($catpath);
483 $parent = 0;
484 $category = null;
486 // check for context id in path, it might not be there in pre 1.9 exports
487 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
488 if ($matchcount == 1) {
489 $contextid = $this->translator->string_to_context($matches[1]);
490 array_shift($catnames);
491 } else {
492 $contextid = false;
495 if ($this->contextfromfile && $contextid !== false) {
496 $context = context::instance_by_id($contextid);
497 require_capability('moodle/question:add', $context);
498 } else {
499 $context = context::instance_by_id($this->category->contextid);
501 $this->importcontext = $context;
503 // Now create any categories that need to be created.
504 foreach ($catnames as $catname) {
505 if ($category = $DB->get_record('question_categories',
506 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
507 $parent = $category->id;
508 } else {
509 require_capability('moodle/question:managecategory', $context);
510 // create the new category
511 $category = new stdClass();
512 $category->contextid = $context->id;
513 $category->name = $catname;
514 $category->info = '';
515 $category->parent = $parent;
516 $category->sortorder = 999;
517 $category->stamp = make_unique_id_code();
518 $id = $DB->insert_record('question_categories', $category);
519 $category->id = $id;
520 $parent = $id;
523 return $category;
527 * Return complete file within an array, one item per line
528 * @param string filename name of file
529 * @return mixed contents array or false on failure
531 protected function readdata($filename) {
532 if (is_readable($filename)) {
533 $filearray = file($filename);
535 // If the first line of the file starts with a UTF-8 BOM, remove it.
536 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
538 // Check for Macintosh OS line returns (ie file on one line), and fix.
539 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
540 return explode("\r", $filearray[0]);
541 } else {
542 return $filearray;
545 return false;
549 * Parses an array of lines into an array of questions,
550 * where each item is a question object as defined by
551 * readquestion(). Questions are defined as anything
552 * between blank lines.
554 * NOTE this method used to take $context as a second argument. However, at
555 * the point where this method was called, it was impossible to know what
556 * context the quetsions were going to be saved into, so the value could be
557 * wrong. Also, none of the standard question formats were using this argument,
558 * so it was removed. See MDL-32220.
560 * If your format does not use blank lines as a delimiter
561 * then you will need to override this method. Even then
562 * try to use readquestion for each question
563 * @param array lines array of lines from readdata
564 * @return array array of question objects
566 protected function readquestions($lines) {
568 $questions = array();
569 $currentquestion = array();
571 foreach ($lines as $line) {
572 $line = trim($line);
573 if (empty($line)) {
574 if (!empty($currentquestion)) {
575 if ($question = $this->readquestion($currentquestion)) {
576 $questions[] = $question;
578 $currentquestion = array();
580 } else {
581 $currentquestion[] = $line;
585 if (!empty($currentquestion)) { // There may be a final question
586 if ($question = $this->readquestion($currentquestion)) {
587 $questions[] = $question;
591 return $questions;
595 * return an "empty" question
596 * Somewhere to specify question parameters that are not handled
597 * by import but are required db fields.
598 * This should not be overridden.
599 * @return object default question
601 protected function defaultquestion() {
602 global $CFG;
603 static $defaultshuffleanswers = null;
604 if (is_null($defaultshuffleanswers)) {
605 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
608 $question = new stdClass();
609 $question->shuffleanswers = $defaultshuffleanswers;
610 $question->defaultmark = 1;
611 $question->image = "";
612 $question->usecase = 0;
613 $question->multiplier = array();
614 $question->questiontextformat = FORMAT_MOODLE;
615 $question->generalfeedback = '';
616 $question->generalfeedbackformat = FORMAT_MOODLE;
617 $question->correctfeedback = '';
618 $question->partiallycorrectfeedback = '';
619 $question->incorrectfeedback = '';
620 $question->answernumbering = 'abc';
621 $question->penalty = 0.3333333;
622 $question->length = 1;
624 // this option in case the questiontypes class wants
625 // to know where the data came from
626 $question->export_process = true;
627 $question->import_process = true;
629 return $question;
633 * Construct a reasonable default question name, based on the start of the question text.
634 * @param string $questiontext the question text.
635 * @param string $default default question name to use if the constructed one comes out blank.
636 * @return string a reasonable question name.
638 public function create_default_question_name($questiontext, $default) {
639 $name = $this->clean_question_name(shorten_text($questiontext, 80));
640 if ($name) {
641 return $name;
642 } else {
643 return $default;
648 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
649 * @param string $name the raw question name.
650 * @return string a safe question name.
652 public function clean_question_name($name) {
653 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
654 $name = trim($name);
655 $trimlength = 251;
656 while (core_text::strlen($name) > 255 && $trimlength > 0) {
657 $name = shorten_text($name, $trimlength);
658 $trimlength -= 10;
660 return $name;
664 * Add a blank combined feedback to a question object.
665 * @param object question
666 * @return object question
668 protected function add_blank_combined_feedback($question) {
669 $question->correctfeedback['text'] = '';
670 $question->correctfeedback['format'] = $question->questiontextformat;
671 $question->correctfeedback['files'] = array();
672 $question->partiallycorrectfeedback['text'] = '';
673 $question->partiallycorrectfeedback['format'] = $question->questiontextformat;
674 $question->partiallycorrectfeedback['files'] = array();
675 $question->incorrectfeedback['text'] = '';
676 $question->incorrectfeedback['format'] = $question->questiontextformat;
677 $question->incorrectfeedback['files'] = array();
678 return $question;
682 * Given the data known to define a question in
683 * this format, this function converts it into a question
684 * object suitable for processing and insertion into Moodle.
686 * If your format does not use blank lines to delimit questions
687 * (e.g. an XML format) you must override 'readquestions' too
688 * @param $lines mixed data that represents question
689 * @return object question object
691 protected function readquestion($lines) {
693 $formatnotimplemented = get_string('formatnotimplemented', 'question');
694 echo "<p>$formatnotimplemented</p>";
696 return null;
700 * Override if any post-processing is required
701 * @return bool success
703 public function importpostprocess() {
704 return true;
707 /*******************
708 * EXPORT FUNCTIONS
709 *******************/
712 * Provide export functionality for plugin questiontypes
713 * Do not override
714 * @param name questiontype name
715 * @param question object data to export
716 * @param extra mixed any addition format specific data needed
717 * @return string the data to append to export or false if error (or unhandled)
719 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
720 // work out the name of format in use
721 $formatname = substr(get_class($this), strlen('qformat_'));
722 $methodname = "export_to_$formatname";
724 $qtype = question_bank::get_qtype($name, false);
725 if (method_exists($qtype, $methodname)) {
726 return $qtype->$methodname($question, $this, $extra);
728 return false;
732 * Do any pre-processing that may be required
733 * @param bool success
735 public function exportpreprocess() {
736 return true;
740 * Enable any processing to be done on the content
741 * just prior to the file being saved
742 * default is to do nothing
743 * @param string output text
744 * @param string processed output text
746 protected function presave_process($content) {
747 return $content;
751 * Do the export
752 * For most types this should not need to be overrided
753 * @return stored_file
755 public function exportprocess() {
756 global $CFG, $OUTPUT, $DB, $USER;
758 // get the questions (from database) in this category
759 // only get q's with no parents (no cloze subquestions specifically)
760 if ($this->category) {
761 $questions = get_questions_category($this->category, true);
762 } else {
763 $questions = $this->questions;
766 $count = 0;
768 // results are first written into string (and then to a file)
769 // so create/initialize the string here
770 $expout = "";
772 // track which category questions are in
773 // if it changes we will record the category change in the output
774 // file if selected. 0 means that it will get printed before the 1st question
775 $trackcategory = 0;
777 // iterate through questions
778 foreach ($questions as $question) {
779 // used by file api
780 $contextid = $DB->get_field('question_categories', 'contextid',
781 array('id' => $question->category));
782 $question->contextid = $contextid;
784 // do not export hidden questions
785 if (!empty($question->hidden)) {
786 continue;
789 // do not export random questions
790 if ($question->qtype == 'random') {
791 continue;
794 // check if we need to record category change
795 if ($this->cattofile) {
796 if ($question->category != $trackcategory) {
797 $trackcategory = $question->category;
798 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
800 // create 'dummy' question for category export
801 $dummyquestion = new stdClass();
802 $dummyquestion->qtype = 'category';
803 $dummyquestion->category = $categoryname;
804 $dummyquestion->name = 'Switch category to ' . $categoryname;
805 $dummyquestion->id = 0;
806 $dummyquestion->questiontextformat = '';
807 $dummyquestion->contextid = 0;
808 $expout .= $this->writequestion($dummyquestion) . "\n";
812 // export the question displaying message
813 $count++;
815 if (question_has_capability_on($question, 'view', $question->category)) {
816 $expout .= $this->writequestion($question, $contextid) . "\n";
820 // continue path for following error checks
821 $course = $this->course;
822 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
824 // did we actually process anything
825 if ($count==0) {
826 print_error('noquestions', 'question', $continuepath);
829 // final pre-process on exported data
830 $expout = $this->presave_process($expout);
831 return $expout;
835 * get the category as a path (e.g., tom/dick/harry)
836 * @param int id the id of the most nested catgory
837 * @return string the path
839 protected function get_category_path($id, $includecontext = true) {
840 global $DB;
842 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
843 print_error('cannotfindcategory', 'error', '', $id);
845 $contextstring = $this->translator->context_to_string($category->contextid);
847 $pathsections = array();
848 do {
849 $pathsections[] = $category->name;
850 $id = $category->parent;
851 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
853 if ($includecontext) {
854 $pathsections[] = '$' . $contextstring . '$';
857 $path = $this->assemble_category_path(array_reverse($pathsections));
859 return $path;
863 * Convert a list of category names, possibly preceeded by one of the
864 * context tokens like $course$, into a string representation of the
865 * category path.
867 * Names are separated by / delimiters. And /s in the name are replaced by //.
869 * To reverse the process and split the paths into names, use
870 * {@link split_category_path()}.
872 * @param array $names
873 * @return string
875 protected function assemble_category_path($names) {
876 $escapednames = array();
877 foreach ($names as $name) {
878 $escapedname = str_replace('/', '//', $name);
879 if (substr($escapedname, 0, 1) == '/') {
880 $escapedname = ' ' . $escapedname;
882 if (substr($escapedname, -1) == '/') {
883 $escapedname = $escapedname . ' ';
885 $escapednames[] = $escapedname;
887 return implode('/', $escapednames);
891 * Convert a string, as returned by {@link assemble_category_path()},
892 * back into an array of category names.
894 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
895 * which matches the cleaning in question/category_form.php.
897 * @param string $path
898 * @return array of category names.
900 protected function split_category_path($path) {
901 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
902 $names = array();
903 foreach ($rawnames as $rawname) {
904 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
906 return $names;
910 * Do an post-processing that may be required
911 * @return bool success
913 protected function exportpostprocess() {
914 return true;
918 * convert a single question object into text output in the given
919 * format.
920 * This must be overriden
921 * @param object question question object
922 * @return mixed question export text or null if not implemented
924 protected function writequestion($question) {
925 // if not overidden, then this is an error.
926 $formatnotimplemented = get_string('formatnotimplemented', 'question');
927 echo "<p>$formatnotimplemented</p>";
928 return null;
932 * Convert the question text to plain text, so it can safely be displayed
933 * during import to let the user see roughly what is going on.
935 protected function format_question_text($question) {
936 return question_utils::to_plain_text($question->questiontext,
937 $question->questiontextformat);
941 class qformat_based_on_xml extends qformat_default {
944 * A lot of imported files contain unwanted entities.
945 * This method tries to clean up all known problems.
946 * @param string str string to correct
947 * @return string the corrected string
949 public function cleaninput($str) {
951 $html_code_list = array(
952 "&#039;" => "'",
953 "&#8217;" => "'",
954 "&#8220;" => "\"",
955 "&#8221;" => "\"",
956 "&#8211;" => "-",
957 "&#8212;" => "-",
959 $str = strtr($str, $html_code_list);
960 // Use core_text entities_to_utf8 function to convert only numerical entities.
961 $str = core_text::entities_to_utf8($str, false);
962 return $str;
966 * Return the array moodle is expecting
967 * for an HTML text. No processing is done on $text.
968 * qformat classes that want to process $text
969 * for instance to import external images files
970 * and recode urls in $text must overwrite this method.
971 * @param array $text some HTML text string
972 * @return array with keys text, format and files.
974 public function text_field($text) {
975 return array(
976 'text' => trim($text),
977 'format' => FORMAT_HTML,
978 'files' => array(),
983 * Return the value of a node, given a path to the node
984 * if it doesn't exist return the default value.
985 * @param array xml data to read
986 * @param array path path to node expressed as array
987 * @param mixed default
988 * @param bool istext process as text
989 * @param string error if set value must exist, return false and issue message if not
990 * @return mixed value
992 public function getpath($xml, $path, $default, $istext=false, $error='') {
993 foreach ($path as $index) {
994 if (!isset($xml[$index])) {
995 if (!empty($error)) {
996 $this->error($error);
997 return false;
998 } else {
999 return $default;
1003 $xml = $xml[$index];
1006 if ($istext) {
1007 if (!is_string($xml)) {
1008 $this->error(get_string('invalidxml', 'qformat_xml'));
1010 $xml = trim($xml);
1013 return $xml;