MDL-57916 mod_data: New WS mod_data_get_access_information
[moodle.git] / question / format.php
blob20b92fec95a7c3d7d8438ed77897283e293bca78
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 // Raise time and memory, as importing can be quite intensive.
293 core_php_time_limit::raise();
294 raise_memory_limit(MEMORY_EXTRA);
296 // STAGE 1: Parse the file
297 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
299 if (! $lines = $this->readdata($this->filename)) {
300 echo $OUTPUT->notification(get_string('cannotread', 'question'));
301 return false;
304 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
305 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
306 return false;
309 // STAGE 2: Write data to database
310 echo $OUTPUT->notification(get_string('importingquestions', 'question',
311 $this->count_questions($questions)), 'notifysuccess');
313 // check for errors before we continue
314 if ($this->stoponerror and ($this->importerrors>0)) {
315 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
316 return true;
319 // get list of valid answer grades
320 $gradeoptionsfull = question_bank::fraction_options_full();
322 // check answer grades are valid
323 // (now need to do this here because of 'stop on error': MDL-10689)
324 $gradeerrors = 0;
325 $goodquestions = array();
326 foreach ($questions as $question) {
327 if (!empty($question->fraction) and (is_array($question->fraction))) {
328 $fractions = $question->fraction;
329 $invalidfractions = array();
330 foreach ($fractions as $key => $fraction) {
331 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
332 $this->matchgrades);
333 if ($newfraction === false) {
334 $invalidfractions[] = $fraction;
335 } else {
336 $fractions[$key] = $newfraction;
339 if ($invalidfractions) {
340 echo $OUTPUT->notification(get_string('invalidgrade', 'question',
341 implode(', ', $invalidfractions)));
342 ++$gradeerrors;
343 continue;
344 } else {
345 $question->fraction = $fractions;
348 $goodquestions[] = $question;
350 $questions = $goodquestions;
352 // check for errors before we continue
353 if ($this->stoponerror && $gradeerrors > 0) {
354 return false;
357 // count number of questions processed
358 $count = 0;
360 foreach ($questions as $question) { // Process and store each question
361 $transaction = $DB->start_delegated_transaction();
363 // reset the php timeout
364 core_php_time_limit::raise();
366 // check for category modifiers
367 if ($question->qtype == 'category') {
368 if ($this->catfromfile) {
369 // find/create category object
370 $catpath = $question->category;
371 $newcategory = $this->create_category_path($catpath);
372 if (!empty($newcategory)) {
373 $this->category = $newcategory;
376 $transaction->allow_commit();
377 continue;
379 $question->context = $this->importcontext;
381 $count++;
383 echo "<hr /><p><b>{$count}</b>. ".$this->format_question_text($question)."</p>";
385 $question->category = $this->category->id;
386 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
388 $question->createdby = $USER->id;
389 $question->timecreated = time();
390 $question->modifiedby = $USER->id;
391 $question->timemodified = time();
392 $fileoptions = array(
393 'subdirs' => true,
394 'maxfiles' => -1,
395 'maxbytes' => 0,
398 $question->id = $DB->insert_record('question', $question);
400 if (isset($question->questiontextitemid)) {
401 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
402 $this->importcontext->id, 'question', 'questiontext', $question->id,
403 $fileoptions, $question->questiontext);
404 } else if (isset($question->questiontextfiles)) {
405 foreach ($question->questiontextfiles as $file) {
406 question_bank::get_qtype($question->qtype)->import_file(
407 $this->importcontext, 'question', 'questiontext', $question->id, $file);
410 if (isset($question->generalfeedbackitemid)) {
411 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
412 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
413 $fileoptions, $question->generalfeedback);
414 } else if (isset($question->generalfeedbackfiles)) {
415 foreach ($question->generalfeedbackfiles as $file) {
416 question_bank::get_qtype($question->qtype)->import_file(
417 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
420 $DB->update_record('question', $question);
422 $this->questionids[] = $question->id;
424 // Now to save all the answers and type-specific options
426 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
428 if (isset($question->tags)) {
429 core_tag_tag::set_item_tags('core_question', 'question', $question->id, $question->context, $question->tags);
432 if (!empty($result->error)) {
433 echo $OUTPUT->notification($result->error);
434 // Can't use $transaction->rollback(); since it requires an exception,
435 // and I don't want to rewrite this code to change the error handling now.
436 $DB->force_transaction_rollback();
437 return false;
440 $transaction->allow_commit();
442 if (!empty($result->notice)) {
443 echo $OUTPUT->notification($result->notice);
444 return true;
447 // Give the question a unique version stamp determined by question_hash()
448 $DB->set_field('question', 'version', question_hash($question),
449 array('id' => $question->id));
451 return true;
455 * Count all non-category questions in the questions array.
457 * @param array questions An array of question objects.
458 * @return int The count.
461 protected function count_questions($questions) {
462 $count = 0;
463 if (!is_array($questions)) {
464 return $count;
466 foreach ($questions as $question) {
467 if (!is_object($question) || !isset($question->qtype) ||
468 ($question->qtype == 'category')) {
469 continue;
471 $count++;
473 return $count;
477 * find and/or create the category described by a delimited list
478 * e.g. $course$/tom/dick/harry or tom/dick/harry
480 * removes any context string no matter whether $getcontext is set
481 * but if $getcontext is set then ignore the context and use selected category context.
483 * @param string catpath delimited category path
484 * @param int courseid course to search for categories
485 * @return mixed category object or null if fails
487 protected function create_category_path($catpath) {
488 global $DB;
489 $catnames = $this->split_category_path($catpath);
490 $parent = 0;
491 $category = null;
493 // check for context id in path, it might not be there in pre 1.9 exports
494 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
495 if ($matchcount == 1) {
496 $contextid = $this->translator->string_to_context($matches[1]);
497 array_shift($catnames);
498 } else {
499 $contextid = false;
502 if ($this->contextfromfile && $contextid !== false) {
503 $context = context::instance_by_id($contextid);
504 require_capability('moodle/question:add', $context);
505 } else {
506 $context = context::instance_by_id($this->category->contextid);
508 $this->importcontext = $context;
510 // Now create any categories that need to be created.
511 foreach ($catnames as $catname) {
512 if ($category = $DB->get_record('question_categories',
513 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
514 $parent = $category->id;
515 } else {
516 require_capability('moodle/question:managecategory', $context);
517 // create the new category
518 $category = new stdClass();
519 $category->contextid = $context->id;
520 $category->name = $catname;
521 $category->info = '';
522 $category->parent = $parent;
523 $category->sortorder = 999;
524 $category->stamp = make_unique_id_code();
525 $id = $DB->insert_record('question_categories', $category);
526 $category->id = $id;
527 $parent = $id;
530 return $category;
534 * Return complete file within an array, one item per line
535 * @param string filename name of file
536 * @return mixed contents array or false on failure
538 protected function readdata($filename) {
539 if (is_readable($filename)) {
540 $filearray = file($filename);
542 // If the first line of the file starts with a UTF-8 BOM, remove it.
543 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
545 // Check for Macintosh OS line returns (ie file on one line), and fix.
546 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
547 return explode("\r", $filearray[0]);
548 } else {
549 return $filearray;
552 return false;
556 * Parses an array of lines into an array of questions,
557 * where each item is a question object as defined by
558 * readquestion(). Questions are defined as anything
559 * between blank lines.
561 * NOTE this method used to take $context as a second argument. However, at
562 * the point where this method was called, it was impossible to know what
563 * context the quetsions were going to be saved into, so the value could be
564 * wrong. Also, none of the standard question formats were using this argument,
565 * so it was removed. See MDL-32220.
567 * If your format does not use blank lines as a delimiter
568 * then you will need to override this method. Even then
569 * try to use readquestion for each question
570 * @param array lines array of lines from readdata
571 * @return array array of question objects
573 protected function readquestions($lines) {
575 $questions = array();
576 $currentquestion = array();
578 foreach ($lines as $line) {
579 $line = trim($line);
580 if (empty($line)) {
581 if (!empty($currentquestion)) {
582 if ($question = $this->readquestion($currentquestion)) {
583 $questions[] = $question;
585 $currentquestion = array();
587 } else {
588 $currentquestion[] = $line;
592 if (!empty($currentquestion)) { // There may be a final question
593 if ($question = $this->readquestion($currentquestion)) {
594 $questions[] = $question;
598 return $questions;
602 * return an "empty" question
603 * Somewhere to specify question parameters that are not handled
604 * by import but are required db fields.
605 * This should not be overridden.
606 * @return object default question
608 protected function defaultquestion() {
609 global $CFG;
610 static $defaultshuffleanswers = null;
611 if (is_null($defaultshuffleanswers)) {
612 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
615 $question = new stdClass();
616 $question->shuffleanswers = $defaultshuffleanswers;
617 $question->defaultmark = 1;
618 $question->image = "";
619 $question->usecase = 0;
620 $question->multiplier = array();
621 $question->questiontextformat = FORMAT_MOODLE;
622 $question->generalfeedback = '';
623 $question->generalfeedbackformat = FORMAT_MOODLE;
624 $question->answernumbering = 'abc';
625 $question->penalty = 0.3333333;
626 $question->length = 1;
628 // this option in case the questiontypes class wants
629 // to know where the data came from
630 $question->export_process = true;
631 $question->import_process = true;
633 $this->add_blank_combined_feedback($question);
635 return $question;
639 * Construct a reasonable default question name, based on the start of the question text.
640 * @param string $questiontext the question text.
641 * @param string $default default question name to use if the constructed one comes out blank.
642 * @return string a reasonable question name.
644 public function create_default_question_name($questiontext, $default) {
645 $name = $this->clean_question_name(shorten_text($questiontext, 80));
646 if ($name) {
647 return $name;
648 } else {
649 return $default;
654 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
655 * @param string $name the raw question name.
656 * @return string a safe question name.
658 public function clean_question_name($name) {
659 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
660 $name = trim($name);
661 $trimlength = 251;
662 while (core_text::strlen($name) > 255 && $trimlength > 0) {
663 $name = shorten_text($name, $trimlength);
664 $trimlength -= 10;
666 return $name;
670 * Add a blank combined feedback to a question object.
671 * @param object question
672 * @return object question
674 protected function add_blank_combined_feedback($question) {
675 $question->correctfeedback = [
676 'text' => '',
677 'format' => $question->questiontextformat,
678 'files' => []
680 $question->partiallycorrectfeedback = [
681 'text' => '',
682 'format' => $question->questiontextformat,
683 'files' => []
685 $question->incorrectfeedback = [
686 'text' => '',
687 'format' => $question->questiontextformat,
688 'files' => []
690 return $question;
694 * Given the data known to define a question in
695 * this format, this function converts it into a question
696 * object suitable for processing and insertion into Moodle.
698 * If your format does not use blank lines to delimit questions
699 * (e.g. an XML format) you must override 'readquestions' too
700 * @param $lines mixed data that represents question
701 * @return object question object
703 protected function readquestion($lines) {
704 // We should never get there unless the qformat plugin is broken.
705 throw new coding_exception('Question format plugin is missing important code: readquestion.');
707 return null;
711 * Override if any post-processing is required
712 * @return bool success
714 public function importpostprocess() {
715 return true;
718 /*******************
719 * EXPORT FUNCTIONS
720 *******************/
723 * Provide export functionality for plugin questiontypes
724 * Do not override
725 * @param name questiontype name
726 * @param question object data to export
727 * @param extra mixed any addition format specific data needed
728 * @return string the data to append to export or false if error (or unhandled)
730 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
731 // work out the name of format in use
732 $formatname = substr(get_class($this), strlen('qformat_'));
733 $methodname = "export_to_{$formatname}";
735 $qtype = question_bank::get_qtype($name, false);
736 if (method_exists($qtype, $methodname)) {
737 return $qtype->$methodname($question, $this, $extra);
739 return false;
743 * Do any pre-processing that may be required
744 * @param bool success
746 public function exportpreprocess() {
747 return true;
751 * Enable any processing to be done on the content
752 * just prior to the file being saved
753 * default is to do nothing
754 * @param string output text
755 * @param string processed output text
757 protected function presave_process($content) {
758 return $content;
762 * Do the export
763 * For most types this should not need to be overrided
764 * @return stored_file
766 public function exportprocess() {
767 global $CFG, $OUTPUT, $DB, $USER;
769 // get the questions (from database) in this category
770 // only get q's with no parents (no cloze subquestions specifically)
771 if ($this->category) {
772 $questions = get_questions_category($this->category, true);
773 } else {
774 $questions = $this->questions;
777 $count = 0;
779 // results are first written into string (and then to a file)
780 // so create/initialize the string here
781 $expout = "";
783 // track which category questions are in
784 // if it changes we will record the category change in the output
785 // file if selected. 0 means that it will get printed before the 1st question
786 $trackcategory = 0;
788 // iterate through questions
789 foreach ($questions as $question) {
790 // used by file api
791 $contextid = $DB->get_field('question_categories', 'contextid',
792 array('id' => $question->category));
793 $question->contextid = $contextid;
795 // do not export hidden questions
796 if (!empty($question->hidden)) {
797 continue;
800 // do not export random questions
801 if ($question->qtype == 'random') {
802 continue;
805 // check if we need to record category change
806 if ($this->cattofile) {
807 if ($question->category != $trackcategory) {
808 $trackcategory = $question->category;
809 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
811 // create 'dummy' question for category export
812 $dummyquestion = new stdClass();
813 $dummyquestion->qtype = 'category';
814 $dummyquestion->category = $categoryname;
815 $dummyquestion->name = 'Switch category to ' . $categoryname;
816 $dummyquestion->id = 0;
817 $dummyquestion->questiontextformat = '';
818 $dummyquestion->contextid = 0;
819 $expout .= $this->writequestion($dummyquestion) . "\n";
823 // export the question displaying message
824 $count++;
826 if (question_has_capability_on($question, 'view', $question->category)) {
827 $expout .= $this->writequestion($question, $contextid) . "\n";
831 // continue path for following error checks
832 $course = $this->course;
833 $continuepath = "{$CFG->wwwroot}/question/export.php?courseid={$course->id}";
835 // did we actually process anything
836 if ($count==0) {
837 print_error('noquestions', 'question', $continuepath);
840 // final pre-process on exported data
841 $expout = $this->presave_process($expout);
842 return $expout;
846 * get the category as a path (e.g., tom/dick/harry)
847 * @param int id the id of the most nested catgory
848 * @return string the path
850 protected function get_category_path($id, $includecontext = true) {
851 global $DB;
853 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
854 print_error('cannotfindcategory', 'error', '', $id);
856 $contextstring = $this->translator->context_to_string($category->contextid);
858 $pathsections = array();
859 do {
860 $pathsections[] = $category->name;
861 $id = $category->parent;
862 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
864 if ($includecontext) {
865 $pathsections[] = '$' . $contextstring . '$';
868 $path = $this->assemble_category_path(array_reverse($pathsections));
870 return $path;
874 * Convert a list of category names, possibly preceeded by one of the
875 * context tokens like $course$, into a string representation of the
876 * category path.
878 * Names are separated by / delimiters. And /s in the name are replaced by //.
880 * To reverse the process and split the paths into names, use
881 * {@link split_category_path()}.
883 * @param array $names
884 * @return string
886 protected function assemble_category_path($names) {
887 $escapednames = array();
888 foreach ($names as $name) {
889 $escapedname = str_replace('/', '//', $name);
890 if (substr($escapedname, 0, 1) == '/') {
891 $escapedname = ' ' . $escapedname;
893 if (substr($escapedname, -1) == '/') {
894 $escapedname = $escapedname . ' ';
896 $escapednames[] = $escapedname;
898 return implode('/', $escapednames);
902 * Convert a string, as returned by {@link assemble_category_path()},
903 * back into an array of category names.
905 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
906 * which matches the cleaning in question/category_form.php.
908 * @param string $path
909 * @return array of category names.
911 protected function split_category_path($path) {
912 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
913 $names = array();
914 foreach ($rawnames as $rawname) {
915 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
917 return $names;
921 * Do an post-processing that may be required
922 * @return bool success
924 protected function exportpostprocess() {
925 return true;
929 * convert a single question object into text output in the given
930 * format.
931 * This must be overriden
932 * @param object question question object
933 * @return mixed question export text or null if not implemented
935 protected function writequestion($question) {
936 // if not overidden, then this is an error.
937 throw new coding_exception('Question format plugin is missing important code: writequestion.');
938 return null;
942 * Convert the question text to plain text, so it can safely be displayed
943 * during import to let the user see roughly what is going on.
945 protected function format_question_text($question) {
946 return question_utils::to_plain_text($question->questiontext,
947 $question->questiontextformat);
951 class qformat_based_on_xml extends qformat_default {
954 * A lot of imported files contain unwanted entities.
955 * This method tries to clean up all known problems.
956 * @param string str string to correct
957 * @return string the corrected string
959 public function cleaninput($str) {
961 $html_code_list = array(
962 "&#039;" => "'",
963 "&#8217;" => "'",
964 "&#8220;" => "\"",
965 "&#8221;" => "\"",
966 "&#8211;" => "-",
967 "&#8212;" => "-",
969 $str = strtr($str, $html_code_list);
970 // Use core_text entities_to_utf8 function to convert only numerical entities.
971 $str = core_text::entities_to_utf8($str, false);
972 return $str;
976 * Return the array moodle is expecting
977 * for an HTML text. No processing is done on $text.
978 * qformat classes that want to process $text
979 * for instance to import external images files
980 * and recode urls in $text must overwrite this method.
981 * @param array $text some HTML text string
982 * @return array with keys text, format and files.
984 public function text_field($text) {
985 return array(
986 'text' => trim($text),
987 'format' => FORMAT_HTML,
988 'files' => array(),
993 * Return the value of a node, given a path to the node
994 * if it doesn't exist return the default value.
995 * @param array xml data to read
996 * @param array path path to node expressed as array
997 * @param mixed default
998 * @param bool istext process as text
999 * @param string error if set value must exist, return false and issue message if not
1000 * @return mixed value
1002 public function getpath($xml, $path, $default, $istext=false, $error='') {
1003 foreach ($path as $index) {
1004 if (!isset($xml[$index])) {
1005 if (!empty($error)) {
1006 $this->error($error);
1007 return false;
1008 } else {
1009 return $default;
1013 $xml = $xml[$index];
1016 if ($istext) {
1017 if (!is_string($xml)) {
1018 $this->error(get_string('invalidxml', 'qformat_xml'));
1020 $xml = trim($xml);
1023 return $xml;