MDL-22414 Fixed the id generation entropy
[moodle.git] / question / format.php
blob8cb7fa9ba75b8705efd246565314b42c474d0a15
1 <?php
2 /**
3 * Base class for question import and export formats.
5 * @author Martin Dougiamas, Howard Miller, and many others.
6 * {@link http://moodle.org}
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
8 * @package questionbank
9 * @subpackage importexport
11 class qformat_default {
13 public $displayerrors = true;
14 public $category = NULL;
15 public $questions = array();
16 public $course = NULL;
17 public $filename = '';
18 public $realfilename = '';
19 public $matchgrades = 'error';
20 public $catfromfile = 0;
21 public $contextfromfile = 0;
22 public $cattofile = 0;
23 public $contexttofile = 0;
24 public $questionids = array();
25 public $importerrors = 0;
26 public $stoponerror = true;
27 public $translator = null;
28 public $canaccessbackupdata = true;
30 protected $importcontext = null;
32 // functions to indicate import/export functionality
33 // override to return true if implemented
35 /** @return boolean whether this plugin provides import functionality. */
36 function provide_import() {
37 return false;
40 /** @return boolean whether this plugin provides export functionality. */
41 function provide_export() {
42 return false;
45 /** The string mime-type of the files that this plugin reads or writes. */
46 function mime_type() {
47 return mimeinfo('type', $this->export_file_extension());
50 /**
51 * @return string the file extension (including .) that is normally used for
52 * files handled by this plugin.
54 function export_file_extension() {
55 return '.txt';
58 // Accessor methods
60 /**
61 * set the category
62 * @param object category the category object
64 function setCategory($category) {
65 if (count($this->questions)) {
66 debugging('You shouldn\'t call setCategory after setQuestions');
68 $this->category = $category;
71 /**
72 * Set the specific questions to export. Should not include questions with
73 * parents (sub questions of cloze question type).
74 * Only used for question export.
75 * @param array of question objects
77 function setQuestions($questions) {
78 if ($this->category !== null) {
79 debugging('You shouldn\'t call setQuestions after setCategory');
81 $this->questions = $questions;
84 /**
85 * set the course class variable
86 * @param course object Moodle course variable
88 function setCourse($course) {
89 $this->course = $course;
92 /**
93 * set an array of contexts.
94 * @param array $contexts Moodle course variable
96 function setContexts($contexts) {
97 $this->contexts = $contexts;
98 $this->translator = new context_to_string_translator($this->contexts);
102 * set the filename
103 * @param string filename name of file to import/export
105 function setFilename($filename) {
106 $this->filename = $filename;
110 * set the "real" filename
111 * (this is what the user typed, regardless of wha happened next)
112 * @param string realfilename name of file as typed by user
114 function setRealfilename($realfilename) {
115 $this->realfilename = $realfilename;
119 * set matchgrades
120 * @param string matchgrades error or nearest for grades
122 function setMatchgrades($matchgrades) {
123 $this->matchgrades = $matchgrades;
127 * set catfromfile
128 * @param bool catfromfile allow categories embedded in import file
130 function setCatfromfile($catfromfile) {
131 $this->catfromfile = $catfromfile;
135 * set contextfromfile
136 * @param bool $contextfromfile allow contexts embedded in import file
138 function setContextfromfile($contextfromfile) {
139 $this->contextfromfile = $contextfromfile;
143 * set cattofile
144 * @param bool cattofile exports categories within export file
146 function setCattofile($cattofile) {
147 $this->cattofile = $cattofile;
151 * set contexttofile
152 * @param bool cattofile exports categories within export file
154 function setContexttofile($contexttofile) {
155 $this->contexttofile = $contexttofile;
159 * set stoponerror
160 * @param bool stoponerror stops database write if any errors reported
162 function setStoponerror($stoponerror) {
163 $this->stoponerror = $stoponerror;
167 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
168 * where export files are saved.
170 function set_can_access_backupdata($canaccess) {
171 $this->canaccessbackupdata = $canaccess;
174 /***********************
175 * IMPORTING FUNCTIONS
176 ***********************/
179 * Handle parsing error
181 function error($message, $text='', $questionname='') {
182 $importerrorquestion = get_string('importerrorquestion','quiz');
184 echo "<div class=\"importerror\">\n";
185 echo "<strong>$importerrorquestion $questionname</strong>";
186 if (!empty($text)) {
187 $text = s($text);
188 echo "<blockquote>$text</blockquote>\n";
190 echo "<strong>$message</strong>\n";
191 echo "</div>";
193 $this->importerrors++;
197 * Import for questiontype plugins
198 * Do not override.
199 * @param data mixed The segment of data containing the question
200 * @param question object processed (so far) by standard import code if appropriate
201 * @param extra mixed any additional format specific data that may be passed by the format
202 * @param qtypehint hint about a question type from format
203 * @return object question object suitable for save_options() or false if cannot handle
205 function try_importing_using_qtypes($data, $question=null, $extra=null, $qtypehint='') {
206 global $QTYPES;
208 // work out what format we are using
209 $formatname = substr(get_class($this), strlen('qformat_'));
210 $methodname = "import_from_$formatname";
212 //first try importing using a hint from format
213 if (!empty($qtypehint)) {
214 $qtype = $QTYPES[$qtypehint];
215 if (is_object($qtype) && method_exists($qtype, $methodname)) {
216 $question = $qtype->$methodname($data, $question, $this, $extra);
217 if ($question) {
218 return $question;
223 // loop through installed questiontypes checking for
224 // function to handle this question
225 foreach ($QTYPES as $qtype) {
226 if (method_exists($qtype, $methodname)) {
227 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
228 return $question;
232 return false;
236 * Perform any required pre-processing
237 * @return boolean success
239 function importpreprocess() {
240 return true;
244 * Process the file
245 * This method should not normally be overidden
246 * @param object $context
247 * @return boolean success
249 function importprocess($category) {
250 global $USER, $CFG, $DB, $OUTPUT, $QTYPES;
252 $context = $category->context;
253 $this->importcontext = $context;
255 // reset the timer in case file upload was slow
256 set_time_limit(0);
258 // STAGE 1: Parse the file
259 echo $OUTPUT->notification(get_string('parsingquestions','quiz'));
261 if (! $lines = $this->readdata($this->filename)) {
262 echo $OUTPUT->notification(get_string('cannotread','quiz'));
263 return false;
266 if (!$questions = $this->readquestions($lines, $context)) { // Extract all the questions
267 echo $OUTPUT->notification(get_string('noquestionsinfile','quiz'));
268 return false;
271 // STAGE 2: Write data to database
272 echo $OUTPUT->notification(get_string('importingquestions','quiz',$this->count_questions($questions)));
274 // check for errors before we continue
275 if ($this->stoponerror and ($this->importerrors>0)) {
276 echo $OUTPUT->notification(get_string('importparseerror','quiz'));
277 return true;
280 // get list of valid answer grades
281 $grades = get_grade_options();
282 $gradeoptionsfull = $grades->gradeoptionsfull;
284 // check answer grades are valid
285 // (now need to do this here because of 'stop on error': MDL-10689)
286 $gradeerrors = 0;
287 $goodquestions = array();
288 foreach ($questions as $question) {
290 if (!empty($question->fraction) and (is_array($question->fraction))) {
291 $fractions = $question->fraction;
292 $answersvalid = true; // in case they are!
293 foreach ($fractions as $key => $fraction) {
294 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
295 if ($newfraction===false) {
296 $answersvalid = false;
298 else {
299 $fractions[$key] = $newfraction;
302 if (!$answersvalid) {
303 echo $OUTPUT->notification(get_string('matcherror', 'quiz'));
304 ++$gradeerrors;
305 continue;
307 else {
308 $question->fraction = $fractions;
311 $goodquestions[] = $question;
313 $questions = $goodquestions;
315 // check for errors before we continue
316 if ($this->stoponerror and ($gradeerrors>0)) {
317 return false;
320 // count number of questions processed
321 $count = 0;
323 foreach ($questions as $question) { // Process and store each question
325 // reset the php timeout
326 @set_time_limit(0);
328 // check for category modifiers
329 if ($question->qtype == 'category') {
330 if ($this->catfromfile) {
331 // find/create category object
332 $catpath = $question->category;
333 $newcategory = $this->create_category_path($catpath);
334 if (!empty($newcategory)) {
335 $this->category = $newcategory;
338 continue;
340 $question->context = $context;
342 $count++;
344 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
346 $question->category = $this->category->id;
347 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
349 $question->createdby = $USER->id;
350 $question->timecreated = time();
352 $question->id = $DB->insert_record('question', $question);
353 if (isset($question->questiontextfiles)) {
354 foreach ($question->questiontextfiles as $file) {
355 $QTYPES[$question->qtype]->import_file($context, 'question', 'questiontext', $question->id, $file);
358 if (isset($question->generalfeedbackfiles)) {
359 foreach ($question->generalfeedbackfiles as $file) {
360 $QTYPES[$question->qtype]->import_file($context, 'question', 'generalfeedback', $question->id, $file);
364 $this->questionids[] = $question->id;
366 // Now to save all the answers and type-specific options
368 $result = $QTYPES[$question->qtype]->save_question_options($question);
370 if (!empty($CFG->usetags) && isset($question->tags)) {
371 require_once($CFG->dirroot . '/tag/lib.php');
372 tag_set('question', $question->id, $question->tags);
375 if (!empty($result->error)) {
376 echo $OUTPUT->notification($result->error);
377 return false;
380 if (!empty($result->notice)) {
381 echo $OUTPUT->notification($result->notice);
382 return true;
385 // Give the question a unique version stamp determined by question_hash()
386 $DB->set_field('question', 'version', question_hash($question), array('id'=>$question->id));
388 return true;
392 * Count all non-category questions in the questions array.
394 * @param array questions An array of question objects.
395 * @return int The count.
398 function count_questions($questions) {
399 $count = 0;
400 if (!is_array($questions)) {
401 return $count;
403 foreach ($questions as $question) {
404 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
405 continue;
407 $count++;
409 return $count;
413 * find and/or create the category described by a delimited list
414 * e.g. $course$/tom/dick/harry or tom/dick/harry
416 * removes any context string no matter whether $getcontext is set
417 * but if $getcontext is set then ignore the context and use selected category context.
419 * @param string catpath delimited category path
420 * @param int courseid course to search for categories
421 * @return mixed category object or null if fails
423 function create_category_path($catpath) {
424 global $DB;
425 $catnames = $this->split_category_path($catpath);
426 $parent = 0;
427 $category = null;
429 // check for context id in path, it might not be there in pre 1.9 exports
430 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
431 if ($matchcount==1) {
432 $contextid = $this->translator->string_to_context($matches[1]);
433 array_shift($catnames);
434 } else {
435 $contextid = false;
438 if ($this->contextfromfile && $contextid !== false) {
439 $context = get_context_instance_by_id($contextid);
440 require_capability('moodle/question:add', $context);
441 } else {
442 $context = get_context_instance_by_id($this->category->contextid);
445 // Now create any categories that need to be created.
446 foreach ($catnames as $catname) {
447 if ($category = $DB->get_record('question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
448 $parent = $category->id;
449 } else {
450 require_capability('moodle/question:managecategory', $context);
451 // create the new category
452 $category = new stdClass();
453 $category->contextid = $context->id;
454 $category->name = $catname;
455 $category->info = '';
456 $category->parent = $parent;
457 $category->sortorder = 999;
458 $category->stamp = make_unique_id_code();
459 $id = $DB->insert_record('question_categories', $category);
460 $category->id = $id;
461 $parent = $id;
464 return $category;
468 * Return complete file within an array, one item per line
469 * @param string filename name of file
470 * @return mixed contents array or false on failure
472 function readdata($filename) {
473 if (is_readable($filename)) {
474 $filearray = file($filename);
476 /// Check for Macintosh OS line returns (ie file on one line), and fix
477 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
478 return explode("\r", $filearray[0]);
479 } else {
480 return $filearray;
483 return false;
487 * Parses an array of lines into an array of questions,
488 * where each item is a question object as defined by
489 * readquestion(). Questions are defined as anything
490 * between blank lines.
492 * If your format does not use blank lines as a delimiter
493 * then you will need to override this method. Even then
494 * try to use readquestion for each question
495 * @param array lines array of lines from readdata
496 * @param object $context
497 * @return array array of question objects
499 function readquestions($lines, $context) {
501 $questions = array();
502 $currentquestion = array();
504 foreach ($lines as $line) {
505 $line = trim($line);
506 if (empty($line)) {
507 if (!empty($currentquestion)) {
508 if ($question = $this->readquestion($currentquestion)) {
509 $questions[] = $question;
511 $currentquestion = array();
513 } else {
514 $currentquestion[] = $line;
518 if (!empty($currentquestion)) { // There may be a final question
519 if ($question = $this->readquestion($currentquestion, $context)) {
520 $questions[] = $question;
524 return $questions;
528 * return an "empty" question
529 * Somewhere to specify question parameters that are not handled
530 * by import but are required db fields.
531 * This should not be overridden.
532 * @return object default question
534 function defaultquestion() {
535 global $CFG;
536 static $defaultshuffleanswers = null;
537 if (is_null($defaultshuffleanswers)) {
538 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
541 $question = new stdClass();
542 $question->shuffleanswers = $defaultshuffleanswers;
543 $question->defaultgrade = 1;
544 $question->image = "";
545 $question->usecase = 0;
546 $question->multiplier = array();
547 $question->generalfeedback = '';
548 $question->correctfeedback = '';
549 $question->partiallycorrectfeedback = '';
550 $question->incorrectfeedback = '';
551 $question->answernumbering = 'abc';
552 $question->penalty = 0.1;
553 $question->length = 1;
555 // this option in case the questiontypes class wants
556 // to know where the data came from
557 $question->export_process = true;
558 $question->import_process = true;
560 return $question;
564 * Given the data known to define a question in
565 * this format, this function converts it into a question
566 * object suitable for processing and insertion into Moodle.
568 * If your format does not use blank lines to delimit questions
569 * (e.g. an XML format) you must override 'readquestions' too
570 * @param $lines mixed data that represents question
571 * @return object question object
573 function readquestion($lines) {
575 $formatnotimplemented = get_string('formatnotimplemented','quiz');
576 echo "<p>$formatnotimplemented</p>";
578 return NULL;
582 * Override if any post-processing is required
583 * @return boolean success
585 function importpostprocess() {
586 return true;
590 /*******************
591 * EXPORT FUNCTIONS
592 *******************/
595 * Provide export functionality for plugin questiontypes
596 * Do not override
597 * @param name questiontype name
598 * @param question object data to export
599 * @param extra mixed any addition format specific data needed
600 * @return string the data to append to export or false if error (or unhandled)
602 function try_exporting_using_qtypes($name, $question, $extra=null) {
603 global $QTYPES;
605 // work out the name of format in use
606 $formatname = substr(get_class($this), strlen('qformat_'));
607 $methodname = "export_to_$formatname";
609 if (array_key_exists($name, $QTYPES)) {
610 $qtype = $QTYPES[ $name ];
611 if (method_exists($qtype, $methodname)) {
612 if ($data = $qtype->$methodname($question, $this, $extra)) {
613 return $data;
617 return false;
621 * Do any pre-processing that may be required
622 * @param boolean success
624 function exportpreprocess() {
625 return true;
629 * Enable any processing to be done on the content
630 * just prior to the file being saved
631 * default is to do nothing
632 * @param string output text
633 * @param string processed output text
635 function presave_process($content) {
636 return $content;
640 * Do the export
641 * For most types this should not need to be overrided
642 * @return stored_file
644 function exportprocess() {
645 global $CFG, $OUTPUT, $DB, $USER;
647 // get the questions (from database) in this category
648 // only get q's with no parents (no cloze subquestions specifically)
649 if ($this->category) {
650 $questions = get_questions_category($this->category, true);
651 } else {
652 $questions = $this->questions;
655 //echo $OUTPUT->notification(get_string('exportingquestions','quiz'));
656 $count = 0;
658 // results are first written into string (and then to a file)
659 // so create/initialize the string here
660 $expout = "";
662 // track which category questions are in
663 // if it changes we will record the category change in the output
664 // file if selected. 0 means that it will get printed before the 1st question
665 $trackcategory = 0;
667 $fs = get_file_storage();
669 // iterate through questions
670 foreach($questions as $question) {
671 // used by file api
672 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$question->category));
673 $question->contextid = $contextid;
675 // do not export hidden questions
676 if (!empty($question->hidden)) {
677 continue;
680 // do not export random questions
681 if ($question->qtype==RANDOM) {
682 continue;
685 // check if we need to record category change
686 if ($this->cattofile) {
687 if ($question->category != $trackcategory) {
688 $trackcategory = $question->category;
689 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
691 // create 'dummy' question for category export
692 $dummyquestion = new stdClass();
693 $dummyquestion->qtype = 'category';
694 $dummyquestion->category = $categoryname;
695 $dummyquestion->name = 'Switch category to ' . $categoryname;
696 $dummyquestion->id = 0;
697 $dummyquestion->questiontextformat = '';
698 $dummyquestion->contextid = 0;
699 $expout .= $this->writequestion($dummyquestion) . "\n";
703 // export the question displaying message
704 $count++;
706 if (question_has_capability_on($question, 'view', $question->category)) {
707 // files used by questiontext
708 $files = $fs->get_area_files($contextid, 'question', 'questiontext', $question->id);
709 $question->questiontextfiles = $files;
710 // files used by generalfeedback
711 $files = $fs->get_area_files($contextid, 'question', 'generalfeedback', $question->id);
712 $question->generalfeedbackfiles = $files;
713 if (!empty($question->options->answers)) {
714 foreach ($question->options->answers as $answer) {
715 $files = $fs->get_area_files($contextid, 'question', 'answerfeedback', $answer->id);
716 $answer->feedbackfiles = $files;
720 $expout .= $this->writequestion($question, $contextid) . "\n";
724 // continue path for following error checks
725 $course = $this->course;
726 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
728 // did we actually process anything
729 if ($count==0) {
730 print_error('noquestions','quiz',$continuepath);
733 // final pre-process on exported data
734 $expout = $this->presave_process($expout);
735 return $expout;
739 * get the category as a path (e.g., tom/dick/harry)
740 * @param int id the id of the most nested catgory
741 * @return string the path
743 function get_category_path($id, $includecontext = true) {
744 global $DB;
746 if (!$category = $DB->get_record('question_categories',array('id' =>$id))) {
747 print_error('cannotfindcategory', 'error', '', $id);
749 $contextstring = $this->translator->context_to_string($category->contextid);
751 $pathsections = array();
752 do {
753 $pathsections[] = $category->name;
754 $id = $category->parent;
755 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
757 if ($includecontext) {
758 $pathsections[] = '$' . $contextstring . '$';
761 $path = $this->assemble_category_path(array_reverse($pathsections));
763 return $path;
767 * Convert a list of category names, possibly preceeded by one of the
768 * context tokens like $course$, into a string representation of the
769 * category path.
771 * Names are separated by / delimiters. And /s in the name are replaced by //.
773 * To reverse the process and split the paths into names, use
774 * {@link split_category_path()}.
776 * @param array $names
777 * @return string
779 protected function assemble_category_path($names) {
780 $escapednames = array();
781 foreach ($names as $name) {
782 $escapedname = str_replace('/', '//', $name);
783 if (substr($escapedname, 0, 1) == '/') {
784 $escapedname = ' ' . $escapedname;
786 if (substr($escapedname, -1) == '/') {
787 $escapedname = $escapedname . ' ';
789 $escapednames[] = $escapedname;
791 return implode('/', $escapednames);
795 * Convert a string, as returned by {@link assemble_category_path()},
796 * back into an array of category names.
798 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
799 * which matches the cleaning in question/category_form.php.
801 * @param string $path
802 * @return array of category names.
804 protected function split_category_path($path) {
805 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
806 $names = array();
807 foreach ($rawnames as $rawname) {
808 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
810 return $names;
814 * Do an post-processing that may be required
815 * @return boolean success
817 function exportpostprocess() {
818 return true;
822 * convert a single question object into text output in the given
823 * format.
824 * This must be overriden
825 * @param object question question object
826 * @return mixed question export text or null if not implemented
828 function writequestion($question) {
829 // if not overidden, then this is an error.
830 $formatnotimplemented = get_string('formatnotimplemented','quiz');
831 echo "<p>$formatnotimplemented</p>";
832 return NULL;
836 * get directory into which export is going
837 * @return string file path
839 function question_get_export_dir() {
840 global $USER;
841 if ($this->canaccessbackupdata) {
842 $dirname = get_string("exportfilename","quiz");
843 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
844 } else {
845 $path = 'temp/questionexport/' . $USER->id;
847 return $path;
851 * Convert the question text to plain text, so it can safely be displayed
852 * during import to let the user see roughly what is going on.
854 function format_question_text($question) {
855 global $DB;
856 $formatoptions = new stdClass;
857 $formatoptions->noclean = true;
858 $formatoptions->para = false;
859 if (empty($question->questiontextformat)) {
860 $format = FORMAT_MOODLE;
861 } else {
862 $format = $question->questiontextformat;
864 $text = $question->questiontext;
865 return format_text(html_to_text($text, 0, false), $format, $formatoptions);
869 * convert files into text output in the given format.
870 * @param array
871 * @param string encoding method
872 * @return string $string
874 function writefiles($files, $encoding='base64') {
875 if (empty($files)) {
876 return '';
878 $string = '';
879 foreach ($files as $file) {
880 if ($file->is_directory()) {
881 continue;
883 $string .= '<file name="' . $file->get_filename() . '" encoding="' . $encoding . '">';
884 $string .= base64_encode($file->get_content());
885 $string .= '</file>';
887 return $string;