weekly release 2.2.8+
[moodle.git] / question / format.php
blob811e9bc58f3fbe6577ea50f7f00984685f0f8782
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 * The core question types.
33 * These used to be in lib/questionlib.php, but are being deprecated. Copying
34 * them here to keep the import/export code working for now (there are 135
35 * references to these constants which I don't want to try to fix at the moment.)
37 if (!defined('SHORTANSWER')) {
38 define("SHORTANSWER", "shortanswer");
39 define("TRUEFALSE", "truefalse");
40 define("MULTICHOICE", "multichoice");
41 define("RANDOM", "random");
42 define("MATCH", "match");
43 define("RANDOMSAMATCH", "randomsamatch");
44 define("DESCRIPTION", "description");
45 define("NUMERICAL", "numerical");
46 define("MULTIANSWER", "multianswer");
47 define("CALCULATED", "calculated");
48 define("ESSAY", "essay");
50 /**#@-*/
53 /**
54 * Base class for question import and export formats.
56 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class qformat_default {
61 public $displayerrors = true;
62 public $category = null;
63 public $questions = array();
64 public $course = null;
65 public $filename = '';
66 public $realfilename = '';
67 public $matchgrades = 'error';
68 public $catfromfile = 0;
69 public $contextfromfile = 0;
70 public $cattofile = 0;
71 public $contexttofile = 0;
72 public $questionids = array();
73 public $importerrors = 0;
74 public $stoponerror = true;
75 public $translator = null;
76 public $canaccessbackupdata = true;
78 protected $importcontext = null;
80 // functions to indicate import/export functionality
81 // override to return true if implemented
83 /** @return bool whether this plugin provides import functionality. */
84 public function provide_import() {
85 return false;
88 /** @return bool whether this plugin provides export functionality. */
89 public function provide_export() {
90 return false;
93 /** The string mime-type of the files that this plugin reads or writes. */
94 public function mime_type() {
95 return mimeinfo('type', $this->export_file_extension());
98 /**
99 * @return string the file extension (including .) that is normally used for
100 * files handled by this plugin.
102 public function export_file_extension() {
103 return '.txt';
107 * Check if the given file is capable of being imported by this plugin.
109 * Note that expensive or detailed integrity checks on the file should
110 * not be performed by this method. Simple file type or magic-number tests
111 * would be suitable.
113 * @param stored_file $file the file to check
114 * @return bool whether this plugin can import the file
116 public function can_import_file($file) {
117 return ($file->get_mimetype() == $this->mime_type());
120 // Accessor methods
123 * set the category
124 * @param object category the category object
126 public function setCategory($category) {
127 if (count($this->questions)) {
128 debugging('You shouldn\'t call setCategory after setQuestions');
130 $this->category = $category;
131 $this->importcontext = get_context_instance_by_id($this->category->contextid);
135 * Set the specific questions to export. Should not include questions with
136 * parents (sub questions of cloze question type).
137 * Only used for question export.
138 * @param array of question objects
140 public function setQuestions($questions) {
141 if ($this->category !== null) {
142 debugging('You shouldn\'t call setQuestions after setCategory');
144 $this->questions = $questions;
148 * set the course class variable
149 * @param course object Moodle course variable
151 public function setCourse($course) {
152 $this->course = $course;
156 * set an array of contexts.
157 * @param array $contexts Moodle course variable
159 public function setContexts($contexts) {
160 $this->contexts = $contexts;
161 $this->translator = new context_to_string_translator($this->contexts);
165 * set the filename
166 * @param string filename name of file to import/export
168 public function setFilename($filename) {
169 $this->filename = $filename;
173 * set the "real" filename
174 * (this is what the user typed, regardless of wha happened next)
175 * @param string realfilename name of file as typed by user
177 public function setRealfilename($realfilename) {
178 $this->realfilename = $realfilename;
182 * set matchgrades
183 * @param string matchgrades error or nearest for grades
185 public function setMatchgrades($matchgrades) {
186 $this->matchgrades = $matchgrades;
190 * set catfromfile
191 * @param bool catfromfile allow categories embedded in import file
193 public function setCatfromfile($catfromfile) {
194 $this->catfromfile = $catfromfile;
198 * set contextfromfile
199 * @param bool $contextfromfile allow contexts embedded in import file
201 public function setContextfromfile($contextfromfile) {
202 $this->contextfromfile = $contextfromfile;
206 * set cattofile
207 * @param bool cattofile exports categories within export file
209 public function setCattofile($cattofile) {
210 $this->cattofile = $cattofile;
214 * set contexttofile
215 * @param bool cattofile exports categories within export file
217 public function setContexttofile($contexttofile) {
218 $this->contexttofile = $contexttofile;
222 * set stoponerror
223 * @param bool stoponerror stops database write if any errors reported
225 public function setStoponerror($stoponerror) {
226 $this->stoponerror = $stoponerror;
230 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
231 * where export files are saved.
233 public function set_can_access_backupdata($canaccess) {
234 $this->canaccessbackupdata = $canaccess;
237 /***********************
238 * IMPORTING FUNCTIONS
239 ***********************/
242 * Handle parsing error
244 protected function error($message, $text='', $questionname='') {
245 $importerrorquestion = get_string('importerrorquestion', 'question');
247 echo "<div class=\"importerror\">\n";
248 echo "<strong>$importerrorquestion $questionname</strong>";
249 if (!empty($text)) {
250 $text = s($text);
251 echo "<blockquote>$text</blockquote>\n";
253 echo "<strong>$message</strong>\n";
254 echo "</div>";
256 $this->importerrors++;
260 * Import for questiontype plugins
261 * Do not override.
262 * @param data mixed The segment of data containing the question
263 * @param question object processed (so far) by standard import code if appropriate
264 * @param extra mixed any additional format specific data that may be passed by the format
265 * @param qtypehint hint about a question type from format
266 * @return object question object suitable for save_options() or false if cannot handle
268 public function try_importing_using_qtypes($data, $question = null, $extra = null,
269 $qtypehint = '') {
271 // work out what format we are using
272 $formatname = substr(get_class($this), strlen('qformat_'));
273 $methodname = "import_from_$formatname";
275 //first try importing using a hint from format
276 if (!empty($qtypehint)) {
277 $qtype = question_bank::get_qtype($qtypehint, false);
278 if (is_object($qtype) && method_exists($qtype, $methodname)) {
279 $question = $qtype->$methodname($data, $question, $this, $extra);
280 if ($question) {
281 return $question;
286 // loop through installed questiontypes checking for
287 // function to handle this question
288 foreach (question_bank::get_all_qtypes() as $qtype) {
289 if (method_exists($qtype, $methodname)) {
290 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
291 return $question;
295 return false;
299 * Perform any required pre-processing
300 * @return bool success
302 public function importpreprocess() {
303 return true;
307 * Process the file
308 * This method should not normally be overidden
309 * @param object $category
310 * @return bool success
312 public function importprocess($category) {
313 global $USER, $CFG, $DB, $OUTPUT;
315 // reset the timer in case file upload was slow
316 set_time_limit(0);
318 // STAGE 1: Parse the file
319 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
321 if (! $lines = $this->readdata($this->filename)) {
322 echo $OUTPUT->notification(get_string('cannotread', 'question'));
323 return false;
326 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
327 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
328 return false;
331 // STAGE 2: Write data to database
332 echo $OUTPUT->notification(get_string('importingquestions', 'question',
333 $this->count_questions($questions)), 'notifysuccess');
335 // check for errors before we continue
336 if ($this->stoponerror and ($this->importerrors>0)) {
337 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
338 return true;
341 // get list of valid answer grades
342 $gradeoptionsfull = question_bank::fraction_options_full();
344 // check answer grades are valid
345 // (now need to do this here because of 'stop on error': MDL-10689)
346 $gradeerrors = 0;
347 $goodquestions = array();
348 foreach ($questions as $question) {
349 if (!empty($question->fraction) and (is_array($question->fraction))) {
350 $fractions = $question->fraction;
351 $answersvalid = true; // in case they are!
352 foreach ($fractions as $key => $fraction) {
353 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
354 $this->matchgrades);
355 if ($newfraction === false) {
356 $answersvalid = false;
357 } else {
358 $fractions[$key] = $newfraction;
361 if (!$answersvalid) {
362 echo $OUTPUT->notification(get_string('invalidgrade', 'question'));
363 ++$gradeerrors;
364 continue;
365 } else {
366 $question->fraction = $fractions;
369 $goodquestions[] = $question;
371 $questions = $goodquestions;
373 // check for errors before we continue
374 if ($this->stoponerror && $gradeerrors > 0) {
375 return false;
378 // count number of questions processed
379 $count = 0;
381 foreach ($questions as $question) { // Process and store each question
383 // reset the php timeout
384 set_time_limit(0);
386 // check for category modifiers
387 if ($question->qtype == 'category') {
388 if ($this->catfromfile) {
389 // find/create category object
390 $catpath = $question->category;
391 $newcategory = $this->create_category_path($catpath);
392 if (!empty($newcategory)) {
393 $this->category = $newcategory;
396 continue;
398 $question->context = $this->importcontext;
400 $count++;
402 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
404 $question->category = $this->category->id;
405 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
407 $question->createdby = $USER->id;
408 $question->timecreated = time();
409 $question->modifiedby = $USER->id;
410 $question->timemodified = time();
411 $fileoptions = array(
412 'subdirs' => false,
413 'maxfiles' => -1,
414 'maxbytes' => 0,
417 $question->id = $DB->insert_record('question', $question);
419 if (isset($question->questiontextitemid)) {
420 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
421 $this->importcontext->id, 'question', 'questiontext', $question->id,
422 $fileoptions, $question->questiontext);
423 } else if (isset($question->questiontextfiles)) {
424 foreach ($question->questiontextfiles as $file) {
425 question_bank::get_qtype($question->qtype)->import_file(
426 $this->importcontext, 'question', 'questiontext', $question->id, $file);
429 if (isset($question->generalfeedbackitemid)) {
430 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
431 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
432 $fileoptions, $question->generalfeedback);
433 } else if (isset($question->generalfeedbackfiles)) {
434 foreach ($question->generalfeedbackfiles as $file) {
435 question_bank::get_qtype($question->qtype)->import_file(
436 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
439 $DB->update_record('question', $question);
441 $this->questionids[] = $question->id;
443 // Now to save all the answers and type-specific options
445 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
447 if (!empty($CFG->usetags) && isset($question->tags)) {
448 require_once($CFG->dirroot . '/tag/lib.php');
449 tag_set('question', $question->id, $question->tags);
452 if (!empty($result->error)) {
453 echo $OUTPUT->notification($result->error);
454 return false;
457 if (!empty($result->notice)) {
458 echo $OUTPUT->notification($result->notice);
459 return true;
462 // Give the question a unique version stamp determined by question_hash()
463 $DB->set_field('question', 'version', question_hash($question),
464 array('id' => $question->id));
466 return true;
470 * Count all non-category questions in the questions array.
472 * @param array questions An array of question objects.
473 * @return int The count.
476 protected function count_questions($questions) {
477 $count = 0;
478 if (!is_array($questions)) {
479 return $count;
481 foreach ($questions as $question) {
482 if (!is_object($question) || !isset($question->qtype) ||
483 ($question->qtype == 'category')) {
484 continue;
486 $count++;
488 return $count;
492 * find and/or create the category described by a delimited list
493 * e.g. $course$/tom/dick/harry or tom/dick/harry
495 * removes any context string no matter whether $getcontext is set
496 * but if $getcontext is set then ignore the context and use selected category context.
498 * @param string catpath delimited category path
499 * @param int courseid course to search for categories
500 * @return mixed category object or null if fails
502 protected function create_category_path($catpath) {
503 global $DB;
504 $catnames = $this->split_category_path($catpath);
505 $parent = 0;
506 $category = null;
508 // check for context id in path, it might not be there in pre 1.9 exports
509 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
510 if ($matchcount == 1) {
511 $contextid = $this->translator->string_to_context($matches[1]);
512 array_shift($catnames);
513 } else {
514 $contextid = false;
517 if ($this->contextfromfile && $contextid !== false) {
518 $context = get_context_instance_by_id($contextid);
519 require_capability('moodle/question:add', $context);
520 } else {
521 $context = get_context_instance_by_id($this->category->contextid);
523 $this->importcontext = $context;
525 // Now create any categories that need to be created.
526 foreach ($catnames as $catname) {
527 if ($category = $DB->get_record('question_categories',
528 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
529 $parent = $category->id;
530 } else {
531 require_capability('moodle/question:managecategory', $context);
532 // create the new category
533 $category = new stdClass();
534 $category->contextid = $context->id;
535 $category->name = $catname;
536 $category->info = '';
537 $category->parent = $parent;
538 $category->sortorder = 999;
539 $category->stamp = make_unique_id_code();
540 $id = $DB->insert_record('question_categories', $category);
541 $category->id = $id;
542 $parent = $id;
545 return $category;
549 * Return complete file within an array, one item per line
550 * @param string filename name of file
551 * @return mixed contents array or false on failure
553 protected function readdata($filename) {
554 if (is_readable($filename)) {
555 $filearray = file($filename);
557 // If the first line of the file starts with a UTF-8 BOM, remove it.
558 $filearray[0] = textlib::trim_utf8_bom($filearray[0]);
560 // Check for Macintosh OS line returns (ie file on one line), and fix.
561 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
562 return explode("\r", $filearray[0]);
563 } else {
564 return $filearray;
567 return false;
571 * Parses an array of lines into an array of questions,
572 * where each item is a question object as defined by
573 * readquestion(). Questions are defined as anything
574 * between blank lines.
576 * NOTE this method used to take $context as a second argument. However, at
577 * the point where this method was called, it was impossible to know what
578 * context the quetsions were going to be saved into, so the value could be
579 * wrong. Also, none of the standard question formats were using this argument,
580 * so it was removed. See MDL-32220.
582 * If your format does not use blank lines as a delimiter
583 * then you will need to override this method. Even then
584 * try to use readquestion for each question
585 * @param array lines array of lines from readdata
586 * @return array array of question objects
588 protected function readquestions($lines) {
590 $questions = array();
591 $currentquestion = array();
593 foreach ($lines as $line) {
594 $line = trim($line);
595 if (empty($line)) {
596 if (!empty($currentquestion)) {
597 if ($question = $this->readquestion($currentquestion)) {
598 $questions[] = $question;
600 $currentquestion = array();
602 } else {
603 $currentquestion[] = $line;
607 if (!empty($currentquestion)) { // There may be a final question
608 if ($question = $this->readquestion($currentquestion)) {
609 $questions[] = $question;
613 return $questions;
617 * return an "empty" question
618 * Somewhere to specify question parameters that are not handled
619 * by import but are required db fields.
620 * This should not be overridden.
621 * @return object default question
623 protected function defaultquestion() {
624 global $CFG;
625 static $defaultshuffleanswers = null;
626 if (is_null($defaultshuffleanswers)) {
627 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
630 $question = new stdClass();
631 $question->shuffleanswers = $defaultshuffleanswers;
632 $question->defaultmark = 1;
633 $question->image = "";
634 $question->usecase = 0;
635 $question->multiplier = array();
636 $question->questiontextformat = FORMAT_MOODLE;
637 $question->generalfeedback = '';
638 $question->generalfeedbackformat = FORMAT_MOODLE;
639 $question->correctfeedback = '';
640 $question->partiallycorrectfeedback = '';
641 $question->incorrectfeedback = '';
642 $question->answernumbering = 'abc';
643 $question->penalty = 0.3333333;
644 $question->length = 1;
646 // this option in case the questiontypes class wants
647 // to know where the data came from
648 $question->export_process = true;
649 $question->import_process = true;
651 return $question;
655 * Construct a reasonable default question name, based on the start of the question text.
656 * @param string $questiontext the question text.
657 * @param string $default default question name to use if the constructed one comes out blank.
658 * @return string a reasonable question name.
660 public function create_default_question_name($questiontext, $default) {
661 $name = $this->clean_question_name(shorten_text($questiontext, 80));
662 if ($name) {
663 return $name;
664 } else {
665 return $default;
670 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
671 * @param string $name the raw question name.
672 * @return string a safe question name.
674 public function clean_question_name($name) {
675 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
676 $name = trim($name);
677 $trimlength = 251;
678 while (textlib::strlen($name) > 255 && $trimlength > 0) {
679 $name = shorten_text($name, $trimlength);
680 $trimlength -= 10;
682 return $name;
686 * Add a blank combined feedback to a question object.
687 * @param object question
688 * @return object question
690 protected function add_blank_combined_feedback($question) {
691 $question->correctfeedback['text'] = '';
692 $question->correctfeedback['format'] = $question->questiontextformat;
693 $question->correctfeedback['files'] = array();
694 $question->partiallycorrectfeedback['text'] = '';
695 $question->partiallycorrectfeedback['format'] = $question->questiontextformat;
696 $question->partiallycorrectfeedback['files'] = array();
697 $question->incorrectfeedback['text'] = '';
698 $question->incorrectfeedback['format'] = $question->questiontextformat;
699 $question->incorrectfeedback['files'] = array();
700 return $question;
704 * Given the data known to define a question in
705 * this format, this function converts it into a question
706 * object suitable for processing and insertion into Moodle.
708 * If your format does not use blank lines to delimit questions
709 * (e.g. an XML format) you must override 'readquestions' too
710 * @param $lines mixed data that represents question
711 * @return object question object
713 protected function readquestion($lines) {
715 $formatnotimplemented = get_string('formatnotimplemented', 'question');
716 echo "<p>$formatnotimplemented</p>";
718 return null;
722 * Override if any post-processing is required
723 * @return bool success
725 public function importpostprocess() {
726 return true;
729 /*******************
730 * EXPORT FUNCTIONS
731 *******************/
734 * Provide export functionality for plugin questiontypes
735 * Do not override
736 * @param name questiontype name
737 * @param question object data to export
738 * @param extra mixed any addition format specific data needed
739 * @return string the data to append to export or false if error (or unhandled)
741 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
742 // work out the name of format in use
743 $formatname = substr(get_class($this), strlen('qformat_'));
744 $methodname = "export_to_$formatname";
746 $qtype = question_bank::get_qtype($name, false);
747 if (method_exists($qtype, $methodname)) {
748 return $qtype->$methodname($question, $this, $extra);
750 return false;
754 * Do any pre-processing that may be required
755 * @param bool success
757 public function exportpreprocess() {
758 return true;
762 * Enable any processing to be done on the content
763 * just prior to the file being saved
764 * default is to do nothing
765 * @param string output text
766 * @param string processed output text
768 protected function presave_process($content) {
769 return $content;
773 * Do the export
774 * For most types this should not need to be overrided
775 * @return stored_file
777 public function exportprocess() {
778 global $CFG, $OUTPUT, $DB, $USER;
780 // get the questions (from database) in this category
781 // only get q's with no parents (no cloze subquestions specifically)
782 if ($this->category) {
783 $questions = get_questions_category($this->category, true);
784 } else {
785 $questions = $this->questions;
788 $count = 0;
790 // results are first written into string (and then to a file)
791 // so create/initialize the string here
792 $expout = "";
794 // track which category questions are in
795 // if it changes we will record the category change in the output
796 // file if selected. 0 means that it will get printed before the 1st question
797 $trackcategory = 0;
799 // iterate through questions
800 foreach ($questions as $question) {
801 // used by file api
802 $contextid = $DB->get_field('question_categories', 'contextid',
803 array('id' => $question->category));
804 $question->contextid = $contextid;
806 // do not export hidden questions
807 if (!empty($question->hidden)) {
808 continue;
811 // do not export random questions
812 if ($question->qtype == 'random') {
813 continue;
816 // check if we need to record category change
817 if ($this->cattofile) {
818 if ($question->category != $trackcategory) {
819 $trackcategory = $question->category;
820 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
822 // create 'dummy' question for category export
823 $dummyquestion = new stdClass();
824 $dummyquestion->qtype = 'category';
825 $dummyquestion->category = $categoryname;
826 $dummyquestion->name = 'Switch category to ' . $categoryname;
827 $dummyquestion->id = 0;
828 $dummyquestion->questiontextformat = '';
829 $dummyquestion->contextid = 0;
830 $expout .= $this->writequestion($dummyquestion) . "\n";
834 // export the question displaying message
835 $count++;
837 if (question_has_capability_on($question, 'view', $question->category)) {
838 $expout .= $this->writequestion($question, $contextid) . "\n";
842 // continue path for following error checks
843 $course = $this->course;
844 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
846 // did we actually process anything
847 if ($count==0) {
848 print_error('noquestions', 'question', $continuepath);
851 // final pre-process on exported data
852 $expout = $this->presave_process($expout);
853 return $expout;
857 * get the category as a path (e.g., tom/dick/harry)
858 * @param int id the id of the most nested catgory
859 * @return string the path
861 protected function get_category_path($id, $includecontext = true) {
862 global $DB;
864 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
865 print_error('cannotfindcategory', 'error', '', $id);
867 $contextstring = $this->translator->context_to_string($category->contextid);
869 $pathsections = array();
870 do {
871 $pathsections[] = $category->name;
872 $id = $category->parent;
873 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
875 if ($includecontext) {
876 $pathsections[] = '$' . $contextstring . '$';
879 $path = $this->assemble_category_path(array_reverse($pathsections));
881 return $path;
885 * Convert a list of category names, possibly preceeded by one of the
886 * context tokens like $course$, into a string representation of the
887 * category path.
889 * Names are separated by / delimiters. And /s in the name are replaced by //.
891 * To reverse the process and split the paths into names, use
892 * {@link split_category_path()}.
894 * @param array $names
895 * @return string
897 protected function assemble_category_path($names) {
898 $escapednames = array();
899 foreach ($names as $name) {
900 $escapedname = str_replace('/', '//', $name);
901 if (substr($escapedname, 0, 1) == '/') {
902 $escapedname = ' ' . $escapedname;
904 if (substr($escapedname, -1) == '/') {
905 $escapedname = $escapedname . ' ';
907 $escapednames[] = $escapedname;
909 return implode('/', $escapednames);
913 * Convert a string, as returned by {@link assemble_category_path()},
914 * back into an array of category names.
916 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
917 * which matches the cleaning in question/category_form.php.
919 * @param string $path
920 * @return array of category names.
922 protected function split_category_path($path) {
923 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
924 $names = array();
925 foreach ($rawnames as $rawname) {
926 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
928 return $names;
932 * Do an post-processing that may be required
933 * @return bool success
935 protected function exportpostprocess() {
936 return true;
940 * convert a single question object into text output in the given
941 * format.
942 * This must be overriden
943 * @param object question question object
944 * @return mixed question export text or null if not implemented
946 protected function writequestion($question) {
947 // if not overidden, then this is an error.
948 $formatnotimplemented = get_string('formatnotimplemented', 'question');
949 echo "<p>$formatnotimplemented</p>";
950 return null;
954 * Convert the question text to plain text, so it can safely be displayed
955 * during import to let the user see roughly what is going on.
957 protected function format_question_text($question) {
958 global $DB;
959 $formatoptions = new stdClass();
960 $formatoptions->noclean = true;
961 return html_to_text(format_text($question->questiontext,
962 $question->questiontextformat, $formatoptions), 0, false);
966 class qformat_based_on_xml extends qformat_default {
969 * A lot of imported files contain unwanted entities.
970 * This method tries to clean up all known problems.
971 * @param string str string to correct
972 * @return string the corrected string
974 public function cleaninput($str) {
976 $html_code_list = array(
977 "&#039;" => "'",
978 "&#8217;" => "'",
979 "&#8220;" => "\"",
980 "&#8221;" => "\"",
981 "&#8211;" => "-",
982 "&#8212;" => "-",
984 $str = strtr($str, $html_code_list);
985 // Use textlib entities_to_utf8 function to convert only numerical entities.
986 $str = textlib::entities_to_utf8($str, false);
987 return $str;
991 * Return the array moodle is expecting
992 * for an HTML text. No processing is done on $text.
993 * qformat classes that want to process $text
994 * for instance to import external images files
995 * and recode urls in $text must overwrite this method.
996 * @param array $text some HTML text string
997 * @return array with keys text, format and files.
999 public function text_field($text) {
1000 return array(
1001 'text' => trim($text),
1002 'format' => FORMAT_HTML,
1003 'files' => array(),
1008 * Return the value of a node, given a path to the node
1009 * if it doesn't exist return the default value.
1010 * @param array xml data to read
1011 * @param array path path to node expressed as array
1012 * @param mixed default
1013 * @param bool istext process as text
1014 * @param string error if set value must exist, return false and issue message if not
1015 * @return mixed value
1017 public function getpath($xml, $path, $default, $istext=false, $error='') {
1018 foreach ($path as $index) {
1019 if (!isset($xml[$index])) {
1020 if (!empty($error)) {
1021 $this->error($error);
1022 return false;
1023 } else {
1024 return $default;
1028 $xml = $xml[$index];
1031 if ($istext) {
1032 if (!is_string($xml)) {
1033 $this->error(get_string('invalidxml', 'qformat_xml'));
1035 $xml = trim($xml);
1038 return $xml;