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;
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
);
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;
183 * @param string matchgrades error or nearest for grades
185 public function setMatchgrades($matchgrades) {
186 $this->matchgrades
= $matchgrades;
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;
207 * @param bool cattofile exports categories within export file
209 public function setCattofile($cattofile) {
210 $this->cattofile
= $cattofile;
215 * @param bool cattofile exports categories within export file
217 public function setContexttofile($contexttofile) {
218 $this->contexttofile
= $contexttofile;
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>";
251 echo "<blockquote>$text</blockquote>\n";
253 echo "<strong>$message</strong>\n";
256 $this->importerrors++
;
260 * Import for questiontype plugins
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,
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);
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)) {
299 * Perform any required pre-processing
300 * @return bool success
302 public function importpreprocess() {
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
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'));
326 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
327 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
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'));
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)
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,
355 if ($newfraction === false) {
356 $answersvalid = false;
358 $fractions[$key] = $newfraction;
361 if (!$answersvalid) {
362 echo $OUTPUT->notification(get_string('invalidgrade', 'question'));
366 $question->fraction
= $fractions;
369 $goodquestions[] = $question;
371 $questions = $goodquestions;
373 // check for errors before we continue
374 if ($this->stoponerror
&& $gradeerrors > 0) {
378 // count number of questions processed
381 foreach ($questions as $question) { // Process and store each question
383 // reset the php timeout
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;
398 $question->context
= $this->importcontext
;
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();
412 $question->id
= $DB->insert_record('question', $question);
413 if (isset($question->questiontextfiles
)) {
414 foreach ($question->questiontextfiles
as $file) {
415 question_bank
::get_qtype($question->qtype
)->import_file(
416 $this->importcontext
, 'question', 'questiontext', $question->id
, $file);
419 if (isset($question->generalfeedbackfiles
)) {
420 foreach ($question->generalfeedbackfiles
as $file) {
421 question_bank
::get_qtype($question->qtype
)->import_file(
422 $this->importcontext
, 'question', 'generalfeedback', $question->id
, $file);
426 $this->questionids
[] = $question->id
;
428 // Now to save all the answers and type-specific options
430 $result = question_bank
::get_qtype($question->qtype
)->save_question_options($question);
432 if (!empty($CFG->usetags
) && isset($question->tags
)) {
433 require_once($CFG->dirroot
. '/tag/lib.php');
434 tag_set('question', $question->id
, $question->tags
);
437 if (!empty($result->error
)) {
438 echo $OUTPUT->notification($result->error
);
442 if (!empty($result->notice
)) {
443 echo $OUTPUT->notification($result->notice
);
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
));
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) {
463 if (!is_array($questions)) {
466 foreach ($questions as $question) {
467 if (!is_object($question) ||
!isset($question->qtype
) ||
468 ($question->qtype
== 'category')) {
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) {
489 $catnames = $this->split_category_path($catpath);
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);
502 if ($this->contextfromfile
&& $contextid !== false) {
503 $context = get_context_instance_by_id($contextid);
504 require_capability('moodle/question:add', $context);
506 $context = get_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
;
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);
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 /// Check for Macintosh OS line returns (ie file on one line), and fix
543 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
544 return explode("\r", $filearray[0]);
553 * Parses an array of lines into an array of questions,
554 * where each item is a question object as defined by
555 * readquestion(). Questions are defined as anything
556 * between blank lines.
558 * NOTE this method used to take $context as a second argument. However, at
559 * the point where this method was called, it was impossible to know what
560 * context the quetsions were going to be saved into, so the value could be
561 * wrong. Also, none of the standard question formats were using this argument,
562 * so it was removed. See MDL-32220.
564 * If your format does not use blank lines as a delimiter
565 * then you will need to override this method. Even then
566 * try to use readquestion for each question
567 * @param array lines array of lines from readdata
568 * @return array array of question objects
570 protected function readquestions($lines) {
572 $questions = array();
573 $currentquestion = array();
575 foreach ($lines as $line) {
578 if (!empty($currentquestion)) {
579 if ($question = $this->readquestion($currentquestion)) {
580 $questions[] = $question;
582 $currentquestion = array();
585 $currentquestion[] = $line;
589 if (!empty($currentquestion)) { // There may be a final question
590 if ($question = $this->readquestion($currentquestion)) {
591 $questions[] = $question;
599 * return an "empty" question
600 * Somewhere to specify question parameters that are not handled
601 * by import but are required db fields.
602 * This should not be overridden.
603 * @return object default question
605 protected function defaultquestion() {
607 static $defaultshuffleanswers = null;
608 if (is_null($defaultshuffleanswers)) {
609 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
612 $question = new stdClass();
613 $question->shuffleanswers
= $defaultshuffleanswers;
614 $question->defaultmark
= 1;
615 $question->image
= "";
616 $question->usecase
= 0;
617 $question->multiplier
= array();
618 $question->questiontextformat
= FORMAT_MOODLE
;
619 $question->generalfeedback
= '';
620 $question->generalfeedbackformat
= FORMAT_MOODLE
;
621 $question->correctfeedback
= '';
622 $question->partiallycorrectfeedback
= '';
623 $question->incorrectfeedback
= '';
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;
637 * Given the data known to define a question in
638 * this format, this function converts it into a question
639 * object suitable for processing and insertion into Moodle.
641 * If your format does not use blank lines to delimit questions
642 * (e.g. an XML format) you must override 'readquestions' too
643 * @param $lines mixed data that represents question
644 * @return object question object
646 protected function readquestion($lines) {
648 $formatnotimplemented = get_string('formatnotimplemented', 'question');
649 echo "<p>$formatnotimplemented</p>";
655 * Override if any post-processing is required
656 * @return bool success
658 public function importpostprocess() {
667 * Provide export functionality for plugin questiontypes
669 * @param name questiontype name
670 * @param question object data to export
671 * @param extra mixed any addition format specific data needed
672 * @return string the data to append to export or false if error (or unhandled)
674 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
675 // work out the name of format in use
676 $formatname = substr(get_class($this), strlen('qformat_'));
677 $methodname = "export_to_$formatname";
679 $qtype = question_bank
::get_qtype($name, false);
680 if (method_exists($qtype, $methodname)) {
681 return $qtype->$methodname($question, $this, $extra);
687 * Do any pre-processing that may be required
688 * @param bool success
690 public function exportpreprocess() {
695 * Enable any processing to be done on the content
696 * just prior to the file being saved
697 * default is to do nothing
698 * @param string output text
699 * @param string processed output text
701 protected function presave_process($content) {
707 * For most types this should not need to be overrided
708 * @return stored_file
710 public function exportprocess() {
711 global $CFG, $OUTPUT, $DB, $USER;
713 // get the questions (from database) in this category
714 // only get q's with no parents (no cloze subquestions specifically)
715 if ($this->category
) {
716 $questions = get_questions_category($this->category
, true);
718 $questions = $this->questions
;
723 // results are first written into string (and then to a file)
724 // so create/initialize the string here
727 // track which category questions are in
728 // if it changes we will record the category change in the output
729 // file if selected. 0 means that it will get printed before the 1st question
732 // iterate through questions
733 foreach ($questions as $question) {
735 $contextid = $DB->get_field('question_categories', 'contextid',
736 array('id' => $question->category
));
737 $question->contextid
= $contextid;
739 // do not export hidden questions
740 if (!empty($question->hidden
)) {
744 // do not export random questions
745 if ($question->qtype
== 'random') {
749 // check if we need to record category change
750 if ($this->cattofile
) {
751 if ($question->category
!= $trackcategory) {
752 $trackcategory = $question->category
;
753 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile
);
755 // create 'dummy' question for category export
756 $dummyquestion = new stdClass();
757 $dummyquestion->qtype
= 'category';
758 $dummyquestion->category
= $categoryname;
759 $dummyquestion->name
= 'Switch category to ' . $categoryname;
760 $dummyquestion->id
= 0;
761 $dummyquestion->questiontextformat
= '';
762 $dummyquestion->contextid
= 0;
763 $expout .= $this->writequestion($dummyquestion) . "\n";
767 // export the question displaying message
770 if (question_has_capability_on($question, 'view', $question->category
)) {
771 $expout .= $this->writequestion($question, $contextid) . "\n";
775 // continue path for following error checks
776 $course = $this->course
;
777 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
779 // did we actually process anything
781 print_error('noquestions', 'question', $continuepath);
784 // final pre-process on exported data
785 $expout = $this->presave_process($expout);
790 * get the category as a path (e.g., tom/dick/harry)
791 * @param int id the id of the most nested catgory
792 * @return string the path
794 protected function get_category_path($id, $includecontext = true) {
797 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
798 print_error('cannotfindcategory', 'error', '', $id);
800 $contextstring = $this->translator
->context_to_string($category->contextid
);
802 $pathsections = array();
804 $pathsections[] = $category->name
;
805 $id = $category->parent
;
806 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
808 if ($includecontext) {
809 $pathsections[] = '$' . $contextstring . '$';
812 $path = $this->assemble_category_path(array_reverse($pathsections));
818 * Convert a list of category names, possibly preceeded by one of the
819 * context tokens like $course$, into a string representation of the
822 * Names are separated by / delimiters. And /s in the name are replaced by //.
824 * To reverse the process and split the paths into names, use
825 * {@link split_category_path()}.
827 * @param array $names
830 protected function assemble_category_path($names) {
831 $escapednames = array();
832 foreach ($names as $name) {
833 $escapedname = str_replace('/', '//', $name);
834 if (substr($escapedname, 0, 1) == '/') {
835 $escapedname = ' ' . $escapedname;
837 if (substr($escapedname, -1) == '/') {
838 $escapedname = $escapedname . ' ';
840 $escapednames[] = $escapedname;
842 return implode('/', $escapednames);
846 * Convert a string, as returned by {@link assemble_category_path()},
847 * back into an array of category names.
849 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
850 * which matches the cleaning in question/category_form.php.
852 * @param string $path
853 * @return array of category names.
855 protected function split_category_path($path) {
856 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
858 foreach ($rawnames as $rawname) {
859 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG
);
865 * Do an post-processing that may be required
866 * @return bool success
868 protected function exportpostprocess() {
873 * convert a single question object into text output in the given
875 * This must be overriden
876 * @param object question question object
877 * @return mixed question export text or null if not implemented
879 protected function writequestion($question) {
880 // if not overidden, then this is an error.
881 $formatnotimplemented = get_string('formatnotimplemented', 'question');
882 echo "<p>$formatnotimplemented</p>";
887 * Convert the question text to plain text, so it can safely be displayed
888 * during import to let the user see roughly what is going on.
890 protected function format_question_text($question) {
892 $formatoptions = new stdClass();
893 $formatoptions->noclean
= true;
894 return html_to_text(format_text($question->questiontext
,
895 $question->questiontextformat
, $formatoptions), 0, false);