2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Defines the base class for question import and export formats.
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();
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");
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() {
88 /** @return bool whether this plugin provides export functionality. */
89 public function provide_export() {
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());
99 * @return string the file extension (including .) that is normally used for
100 * files handled by this plugin.
102 public function export_file_extension() {
110 * @param object category the category object
112 public function setCategory($category) {
113 if (count($this->questions)) {
114 debugging('You shouldn\'t call setCategory after setQuestions');
116 $this->category = $category;
120 * Set the specific questions to export. Should not include questions with
121 * parents (sub questions of cloze question type).
122 * Only used for question export.
123 * @param array of question objects
125 public function setQuestions($questions) {
126 if ($this->category !== null) {
127 debugging('You shouldn\'t call setQuestions after setCategory');
129 $this->questions = $questions;
133 * set the course class variable
134 * @param course object Moodle course variable
136 public function setCourse($course) {
137 $this->course = $course;
141 * set an array of contexts.
142 * @param array $contexts Moodle course variable
144 public function setContexts($contexts) {
145 $this->contexts = $contexts;
146 $this->translator = new context_to_string_translator($this->contexts);
151 * @param string filename name of file to import/export
153 public function setFilename($filename) {
154 $this->filename = $filename;
158 * set the "real" filename
159 * (this is what the user typed, regardless of wha happened next)
160 * @param string realfilename name of file as typed by user
162 public function setRealfilename($realfilename) {
163 $this->realfilename = $realfilename;
168 * @param string matchgrades error or nearest for grades
170 public function setMatchgrades($matchgrades) {
171 $this->matchgrades = $matchgrades;
176 * @param bool catfromfile allow categories embedded in import file
178 public function setCatfromfile($catfromfile) {
179 $this->catfromfile = $catfromfile;
183 * set contextfromfile
184 * @param bool $contextfromfile allow contexts embedded in import file
186 public function setContextfromfile($contextfromfile) {
187 $this->contextfromfile = $contextfromfile;
192 * @param bool cattofile exports categories within export file
194 public function setCattofile($cattofile) {
195 $this->cattofile = $cattofile;
200 * @param bool cattofile exports categories within export file
202 public function setContexttofile($contexttofile) {
203 $this->contexttofile = $contexttofile;
208 * @param bool stoponerror stops database write if any errors reported
210 public function setStoponerror($stoponerror) {
211 $this->stoponerror = $stoponerror;
215 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
216 * where export files are saved.
218 public function set_can_access_backupdata($canaccess) {
219 $this->canaccessbackupdata = $canaccess;
222 /***********************
223 * IMPORTING FUNCTIONS
224 ***********************/
227 * Handle parsing error
229 protected function error($message, $text='', $questionname='') {
230 $importerrorquestion = get_string('importerrorquestion', 'question');
232 echo "<div class=\"importerror\">\n";
233 echo "<strong>$importerrorquestion $questionname</strong>";
236 echo "<blockquote>$text</blockquote>\n";
238 echo "<strong>$message</strong>\n";
241 $this->importerrors++;
245 * Import for questiontype plugins
247 * @param data mixed The segment of data containing the question
248 * @param question object processed (so far) by standard import code if appropriate
249 * @param extra mixed any additional format specific data that may be passed by the format
250 * @param qtypehint hint about a question type from format
251 * @return object question object suitable for save_options() or false if cannot handle
253 public function try_importing_using_qtypes($data, $question = null, $extra = null,
256 // work out what format we are using
257 $formatname = substr(get_class($this), strlen('qformat_'));
258 $methodname = "import_from_$formatname";
260 //first try importing using a hint from format
261 if (!empty($qtypehint)) {
262 $qtype = question_bank::get_qtype($qtypehint, false);
263 if (is_object($qtype) && method_exists($qtype, $methodname)) {
264 $question = $qtype->$methodname($data, $question, $this, $extra);
271 // loop through installed questiontypes checking for
272 // function to handle this question
273 foreach (question_bank::get_all_qtypes() as $qtype) {
274 if (method_exists($qtype, $methodname)) {
275 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
284 * Perform any required pre-processing
285 * @return bool success
287 public function importpreprocess() {
293 * This method should not normally be overidden
294 * @param object $category
295 * @return bool success
297 public function importprocess($category) {
298 global $USER, $CFG, $DB, $OUTPUT;
300 $context = $category->context;
301 $this->importcontext = $context;
303 // reset the timer in case file upload was slow
306 // STAGE 1: Parse the file
307 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
309 if (! $lines = $this->readdata($this->filename)) {
310 echo $OUTPUT->notification(get_string('cannotread', 'question'));
314 if (!$questions = $this->readquestions($lines, $context)) { // Extract all the questions
315 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
319 // STAGE 2: Write data to database
320 echo $OUTPUT->notification(get_string('importingquestions', 'question',
321 $this->count_questions($questions)), 'notifysuccess');
323 // check for errors before we continue
324 if ($this->stoponerror and ($this->importerrors>0)) {
325 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
329 // get list of valid answer grades
330 $gradeoptionsfull = question_bank::fraction_options_full();
332 // check answer grades are valid
333 // (now need to do this here because of 'stop on error': MDL-10689)
335 $goodquestions = array();
336 foreach ($questions as $question) {
337 if (!empty($question->fraction) and (is_array($question->fraction))) {
338 $fractions = $question->fraction;
339 $answersvalid = true; // in case they are!
340 foreach ($fractions as $key => $fraction) {
341 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
343 if ($newfraction === false) {
344 $answersvalid = false;
346 $fractions[$key] = $newfraction;
349 if (!$answersvalid) {
350 echo $OUTPUT->notification(get_string('invalidgrade', 'question'));
354 $question->fraction = $fractions;
357 $goodquestions[] = $question;
359 $questions = $goodquestions;
361 // check for errors before we continue
362 if ($this->stoponerror && $gradeerrors > 0) {
366 // count number of questions processed
369 foreach ($questions as $question) { // Process and store each question
371 // reset the php timeout
374 // check for category modifiers
375 if ($question->qtype == 'category') {
376 if ($this->catfromfile) {
377 // find/create category object
378 $catpath = $question->category;
379 $newcategory = $this->create_category_path($catpath);
380 if (!empty($newcategory)) {
381 $this->category = $newcategory;
386 $question->context = $context;
390 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
392 $question->category = $this->category->id;
393 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
395 $question->createdby = $USER->id;
396 $question->timecreated = time();
398 $question->id = $DB->insert_record('question', $question);
399 if (isset($question->questiontextfiles)) {
400 foreach ($question->questiontextfiles as $file) {
401 question_bank::get_qtype($question->qtype)->import_file(
402 $context, 'question', 'questiontext', $question->id, $file);
405 if (isset($question->generalfeedbackfiles)) {
406 foreach ($question->generalfeedbackfiles as $file) {
407 question_bank::get_qtype($question->qtype)->import_file(
408 $context, 'question', 'generalfeedback', $question->id, $file);
412 $this->questionids[] = $question->id;
414 // Now to save all the answers and type-specific options
416 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
418 if (!empty($CFG->usetags) && isset($question->tags)) {
419 require_once($CFG->dirroot . '/tag/lib.php');
420 tag_set('question', $question->id, $question->tags);
423 if (!empty($result->error)) {
424 echo $OUTPUT->notification($result->error);
428 if (!empty($result->notice)) {
429 echo $OUTPUT->notification($result->notice);
433 // Give the question a unique version stamp determined by question_hash()
434 $DB->set_field('question', 'version', question_hash($question),
435 array('id' => $question->id));
441 * Count all non-category questions in the questions array.
443 * @param array questions An array of question objects.
444 * @return int The count.
447 protected function count_questions($questions) {
449 if (!is_array($questions)) {
452 foreach ($questions as $question) {
453 if (!is_object($question) || !isset($question->qtype) ||
454 ($question->qtype == 'category')) {
463 * find and/or create the category described by a delimited list
464 * e.g. $course$/tom/dick/harry or tom/dick/harry
466 * removes any context string no matter whether $getcontext is set
467 * but if $getcontext is set then ignore the context and use selected category context.
469 * @param string catpath delimited category path
470 * @param int courseid course to search for categories
471 * @return mixed category object or null if fails
473 protected function create_category_path($catpath) {
475 $catnames = $this->split_category_path($catpath);
479 // check for context id in path, it might not be there in pre 1.9 exports
480 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
481 if ($matchcount == 1) {
482 $contextid = $this->translator->string_to_context($matches[1]);
483 array_shift($catnames);
488 if ($this->contextfromfile && $contextid !== false) {
489 $context = get_context_instance_by_id($contextid);
490 require_capability('moodle/question:add', $context);
492 $context = get_context_instance_by_id($this->category->contextid);
495 // Now create any categories that need to be created.
496 foreach ($catnames as $catname) {
497 if ($category = $DB->get_record('question_categories',
498 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
499 $parent = $category->id;
501 require_capability('moodle/question:managecategory', $context);
502 // create the new category
503 $category = new stdClass();
504 $category->contextid = $context->id;
505 $category->name = $catname;
506 $category->info = '';
507 $category->parent = $parent;
508 $category->sortorder = 999;
509 $category->stamp = make_unique_id_code();
510 $id = $DB->insert_record('question_categories', $category);
519 * Return complete file within an array, one item per line
520 * @param string filename name of file
521 * @return mixed contents array or false on failure
523 protected function readdata($filename) {
524 if (is_readable($filename)) {
525 $filearray = file($filename);
527 /// Check for Macintosh OS line returns (ie file on one line), and fix
528 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
529 return explode("\r", $filearray[0]);
538 * Parses an array of lines into an array of questions,
539 * where each item is a question object as defined by
540 * readquestion(). Questions are defined as anything
541 * between blank lines.
543 * If your format does not use blank lines as a delimiter
544 * then you will need to override this method. Even then
545 * try to use readquestion for each question
546 * @param array lines array of lines from readdata
547 * @param object $context
548 * @return array array of question objects
550 protected function readquestions($lines, $context) {
552 $questions = array();
553 $currentquestion = array();
555 foreach ($lines as $line) {
558 if (!empty($currentquestion)) {
559 if ($question = $this->readquestion($currentquestion)) {
560 $questions[] = $question;
562 $currentquestion = array();
565 $currentquestion[] = $line;
569 if (!empty($currentquestion)) { // There may be a final question
570 if ($question = $this->readquestion($currentquestion, $context)) {
571 $questions[] = $question;
579 * return an "empty" question
580 * Somewhere to specify question parameters that are not handled
581 * by import but are required db fields.
582 * This should not be overridden.
583 * @return object default question
585 protected function defaultquestion() {
587 static $defaultshuffleanswers = null;
588 if (is_null($defaultshuffleanswers)) {
589 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
592 $question = new stdClass();
593 $question->shuffleanswers = $defaultshuffleanswers;
594 $question->defaultmark = 1;
595 $question->image = "";
596 $question->usecase = 0;
597 $question->multiplier = array();
598 $question->generalfeedback = '';
599 $question->correctfeedback = '';
600 $question->partiallycorrectfeedback = '';
601 $question->incorrectfeedback = '';
602 $question->answernumbering = 'abc';
603 $question->penalty = 0.3333333;
604 $question->length = 1;
606 // this option in case the questiontypes class wants
607 // to know where the data came from
608 $question->export_process = true;
609 $question->import_process = true;
615 * Given the data known to define a question in
616 * this format, this function converts it into a question
617 * object suitable for processing and insertion into Moodle.
619 * If your format does not use blank lines to delimit questions
620 * (e.g. an XML format) you must override 'readquestions' too
621 * @param $lines mixed data that represents question
622 * @return object question object
624 protected function readquestion($lines) {
626 $formatnotimplemented = get_string('formatnotimplemented', 'question');
627 echo "<p>$formatnotimplemented</p>";
633 * Override if any post-processing is required
634 * @return bool success
636 public function importpostprocess() {
645 * Provide export functionality for plugin questiontypes
647 * @param name questiontype name
648 * @param question object data to export
649 * @param extra mixed any addition format specific data needed
650 * @return string the data to append to export or false if error (or unhandled)
652 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
653 // work out the name of format in use
654 $formatname = substr(get_class($this), strlen('qformat_'));
655 $methodname = "export_to_$formatname";
657 $qtype = question_bank::get_qtype($name, false);
658 if (method_exists($qtype, $methodname)) {
659 return $qtype->$methodname($question, $this, $extra);
665 * Do any pre-processing that may be required
666 * @param bool success
668 public function exportpreprocess() {
673 * Enable any processing to be done on the content
674 * just prior to the file being saved
675 * default is to do nothing
676 * @param string output text
677 * @param string processed output text
679 protected function presave_process($content) {
685 * For most types this should not need to be overrided
686 * @return stored_file
688 public function exportprocess() {
689 global $CFG, $OUTPUT, $DB, $USER;
691 // get the questions (from database) in this category
692 // only get q's with no parents (no cloze subquestions specifically)
693 if ($this->category) {
694 $questions = get_questions_category($this->category, true);
696 $questions = $this->questions;
701 // results are first written into string (and then to a file)
702 // so create/initialize the string here
705 // track which category questions are in
706 // if it changes we will record the category change in the output
707 // file if selected. 0 means that it will get printed before the 1st question
710 // iterate through questions
711 foreach ($questions as $question) {
713 $contextid = $DB->get_field('question_categories', 'contextid',
714 array('id' => $question->category));
715 $question->contextid = $contextid;
717 // do not export hidden questions
718 if (!empty($question->hidden)) {
722 // do not export random questions
723 if ($question->qtype == 'random') {
727 // check if we need to record category change
728 if ($this->cattofile) {
729 if ($question->category != $trackcategory) {
730 $trackcategory = $question->category;
731 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
733 // create 'dummy' question for category export
734 $dummyquestion = new stdClass();
735 $dummyquestion->qtype = 'category';
736 $dummyquestion->category = $categoryname;
737 $dummyquestion->name = 'Switch category to ' . $categoryname;
738 $dummyquestion->id = 0;
739 $dummyquestion->questiontextformat = '';
740 $dummyquestion->contextid = 0;
741 $expout .= $this->writequestion($dummyquestion) . "\n";
745 // export the question displaying message
748 if (question_has_capability_on($question, 'view', $question->category)) {
749 $expout .= $this->writequestion($question, $contextid) . "\n";
753 // continue path for following error checks
754 $course = $this->course;
755 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
757 // did we actually process anything
759 print_error('noquestions', 'question', $continuepath);
762 // final pre-process on exported data
763 $expout = $this->presave_process($expout);
768 * get the category as a path (e.g., tom/dick/harry)
769 * @param int id the id of the most nested catgory
770 * @return string the path
772 protected function get_category_path($id, $includecontext = true) {
775 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
776 print_error('cannotfindcategory', 'error', '', $id);
778 $contextstring = $this->translator->context_to_string($category->contextid);
780 $pathsections = array();
782 $pathsections[] = $category->name;
783 $id = $category->parent;
784 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
786 if ($includecontext) {
787 $pathsections[] = '$' . $contextstring . '$';
790 $path = $this->assemble_category_path(array_reverse($pathsections));
796 * Convert a list of category names, possibly preceeded by one of the
797 * context tokens like $course$, into a string representation of the
800 * Names are separated by / delimiters. And /s in the name are replaced by //.
802 * To reverse the process and split the paths into names, use
803 * {@link split_category_path()}.
805 * @param array $names
808 protected function assemble_category_path($names) {
809 $escapednames = array();
810 foreach ($names as $name) {
811 $escapedname = str_replace('/', '//', $name);
812 if (substr($escapedname, 0, 1) == '/') {
813 $escapedname = ' ' . $escapedname;
815 if (substr($escapedname, -1) == '/') {
816 $escapedname = $escapedname . ' ';
818 $escapednames[] = $escapedname;
820 return implode('/', $escapednames);
824 * Convert a string, as returned by {@link assemble_category_path()},
825 * back into an array of category names.
827 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
828 * which matches the cleaning in question/category_form.php.
830 * @param string $path
831 * @return array of category names.
833 protected function split_category_path($path) {
834 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
836 foreach ($rawnames as $rawname) {
837 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
843 * Do an post-processing that may be required
844 * @return bool success
846 protected function exportpostprocess() {
851 * convert a single question object into text output in the given
853 * This must be overriden
854 * @param object question question object
855 * @return mixed question export text or null if not implemented
857 protected function writequestion($question) {
858 // if not overidden, then this is an error.
859 $formatnotimplemented = get_string('formatnotimplemented', 'question');
860 echo "<p>$formatnotimplemented</p>";
865 * Convert the question text to plain text, so it can safely be displayed
866 * during import to let the user see roughly what is going on.
868 protected function format_question_text($question) {
870 $formatoptions = new stdClass();
871 $formatoptions->noclean = true;
872 return html_to_text(format_text($question->questiontext,
873 $question->questiontextformat, $formatoptions), 0, false);
877 * convert files into text output in the given format.
879 * @param string encoding method
880 * @return string $string
882 protected function writefiles($files, $encoding='base64') {
887 foreach ($files as $file) {
888 if ($file->is_directory()) {
891 $string .= '<file name="' . $file->get_filename() . '" encoding="' . $encoding . '">';
892 $string .= base64_encode($file->get_content());
893 $string .= '</file>';