MDL-28975 question engine, JavaScript error in IE.
[moodle.git] / question / format.php
blobdc3db4aadce3cc193fbd2cc441feda3845bfe616
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Defines the base class for question import and export formats.
20 * @package moodlecore
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 /**#@+
31 * The core question types.
33 * These used to be in lib/questionlib.php, but are being deprecated. Copying
34 * them here to keep the import/export code working for now (there are 135
35 * references to these constants which I don't want to try to fix at the moment.)
37 if (!defined('SHORTANSWER')) {
38 define("SHORTANSWER", "shortanswer");
39 define("TRUEFALSE", "truefalse");
40 define("MULTICHOICE", "multichoice");
41 define("RANDOM", "random");
42 define("MATCH", "match");
43 define("RANDOMSAMATCH", "randomsamatch");
44 define("DESCRIPTION", "description");
45 define("NUMERICAL", "numerical");
46 define("MULTIANSWER", "multianswer");
47 define("CALCULATED", "calculated");
48 define("ESSAY", "essay");
50 /**#@-*/
53 /**
54 * Base class for question import and export formats.
56 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class qformat_default {
61 public $displayerrors = true;
62 public $category = null;
63 public $questions = array();
64 public $course = null;
65 public $filename = '';
66 public $realfilename = '';
67 public $matchgrades = 'error';
68 public $catfromfile = 0;
69 public $contextfromfile = 0;
70 public $cattofile = 0;
71 public $contexttofile = 0;
72 public $questionids = array();
73 public $importerrors = 0;
74 public $stoponerror = true;
75 public $translator = null;
76 public $canaccessbackupdata = true;
78 protected $importcontext = null;
80 // functions to indicate import/export functionality
81 // override to return true if implemented
83 /** @return bool whether this plugin provides import functionality. */
84 public function provide_import() {
85 return false;
88 /** @return bool whether this plugin provides export functionality. */
89 public function provide_export() {
90 return false;
93 /** The string mime-type of the files that this plugin reads or writes. */
94 public function mime_type() {
95 return mimeinfo('type', $this->export_file_extension());
98 /**
99 * @return string the file extension (including .) that is normally used for
100 * files handled by this plugin.
102 public function export_file_extension() {
103 return '.txt';
106 // Accessor methods
109 * set the category
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);
150 * set the filename
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;
167 * set matchgrades
168 * @param string matchgrades error or nearest for grades
170 public function setMatchgrades($matchgrades) {
171 $this->matchgrades = $matchgrades;
175 * set catfromfile
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;
191 * set cattofile
192 * @param bool cattofile exports categories within export file
194 public function setCattofile($cattofile) {
195 $this->cattofile = $cattofile;
199 * set contexttofile
200 * @param bool cattofile exports categories within export file
202 public function setContexttofile($contexttofile) {
203 $this->contexttofile = $contexttofile;
207 * set stoponerror
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>";
234 if (!empty($text)) {
235 $text = s($text);
236 echo "<blockquote>$text</blockquote>\n";
238 echo "<strong>$message</strong>\n";
239 echo "</div>";
241 $this->importerrors++;
245 * Import for questiontype plugins
246 * Do not override.
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,
254 $qtypehint = '') {
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);
265 if ($question) {
266 return $question;
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)) {
276 return $question;
280 return false;
284 * Perform any required pre-processing
285 * @return bool success
287 public function importpreprocess() {
288 return true;
292 * Process the file
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
304 set_time_limit(0);
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'));
311 return false;
314 if (!$questions = $this->readquestions($lines, $context)) { // Extract all the questions
315 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
316 return false;
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'));
326 return true;
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)
334 $gradeerrors = 0;
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,
342 $this->matchgrades);
343 if ($newfraction === false) {
344 $answersvalid = false;
345 } else {
346 $fractions[$key] = $newfraction;
349 if (!$answersvalid) {
350 echo $OUTPUT->notification(get_string('invalidgrade', 'question'));
351 ++$gradeerrors;
352 continue;
353 } else {
354 $question->fraction = $fractions;
357 $goodquestions[] = $question;
359 $questions = $goodquestions;
361 // check for errors before we continue
362 if ($this->stoponerror && $gradeerrors > 0) {
363 return false;
366 // count number of questions processed
367 $count = 0;
369 foreach ($questions as $question) { // Process and store each question
371 // reset the php timeout
372 set_time_limit(0);
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;
384 continue;
386 $question->context = $context;
388 $count++;
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();
397 $question->modifiedby = $USER->id;
398 $question->timemodified = time();
400 $question->id = $DB->insert_record('question', $question);
401 if (isset($question->questiontextfiles)) {
402 foreach ($question->questiontextfiles as $file) {
403 question_bank::get_qtype($question->qtype)->import_file(
404 $context, 'question', 'questiontext', $question->id, $file);
407 if (isset($question->generalfeedbackfiles)) {
408 foreach ($question->generalfeedbackfiles as $file) {
409 question_bank::get_qtype($question->qtype)->import_file(
410 $context, 'question', 'generalfeedback', $question->id, $file);
414 $this->questionids[] = $question->id;
416 // Now to save all the answers and type-specific options
418 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
420 if (!empty($CFG->usetags) && isset($question->tags)) {
421 require_once($CFG->dirroot . '/tag/lib.php');
422 tag_set('question', $question->id, $question->tags);
425 if (!empty($result->error)) {
426 echo $OUTPUT->notification($result->error);
427 return false;
430 if (!empty($result->notice)) {
431 echo $OUTPUT->notification($result->notice);
432 return true;
435 // Give the question a unique version stamp determined by question_hash()
436 $DB->set_field('question', 'version', question_hash($question),
437 array('id' => $question->id));
439 return true;
443 * Count all non-category questions in the questions array.
445 * @param array questions An array of question objects.
446 * @return int The count.
449 protected function count_questions($questions) {
450 $count = 0;
451 if (!is_array($questions)) {
452 return $count;
454 foreach ($questions as $question) {
455 if (!is_object($question) || !isset($question->qtype) ||
456 ($question->qtype == 'category')) {
457 continue;
459 $count++;
461 return $count;
465 * find and/or create the category described by a delimited list
466 * e.g. $course$/tom/dick/harry or tom/dick/harry
468 * removes any context string no matter whether $getcontext is set
469 * but if $getcontext is set then ignore the context and use selected category context.
471 * @param string catpath delimited category path
472 * @param int courseid course to search for categories
473 * @return mixed category object or null if fails
475 protected function create_category_path($catpath) {
476 global $DB;
477 $catnames = $this->split_category_path($catpath);
478 $parent = 0;
479 $category = null;
481 // check for context id in path, it might not be there in pre 1.9 exports
482 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
483 if ($matchcount == 1) {
484 $contextid = $this->translator->string_to_context($matches[1]);
485 array_shift($catnames);
486 } else {
487 $contextid = false;
490 if ($this->contextfromfile && $contextid !== false) {
491 $context = get_context_instance_by_id($contextid);
492 require_capability('moodle/question:add', $context);
493 } else {
494 $context = get_context_instance_by_id($this->category->contextid);
497 // Now create any categories that need to be created.
498 foreach ($catnames as $catname) {
499 if ($category = $DB->get_record('question_categories',
500 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
501 $parent = $category->id;
502 } else {
503 require_capability('moodle/question:managecategory', $context);
504 // create the new category
505 $category = new stdClass();
506 $category->contextid = $context->id;
507 $category->name = $catname;
508 $category->info = '';
509 $category->parent = $parent;
510 $category->sortorder = 999;
511 $category->stamp = make_unique_id_code();
512 $id = $DB->insert_record('question_categories', $category);
513 $category->id = $id;
514 $parent = $id;
517 return $category;
521 * Return complete file within an array, one item per line
522 * @param string filename name of file
523 * @return mixed contents array or false on failure
525 protected function readdata($filename) {
526 if (is_readable($filename)) {
527 $filearray = file($filename);
529 /// Check for Macintosh OS line returns (ie file on one line), and fix
530 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
531 return explode("\r", $filearray[0]);
532 } else {
533 return $filearray;
536 return false;
540 * Parses an array of lines into an array of questions,
541 * where each item is a question object as defined by
542 * readquestion(). Questions are defined as anything
543 * between blank lines.
545 * If your format does not use blank lines as a delimiter
546 * then you will need to override this method. Even then
547 * try to use readquestion for each question
548 * @param array lines array of lines from readdata
549 * @param object $context
550 * @return array array of question objects
552 protected function readquestions($lines, $context) {
554 $questions = array();
555 $currentquestion = array();
557 foreach ($lines as $line) {
558 $line = trim($line);
559 if (empty($line)) {
560 if (!empty($currentquestion)) {
561 if ($question = $this->readquestion($currentquestion)) {
562 $questions[] = $question;
564 $currentquestion = array();
566 } else {
567 $currentquestion[] = $line;
571 if (!empty($currentquestion)) { // There may be a final question
572 if ($question = $this->readquestion($currentquestion, $context)) {
573 $questions[] = $question;
577 return $questions;
581 * return an "empty" question
582 * Somewhere to specify question parameters that are not handled
583 * by import but are required db fields.
584 * This should not be overridden.
585 * @return object default question
587 protected function defaultquestion() {
588 global $CFG;
589 static $defaultshuffleanswers = null;
590 if (is_null($defaultshuffleanswers)) {
591 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
594 $question = new stdClass();
595 $question->shuffleanswers = $defaultshuffleanswers;
596 $question->defaultmark = 1;
597 $question->image = "";
598 $question->usecase = 0;
599 $question->multiplier = array();
600 $question->questiontextformat = FORMAT_MOODLE;
601 $question->generalfeedback = '';
602 $question->generalfeedbackformat = FORMAT_MOODLE;
603 $question->correctfeedback = '';
604 $question->partiallycorrectfeedback = '';
605 $question->incorrectfeedback = '';
606 $question->answernumbering = 'abc';
607 $question->penalty = 0.3333333;
608 $question->length = 1;
610 // this option in case the questiontypes class wants
611 // to know where the data came from
612 $question->export_process = true;
613 $question->import_process = true;
615 return $question;
619 * Given the data known to define a question in
620 * this format, this function converts it into a question
621 * object suitable for processing and insertion into Moodle.
623 * If your format does not use blank lines to delimit questions
624 * (e.g. an XML format) you must override 'readquestions' too
625 * @param $lines mixed data that represents question
626 * @return object question object
628 protected function readquestion($lines) {
630 $formatnotimplemented = get_string('formatnotimplemented', 'question');
631 echo "<p>$formatnotimplemented</p>";
633 return null;
637 * Override if any post-processing is required
638 * @return bool success
640 public function importpostprocess() {
641 return true;
644 /*******************
645 * EXPORT FUNCTIONS
646 *******************/
649 * Provide export functionality for plugin questiontypes
650 * Do not override
651 * @param name questiontype name
652 * @param question object data to export
653 * @param extra mixed any addition format specific data needed
654 * @return string the data to append to export or false if error (or unhandled)
656 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
657 // work out the name of format in use
658 $formatname = substr(get_class($this), strlen('qformat_'));
659 $methodname = "export_to_$formatname";
661 $qtype = question_bank::get_qtype($name, false);
662 if (method_exists($qtype, $methodname)) {
663 return $qtype->$methodname($question, $this, $extra);
665 return false;
669 * Do any pre-processing that may be required
670 * @param bool success
672 public function exportpreprocess() {
673 return true;
677 * Enable any processing to be done on the content
678 * just prior to the file being saved
679 * default is to do nothing
680 * @param string output text
681 * @param string processed output text
683 protected function presave_process($content) {
684 return $content;
688 * Do the export
689 * For most types this should not need to be overrided
690 * @return stored_file
692 public function exportprocess() {
693 global $CFG, $OUTPUT, $DB, $USER;
695 // get the questions (from database) in this category
696 // only get q's with no parents (no cloze subquestions specifically)
697 if ($this->category) {
698 $questions = get_questions_category($this->category, true);
699 } else {
700 $questions = $this->questions;
703 $count = 0;
705 // results are first written into string (and then to a file)
706 // so create/initialize the string here
707 $expout = "";
709 // track which category questions are in
710 // if it changes we will record the category change in the output
711 // file if selected. 0 means that it will get printed before the 1st question
712 $trackcategory = 0;
714 // iterate through questions
715 foreach ($questions as $question) {
716 // used by file api
717 $contextid = $DB->get_field('question_categories', 'contextid',
718 array('id' => $question->category));
719 $question->contextid = $contextid;
721 // do not export hidden questions
722 if (!empty($question->hidden)) {
723 continue;
726 // do not export random questions
727 if ($question->qtype == 'random') {
728 continue;
731 // check if we need to record category change
732 if ($this->cattofile) {
733 if ($question->category != $trackcategory) {
734 $trackcategory = $question->category;
735 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
737 // create 'dummy' question for category export
738 $dummyquestion = new stdClass();
739 $dummyquestion->qtype = 'category';
740 $dummyquestion->category = $categoryname;
741 $dummyquestion->name = 'Switch category to ' . $categoryname;
742 $dummyquestion->id = 0;
743 $dummyquestion->questiontextformat = '';
744 $dummyquestion->contextid = 0;
745 $expout .= $this->writequestion($dummyquestion) . "\n";
749 // export the question displaying message
750 $count++;
752 if (question_has_capability_on($question, 'view', $question->category)) {
753 $expout .= $this->writequestion($question, $contextid) . "\n";
757 // continue path for following error checks
758 $course = $this->course;
759 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
761 // did we actually process anything
762 if ($count==0) {
763 print_error('noquestions', 'question', $continuepath);
766 // final pre-process on exported data
767 $expout = $this->presave_process($expout);
768 return $expout;
772 * get the category as a path (e.g., tom/dick/harry)
773 * @param int id the id of the most nested catgory
774 * @return string the path
776 protected function get_category_path($id, $includecontext = true) {
777 global $DB;
779 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
780 print_error('cannotfindcategory', 'error', '', $id);
782 $contextstring = $this->translator->context_to_string($category->contextid);
784 $pathsections = array();
785 do {
786 $pathsections[] = $category->name;
787 $id = $category->parent;
788 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
790 if ($includecontext) {
791 $pathsections[] = '$' . $contextstring . '$';
794 $path = $this->assemble_category_path(array_reverse($pathsections));
796 return $path;
800 * Convert a list of category names, possibly preceeded by one of the
801 * context tokens like $course$, into a string representation of the
802 * category path.
804 * Names are separated by / delimiters. And /s in the name are replaced by //.
806 * To reverse the process and split the paths into names, use
807 * {@link split_category_path()}.
809 * @param array $names
810 * @return string
812 protected function assemble_category_path($names) {
813 $escapednames = array();
814 foreach ($names as $name) {
815 $escapedname = str_replace('/', '//', $name);
816 if (substr($escapedname, 0, 1) == '/') {
817 $escapedname = ' ' . $escapedname;
819 if (substr($escapedname, -1) == '/') {
820 $escapedname = $escapedname . ' ';
822 $escapednames[] = $escapedname;
824 return implode('/', $escapednames);
828 * Convert a string, as returned by {@link assemble_category_path()},
829 * back into an array of category names.
831 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
832 * which matches the cleaning in question/category_form.php.
834 * @param string $path
835 * @return array of category names.
837 protected function split_category_path($path) {
838 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
839 $names = array();
840 foreach ($rawnames as $rawname) {
841 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
843 return $names;
847 * Do an post-processing that may be required
848 * @return bool success
850 protected function exportpostprocess() {
851 return true;
855 * convert a single question object into text output in the given
856 * format.
857 * This must be overriden
858 * @param object question question object
859 * @return mixed question export text or null if not implemented
861 protected function writequestion($question) {
862 // if not overidden, then this is an error.
863 $formatnotimplemented = get_string('formatnotimplemented', 'question');
864 echo "<p>$formatnotimplemented</p>";
865 return null;
869 * Convert the question text to plain text, so it can safely be displayed
870 * during import to let the user see roughly what is going on.
872 protected function format_question_text($question) {
873 global $DB;
874 $formatoptions = new stdClass();
875 $formatoptions->noclean = true;
876 return html_to_text(format_text($question->questiontext,
877 $question->questiontextformat, $formatoptions), 0, false);
881 * convert files into text output in the given format.
882 * @param array
883 * @param string encoding method
884 * @return string $string
886 protected function writefiles($files, $encoding='base64') {
887 if (empty($files)) {
888 return '';
890 $string = '';
891 foreach ($files as $file) {
892 if ($file->is_directory()) {
893 continue;
895 $string .= '<file name="' . $file->get_filename() . '" encoding="' . $encoding . '">';
896 $string .= base64_encode($file->get_content());
897 $string .= '</file>';
899 return $string;