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() {
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
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());
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;
134 * Set the specific questions to export. Should not include questions with
135 * parents (sub questions of cloze question type).
136 * Only used for question export.
137 * @param array of question objects
139 public function setQuestions($questions) {
140 if ($this->category !== null) {
141 debugging('You shouldn\'t call setQuestions after setCategory');
143 $this->questions = $questions;
147 * set the course class variable
148 * @param course object Moodle course variable
150 public function setCourse($course) {
151 $this->course = $course;
155 * set an array of contexts.
156 * @param array $contexts Moodle course variable
158 public function setContexts($contexts) {
159 $this->contexts = $contexts;
160 $this->translator = new context_to_string_translator($this->contexts);
165 * @param string filename name of file to import/export
167 public function setFilename($filename) {
168 $this->filename = $filename;
172 * set the "real" filename
173 * (this is what the user typed, regardless of wha happened next)
174 * @param string realfilename name of file as typed by user
176 public function setRealfilename($realfilename) {
177 $this->realfilename = $realfilename;
182 * @param string matchgrades error or nearest for grades
184 public function setMatchgrades($matchgrades) {
185 $this->matchgrades = $matchgrades;
190 * @param bool catfromfile allow categories embedded in import file
192 public function setCatfromfile($catfromfile) {
193 $this->catfromfile = $catfromfile;
197 * set contextfromfile
198 * @param bool $contextfromfile allow contexts embedded in import file
200 public function setContextfromfile($contextfromfile) {
201 $this->contextfromfile = $contextfromfile;
206 * @param bool cattofile exports categories within export file
208 public function setCattofile($cattofile) {
209 $this->cattofile = $cattofile;
214 * @param bool cattofile exports categories within export file
216 public function setContexttofile($contexttofile) {
217 $this->contexttofile = $contexttofile;
222 * @param bool stoponerror stops database write if any errors reported
224 public function setStoponerror($stoponerror) {
225 $this->stoponerror = $stoponerror;
229 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
230 * where export files are saved.
232 public function set_can_access_backupdata($canaccess) {
233 $this->canaccessbackupdata = $canaccess;
236 /***********************
237 * IMPORTING FUNCTIONS
238 ***********************/
241 * Handle parsing error
243 protected function error($message, $text='', $questionname='') {
244 $importerrorquestion = get_string('importerrorquestion', 'question');
246 echo "<div class=\"importerror\">\n";
247 echo "<strong>$importerrorquestion $questionname</strong>";
250 echo "<blockquote>$text</blockquote>\n";
252 echo "<strong>$message</strong>\n";
255 $this->importerrors++;
259 * Import for questiontype plugins
261 * @param data mixed The segment of data containing the question
262 * @param question object processed (so far) by standard import code if appropriate
263 * @param extra mixed any additional format specific data that may be passed by the format
264 * @param qtypehint hint about a question type from format
265 * @return object question object suitable for save_options() or false if cannot handle
267 public function try_importing_using_qtypes($data, $question = null, $extra = null,
270 // work out what format we are using
271 $formatname = substr(get_class($this), strlen('qformat_'));
272 $methodname = "import_from_$formatname";
274 //first try importing using a hint from format
275 if (!empty($qtypehint)) {
276 $qtype = question_bank::get_qtype($qtypehint, false);
277 if (is_object($qtype) && method_exists($qtype, $methodname)) {
278 $question = $qtype->$methodname($data, $question, $this, $extra);
285 // loop through installed questiontypes checking for
286 // function to handle this question
287 foreach (question_bank::get_all_qtypes() as $qtype) {
288 if (method_exists($qtype, $methodname)) {
289 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
298 * Perform any required pre-processing
299 * @return bool success
301 public function importpreprocess() {
307 * This method should not normally be overidden
308 * @param object $category
309 * @return bool success
311 public function importprocess($category) {
312 global $USER, $CFG, $DB, $OUTPUT;
314 $context = $category->context;
315 $this->importcontext = $context;
317 // reset the timer in case file upload was slow
320 // STAGE 1: Parse the file
321 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
323 if (! $lines = $this->readdata($this->filename)) {
324 echo $OUTPUT->notification(get_string('cannotread', 'question'));
328 if (!$questions = $this->readquestions($lines, $context)) { // Extract all the questions
329 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
333 // STAGE 2: Write data to database
334 echo $OUTPUT->notification(get_string('importingquestions', 'question',
335 $this->count_questions($questions)), 'notifysuccess');
337 // check for errors before we continue
338 if ($this->stoponerror and ($this->importerrors>0)) {
339 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
343 // get list of valid answer grades
344 $gradeoptionsfull = question_bank::fraction_options_full();
346 // check answer grades are valid
347 // (now need to do this here because of 'stop on error': MDL-10689)
349 $goodquestions = array();
350 foreach ($questions as $question) {
351 if (!empty($question->fraction) and (is_array($question->fraction))) {
352 $fractions = $question->fraction;
353 $answersvalid = true; // in case they are!
354 foreach ($fractions as $key => $fraction) {
355 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
357 if ($newfraction === false) {
358 $answersvalid = false;
360 $fractions[$key] = $newfraction;
363 if (!$answersvalid) {
364 echo $OUTPUT->notification(get_string('invalidgrade', 'question'));
368 $question->fraction = $fractions;
371 $goodquestions[] = $question;
373 $questions = $goodquestions;
375 // check for errors before we continue
376 if ($this->stoponerror && $gradeerrors > 0) {
380 // count number of questions processed
383 foreach ($questions as $question) { // Process and store each question
385 // reset the php timeout
388 // check for category modifiers
389 if ($question->qtype == 'category') {
390 if ($this->catfromfile) {
391 // find/create category object
392 $catpath = $question->category;
393 $newcategory = $this->create_category_path($catpath);
394 if (!empty($newcategory)) {
395 $this->category = $newcategory;
400 $question->context = $context;
404 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
406 $question->category = $this->category->id;
407 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
409 $question->createdby = $USER->id;
410 $question->timecreated = time();
411 $question->modifiedby = $USER->id;
412 $question->timemodified = time();
414 $question->id = $DB->insert_record('question', $question);
415 if (isset($question->questiontextfiles)) {
416 foreach ($question->questiontextfiles as $file) {
417 question_bank::get_qtype($question->qtype)->import_file(
418 $context, 'question', 'questiontext', $question->id, $file);
421 if (isset($question->generalfeedbackfiles)) {
422 foreach ($question->generalfeedbackfiles as $file) {
423 question_bank::get_qtype($question->qtype)->import_file(
424 $context, 'question', 'generalfeedback', $question->id, $file);
428 $this->questionids[] = $question->id;
430 // Now to save all the answers and type-specific options
432 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
434 if (!empty($CFG->usetags) && isset($question->tags)) {
435 require_once($CFG->dirroot . '/tag/lib.php');
436 tag_set('question', $question->id, $question->tags);
439 if (!empty($result->error)) {
440 echo $OUTPUT->notification($result->error);
444 if (!empty($result->notice)) {
445 echo $OUTPUT->notification($result->notice);
449 // Give the question a unique version stamp determined by question_hash()
450 $DB->set_field('question', 'version', question_hash($question),
451 array('id' => $question->id));
457 * Count all non-category questions in the questions array.
459 * @param array questions An array of question objects.
460 * @return int The count.
463 protected function count_questions($questions) {
465 if (!is_array($questions)) {
468 foreach ($questions as $question) {
469 if (!is_object($question) || !isset($question->qtype) ||
470 ($question->qtype == 'category')) {
479 * find and/or create the category described by a delimited list
480 * e.g. $course$/tom/dick/harry or tom/dick/harry
482 * removes any context string no matter whether $getcontext is set
483 * but if $getcontext is set then ignore the context and use selected category context.
485 * @param string catpath delimited category path
486 * @param int courseid course to search for categories
487 * @return mixed category object or null if fails
489 protected function create_category_path($catpath) {
491 $catnames = $this->split_category_path($catpath);
495 // check for context id in path, it might not be there in pre 1.9 exports
496 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
497 if ($matchcount == 1) {
498 $contextid = $this->translator->string_to_context($matches[1]);
499 array_shift($catnames);
504 if ($this->contextfromfile && $contextid !== false) {
505 $context = get_context_instance_by_id($contextid);
506 require_capability('moodle/question:add', $context);
508 $context = get_context_instance_by_id($this->category->contextid);
511 // Now create any categories that need to be created.
512 foreach ($catnames as $catname) {
513 if ($category = $DB->get_record('question_categories',
514 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
515 $parent = $category->id;
517 require_capability('moodle/question:managecategory', $context);
518 // create the new category
519 $category = new stdClass();
520 $category->contextid = $context->id;
521 $category->name = $catname;
522 $category->info = '';
523 $category->parent = $parent;
524 $category->sortorder = 999;
525 $category->stamp = make_unique_id_code();
526 $id = $DB->insert_record('question_categories', $category);
535 * Return complete file within an array, one item per line
536 * @param string filename name of file
537 * @return mixed contents array or false on failure
539 protected function readdata($filename) {
540 if (is_readable($filename)) {
541 $filearray = file($filename);
543 /// Check for Macintosh OS line returns (ie file on one line), and fix
544 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
545 return explode("\r", $filearray[0]);
554 * Parses an array of lines into an array of questions,
555 * where each item is a question object as defined by
556 * readquestion(). Questions are defined as anything
557 * between blank lines.
559 * If your format does not use blank lines as a delimiter
560 * then you will need to override this method. Even then
561 * try to use readquestion for each question
562 * @param array lines array of lines from readdata
563 * @param object $context
564 * @return array array of question objects
566 protected function readquestions($lines, $context) {
568 $questions = array();
569 $currentquestion = array();
571 foreach ($lines as $line) {
574 if (!empty($currentquestion)) {
575 if ($question = $this->readquestion($currentquestion)) {
576 $questions[] = $question;
578 $currentquestion = array();
581 $currentquestion[] = $line;
585 if (!empty($currentquestion)) { // There may be a final question
586 if ($question = $this->readquestion($currentquestion, $context)) {
587 $questions[] = $question;
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() {
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;
633 * Given the data known to define a question in
634 * this format, this function converts it into a question
635 * object suitable for processing and insertion into Moodle.
637 * If your format does not use blank lines to delimit questions
638 * (e.g. an XML format) you must override 'readquestions' too
639 * @param $lines mixed data that represents question
640 * @return object question object
642 protected function readquestion($lines) {
644 $formatnotimplemented = get_string('formatnotimplemented', 'question');
645 echo "<p>$formatnotimplemented</p>";
651 * Override if any post-processing is required
652 * @return bool success
654 public function importpostprocess() {
663 * Provide export functionality for plugin questiontypes
665 * @param name questiontype name
666 * @param question object data to export
667 * @param extra mixed any addition format specific data needed
668 * @return string the data to append to export or false if error (or unhandled)
670 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
671 // work out the name of format in use
672 $formatname = substr(get_class($this), strlen('qformat_'));
673 $methodname = "export_to_$formatname";
675 $qtype = question_bank::get_qtype($name, false);
676 if (method_exists($qtype, $methodname)) {
677 return $qtype->$methodname($question, $this, $extra);
683 * Do any pre-processing that may be required
684 * @param bool success
686 public function exportpreprocess() {
691 * Enable any processing to be done on the content
692 * just prior to the file being saved
693 * default is to do nothing
694 * @param string output text
695 * @param string processed output text
697 protected function presave_process($content) {
703 * For most types this should not need to be overrided
704 * @return stored_file
706 public function exportprocess() {
707 global $CFG, $OUTPUT, $DB, $USER;
709 // get the questions (from database) in this category
710 // only get q's with no parents (no cloze subquestions specifically)
711 if ($this->category) {
712 $questions = get_questions_category($this->category, true);
714 $questions = $this->questions;
719 // results are first written into string (and then to a file)
720 // so create/initialize the string here
723 // track which category questions are in
724 // if it changes we will record the category change in the output
725 // file if selected. 0 means that it will get printed before the 1st question
728 // iterate through questions
729 foreach ($questions as $question) {
731 $contextid = $DB->get_field('question_categories', 'contextid',
732 array('id' => $question->category));
733 $question->contextid = $contextid;
735 // do not export hidden questions
736 if (!empty($question->hidden)) {
740 // do not export random questions
741 if ($question->qtype == 'random') {
745 // check if we need to record category change
746 if ($this->cattofile) {
747 if ($question->category != $trackcategory) {
748 $trackcategory = $question->category;
749 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
751 // create 'dummy' question for category export
752 $dummyquestion = new stdClass();
753 $dummyquestion->qtype = 'category';
754 $dummyquestion->category = $categoryname;
755 $dummyquestion->name = 'Switch category to ' . $categoryname;
756 $dummyquestion->id = 0;
757 $dummyquestion->questiontextformat = '';
758 $dummyquestion->contextid = 0;
759 $expout .= $this->writequestion($dummyquestion) . "\n";
763 // export the question displaying message
766 if (question_has_capability_on($question, 'view', $question->category)) {
767 $expout .= $this->writequestion($question, $contextid) . "\n";
771 // continue path for following error checks
772 $course = $this->course;
773 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
775 // did we actually process anything
777 print_error('noquestions', 'question', $continuepath);
780 // final pre-process on exported data
781 $expout = $this->presave_process($expout);
786 * get the category as a path (e.g., tom/dick/harry)
787 * @param int id the id of the most nested catgory
788 * @return string the path
790 protected function get_category_path($id, $includecontext = true) {
793 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
794 print_error('cannotfindcategory', 'error', '', $id);
796 $contextstring = $this->translator->context_to_string($category->contextid);
798 $pathsections = array();
800 $pathsections[] = $category->name;
801 $id = $category->parent;
802 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
804 if ($includecontext) {
805 $pathsections[] = '$' . $contextstring . '$';
808 $path = $this->assemble_category_path(array_reverse($pathsections));
814 * Convert a list of category names, possibly preceeded by one of the
815 * context tokens like $course$, into a string representation of the
818 * Names are separated by / delimiters. And /s in the name are replaced by //.
820 * To reverse the process and split the paths into names, use
821 * {@link split_category_path()}.
823 * @param array $names
826 protected function assemble_category_path($names) {
827 $escapednames = array();
828 foreach ($names as $name) {
829 $escapedname = str_replace('/', '//', $name);
830 if (substr($escapedname, 0, 1) == '/') {
831 $escapedname = ' ' . $escapedname;
833 if (substr($escapedname, -1) == '/') {
834 $escapedname = $escapedname . ' ';
836 $escapednames[] = $escapedname;
838 return implode('/', $escapednames);
842 * Convert a string, as returned by {@link assemble_category_path()},
843 * back into an array of category names.
845 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
846 * which matches the cleaning in question/category_form.php.
848 * @param string $path
849 * @return array of category names.
851 protected function split_category_path($path) {
852 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
854 foreach ($rawnames as $rawname) {
855 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
861 * Do an post-processing that may be required
862 * @return bool success
864 protected function exportpostprocess() {
869 * convert a single question object into text output in the given
871 * This must be overriden
872 * @param object question question object
873 * @return mixed question export text or null if not implemented
875 protected function writequestion($question) {
876 // if not overidden, then this is an error.
877 $formatnotimplemented = get_string('formatnotimplemented', 'question');
878 echo "<p>$formatnotimplemented</p>";
883 * Convert the question text to plain text, so it can safely be displayed
884 * during import to let the user see roughly what is going on.
886 protected function format_question_text($question) {
888 $formatoptions = new stdClass();
889 $formatoptions->noclean = true;
890 return html_to_text(format_text($question->questiontext,
891 $question->questiontextformat, $formatoptions), 0, false);