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 var $displayerrors = true;
15 var $questions = array();
18 var $matchgrades = 'error';
20 var $contextfromfile = 0;
22 var $contexttofile = 0;
23 var $questionids = array();
24 var $importerrors = 0;
25 var $stoponerror = true;
26 var $translator = null;
29 // functions to indicate import/export functionality
30 // override to return true if implemented
32 function provide_import() {
36 function provide_export() {
44 * @param object category the category object
46 function setCategory( $category ) {
47 if (count($this->questions
)){
48 debugging('You shouldn\'t call setCategory after setQuestions');
50 $this->category
= $category;
54 * Set the specific questions to export. Should not include questions with
55 * parents (sub questions of cloze question type).
56 * Only used for question export.
57 * @param array of question objects
59 function setQuestions( $questions ) {
60 if ($this->category
!== null){
61 debugging('You shouldn\'t call setQuestions after setCategory');
63 $this->questions
= $questions;
67 * set the course class variable
68 * @param course object Moodle course variable
70 function setCourse( $course ) {
71 $this->course
= $course;
74 * set an array of contexts.
75 * @param array $contexts Moodle course variable
77 function setContexts($contexts) {
78 $this->contexts
= $contexts;
79 $this->translator
= new context_to_string_translator($this->contexts
);
84 * @param string filename name of file to import/export
86 function setFilename( $filename ) {
87 $this->filename
= $filename;
92 * @param string matchgrades error or nearest for grades
94 function setMatchgrades( $matchgrades ) {
95 $this->matchgrades
= $matchgrades;
100 * @param bool catfromfile allow categories embedded in import file
102 function setCatfromfile( $catfromfile ) {
103 $this->catfromfile
= $catfromfile;
107 * set contextfromfile
108 * @param bool $contextfromfile allow contexts embedded in import file
110 function setContextfromfile($contextfromfile) {
111 $this->contextfromfile
= $contextfromfile;
116 * @param bool cattofile exports categories within export file
118 function setCattofile( $cattofile ) {
119 $this->cattofile
= $cattofile;
123 * @param bool cattofile exports categories within export file
125 function setContexttofile($contexttofile) {
126 $this->contexttofile
= $contexttofile;
131 * @param bool stoponerror stops database write if any errors reported
133 function setStoponerror( $stoponerror ) {
134 $this->stoponerror
= $stoponerror;
137 /***********************
138 * IMPORTING FUNCTIONS
139 ***********************/
142 * Handle parsing error
144 function error( $message, $text='', $questionname='' ) {
145 $importerrorquestion = get_string('importerrorquestion','quiz');
147 echo "<div class=\"importerror\">\n";
148 echo "<strong>$importerrorquestion $questionname</strong>";
151 echo "<blockquote>$text</blockquote>\n";
153 echo "<strong>$message</strong>\n";
156 $this->importerrors++
;
160 * Import for questiontype plugins
162 * @param data mixed The segment of data containing the question
163 * @param question object processed (so far) by standard import code if appropriate
164 * @param extra mixed any additional format specific data that may be passed by the format
165 * @return object question object suitable for save_options() or false if cannot handle
167 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
170 // work out what format we are using
171 $formatname = substr( get_class( $this ), strlen('qformat_'));
172 $methodname = "import_from_$formatname";
174 // loop through installed questiontypes checking for
175 // function to handle this question
176 foreach ($QTYPES as $qtype) {
177 if (method_exists( $qtype, $methodname)) {
178 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
187 * Perform any required pre-processing
188 * @return boolean success
190 function importpreprocess() {
196 * This method should not normally be overidden
197 * @return boolean success
199 function importprocess() {
202 // reset the timer in case file upload was slow
205 // STAGE 1: Parse the file
206 notify( get_string('parsingquestions','quiz') );
208 if (! $lines = $this->readdata($this->filename
)) {
209 notify( get_string('cannotread','quiz') );
213 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
214 notify( get_string('noquestionsinfile','quiz') );
218 // STAGE 2: Write data to database
219 notify( get_string('importingquestions','quiz',$this->count_questions($questions)) );
221 // check for errors before we continue
222 if ($this->stoponerror
and ($this->importerrors
>0)) {
226 // get list of valid answer grades
227 $grades = get_grade_options();
228 $gradeoptionsfull = $grades->gradeoptionsfull
;
230 // check answer grades are valid
231 // (now need to do this here because of 'stop on error': MDL-10689)
233 $goodquestions = array();
234 foreach ($questions as $question) {
235 if (!empty($question->fraction
) and (is_array($question->fraction
))) {
236 $fractions = $question->fraction
;
237 $answersvalid = true; // in case they are!
238 foreach ($fractions as $key => $fraction) {
239 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades
);
240 if ($newfraction===false) {
241 $answersvalid = false;
244 $fractions[$key] = $newfraction;
247 if (!$answersvalid) {
248 notify(get_string('matcherror', 'quiz'));
253 $question->fraction
= $fractions;
256 $goodquestions[] = $question;
258 $questions = $goodquestions;
260 // check for errors before we continue
261 if ($this->stoponerror
and ($gradeerrors>0)) {
265 // count number of questions processed
268 foreach ($questions as $question) { // Process and store each question
270 // reset the php timeout
273 // check for category modifiers
274 if ($question->qtype
=='category') {
275 if ($this->catfromfile
) {
276 // find/create category object
277 $catpath = $question->category
;
278 $newcategory = $this->create_category_path( $catpath, '/');
279 if (!empty($newcategory)) {
280 $this->category
= $newcategory;
288 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
290 $question->category
= $this->category
->id
;
291 $question->stamp
= make_unique_id_code(); // Set the unique code (not to be changed)
293 $question->createdby
= $USER->id
;
294 $question->timecreated
= time();
296 if (!$question->id
= insert_record("question", $question)) {
297 error( get_string('cannotinsert','quiz') );
300 $this->questionids
[] = $question->id
;
302 // Now to save all the answers and type-specific options
305 $result = $QTYPES[$question->qtype
]
306 ->save_question_options($question);
308 if (!empty($result->error
)) {
309 notify($result->error
);
313 if (!empty($result->notice
)) {
314 notify($result->notice
);
318 // Give the question a unique version stamp determined by question_hash()
319 set_field('question', 'version', question_hash($question), 'id', $question->id
);
324 * Count all non-category questions in the questions array.
326 * @param array questions An array of question objects.
327 * @return int The count.
330 function count_questions($questions) {
332 if (!is_array($questions)) {
335 foreach ($questions as $question) {
336 if (!is_object($question) ||
!isset($question->qtype
) ||
($question->qtype
== 'category')) {
345 * find and/or create the category described by a delimited list
346 * e.g. $course$/tom/dick/harry or tom/dick/harry
348 * removes any context string no matter whether $getcontext is set
349 * but if $getcontext is set then ignore the context and use selected category context.
351 * @param string catpath delimited category path
352 * @param string delimiter path delimiting character
353 * @param int courseid course to search for categories
354 * @return mixed category object or null if fails
356 function create_category_path($catpath, $delimiter='/') {
357 $catpath = clean_param($catpath, PARAM_PATH
);
358 $catnames = explode($delimiter, $catpath);
361 if (FALSE !== preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches)){
362 $contextid = $this->translator
->string_to_context($matches[1]);
363 array_shift($catnames);
367 if ($this->contextfromfile
&& ($contextid !== FALSE)){
368 $context = get_context_instance_by_id($contextid);
369 require_capability('moodle/question:add', $context);
371 $context = get_context_instance_by_id($this->category
->contextid
);
373 foreach ($catnames as $catname) {
374 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id
, 'parent', $parent)) {
375 $parent = $category->id
;
377 require_capability('moodle/question:managecategory', $context);
378 // create the new category
379 $category = new object;
380 $category->contextid
= $context->id
;
381 $category->name
= $catname;
382 $category->info
= '';
383 $category->parent
= $parent;
384 $category->sortorder
= 999;
385 $category->stamp
= make_unique_id_code();
386 if (!($id = insert_record('question_categories', $category))) {
387 error( "cannot create new category - $catname" );
397 * Return complete file within an array, one item per line
398 * @param string filename name of file
399 * @return mixed contents array or false on failure
401 function readdata($filename) {
402 if (is_readable($filename)) {
403 $filearray = file($filename);
405 /// Check for Macintosh OS line returns (ie file on one line), and fix
406 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
407 return explode("\r", $filearray[0]);
416 * Parses an array of lines into an array of questions,
417 * where each item is a question object as defined by
418 * readquestion(). Questions are defined as anything
419 * between blank lines.
421 * If your format does not use blank lines as a delimiter
422 * then you will need to override this method. Even then
423 * try to use readquestion for each question
424 * @param array lines array of lines from readdata
425 * @return array array of question objects
427 function readquestions($lines) {
429 $questions = array();
430 $currentquestion = array();
432 foreach ($lines as $line) {
435 if (!empty($currentquestion)) {
436 if ($question = $this->readquestion($currentquestion)) {
437 $questions[] = $question;
439 $currentquestion = array();
442 $currentquestion[] = $line;
446 if (!empty($currentquestion)) { // There may be a final question
447 if ($question = $this->readquestion($currentquestion)) {
448 $questions[] = $question;
457 * return an "empty" question
458 * Somewhere to specify question parameters that are not handled
459 * by import but are required db fields.
460 * This should not be overridden.
461 * @return object default question
463 function defaultquestion() {
466 $question = new stdClass();
467 $question->shuffleanswers
= $CFG->quiz_shuffleanswers
;
468 $question->defaultgrade
= 1;
469 $question->image
= "";
470 $question->usecase
= 0;
471 $question->multiplier
= array();
472 $question->generalfeedback
= '';
473 $question->correctfeedback
= '';
474 $question->partiallycorrectfeedback
= '';
475 $question->incorrectfeedback
= '';
476 $question->answernumbering
= 'abc';
477 $question->penalty
= 0.1;
478 $question->length
= 1;
480 // this option in case the questiontypes class wants
481 // to know where the data came from
482 $question->export_process
= true;
483 $question->import_process
= true;
489 * Given the data known to define a question in
490 * this format, this function converts it into a question
491 * object suitable for processing and insertion into Moodle.
493 * If your format does not use blank lines to delimit questions
494 * (e.g. an XML format) you must override 'readquestions' too
495 * @param $lines mixed data that represents question
496 * @return object question object
498 function readquestion($lines) {
500 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
501 echo "<p>$formatnotimplemented</p>";
507 * Override if any post-processing is required
508 * @return boolean success
510 function importpostprocess() {
515 * Import an image file encoded in base64 format
516 * @param string path path (in course data) to store picture
517 * @param string base64 encoded picture
518 * @return string filename (nb. collisions are handled)
520 function importimagefile( $path, $base64 ) {
523 // all this to get the destination directory
525 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
526 $path_parts = pathinfo( $fullpath );
527 $destination = $path_parts['dirname'];
528 $file = clean_filename( $path_parts['basename'] );
530 // check if path exists
531 check_dir_exists($destination, true, true );
533 // detect and fix any filename collision - get unique filename
534 $newfiles = resolve_filename_collisions( $destination, array($file) );
535 $newfile = $newfiles[0];
537 // convert and save file contents
538 if (!$content = base64_decode( $base64 )) {
541 $newfullpath = "$destination/$newfile";
542 if (!$fh = fopen( $newfullpath, 'w' )) {
545 if (!fwrite( $fh, $content )) {
550 // return the (possibly) new filename
551 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
561 * Provide export functionality for plugin questiontypes
563 * @param name questiontype name
564 * @param question object data to export
565 * @param extra mixed any addition format specific data needed
566 * @return string the data to append to export or false if error (or unhandled)
568 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
571 // work out the name of format in use
572 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
573 $methodname = "export_to_$formatname";
575 if (array_key_exists( $name, $QTYPES )) {
576 $qtype = $QTYPES[ $name ];
577 if (method_exists( $qtype, $methodname )) {
578 if ($data = $qtype->$methodname( $question, $this, $extra )) {
587 * Return the files extension appropriate for this type
588 * override if you don't want .txt
589 * @return string file extension
591 function export_file_extension() {
596 * Do any pre-processing that may be required
597 * @param boolean success
599 function exportpreprocess() {
604 * Enable any processing to be done on the content
605 * just prior to the file being saved
606 * default is to do nothing
607 * @param string output text
608 * @param string processed output text
610 function presave_process( $content ) {
616 * For most types this should not need to be overrided
617 * @return boolean success
619 function exportprocess() {
622 // create a directory for the exports (if not already existing)
623 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
624 error( get_string('cannotcreatepath','quiz',$export_dir) );
626 $path = $CFG->dataroot
.'/'.$this->question_get_export_dir();
628 // get the questions (from database) in this category
629 // only get q's with no parents (no cloze subquestions specifically)
630 if ($this->category
){
631 $questions = get_questions_category( $this->category
, true );
633 $questions = $this->questions
;
636 notify( get_string('exportingquestions','quiz') );
639 // results are first written into string (and then to a file)
640 // so create/initialize the string here
643 // track which category questions are in
644 // if it changes we will record the category change in the output
645 // file if selected. 0 means that it will get printed before the 1st question
648 // iterate through questions
649 foreach($questions as $question) {
651 // do not export hidden questions
652 if (!empty($question->hidden
)) {
656 // do not export random questions
657 if ($question->qtype
==RANDOM
) {
661 // check if we need to record category change
662 if ($this->cattofile
) {
663 if ($question->category
!= $trackcategory) {
664 $trackcategory = $question->category
;
665 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile
);
667 // create 'dummy' question for category export
668 $dummyquestion = new object;
669 $dummyquestion->qtype
= 'category';
670 $dummyquestion->category
= $categoryname;
671 $dummyquestion->name
= "switch category to $categoryname";
672 $dummyquestion->id
= 0;
673 $dummyquestion->questiontextformat
= '';
674 $expout .= $this->writequestion( $dummyquestion ) . "\n";
678 // export the question displaying message
680 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
681 if (question_has_capability_on($question, 'view', $question->category
)){
682 $expout .= $this->writequestion( $question ) . "\n";
686 // continue path for following error checks
687 $course = $this->course
;
688 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
690 // did we actually process anything
692 print_error( 'noquestions','quiz',$continuepath );
695 // final pre-process on exported data
696 $expout = $this->presave_process( $expout );
699 $filepath = $path."/".$this->filename
. $this->export_file_extension();
700 if (!$fh=fopen($filepath,"w")) {
701 print_error( 'cannotopen','quiz',$continuepath,$filepath );
703 if (!fwrite($fh, $expout, strlen($expout) )) {
704 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
711 * get the category as a path (e.g., tom/dick/harry)
712 * @param int id the id of the most nested catgory
713 * @param string delimiter the delimiter you want
714 * @return string the path
716 function get_category_path($id, $delimiter='/', $includecontext = true) {
718 if (!$firstcategory = get_record('question_categories','id',$id)) {
719 error( "Error getting category record from db - " . $id );
721 $category = $firstcategory;
722 $contextstring = $this->translator
->context_to_string($category->contextid
);
724 $name = $category->name
;
725 $id = $category->parent
;
727 $path = "{$name}{$delimiter}{$path}";
732 } while ($category = get_record( 'question_categories','id',$id ));
734 if ($includecontext){
735 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
741 * Do an post-processing that may be required
742 * @return boolean success
744 function exportpostprocess() {
749 * convert a single question object into text output in the given
751 * This must be overriden
752 * @param object question question object
753 * @return mixed question export text or null if not implemented
755 function writequestion($question) {
756 // if not overidden, then this is an error.
757 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
758 echo "<p>$formatnotimplemented</p>";
763 * get directory into which export is going
764 * @return string file path
766 function question_get_export_dir() {
767 $dirname = get_string("exportfilename","quiz");
768 $path = $this->course
->id
.'/backupdata/'.$dirname; // backupdata is protected directory
773 * where question specifies a moodle (text) format this
774 * performs the conversion.
776 function format_question_text($question) {
777 $formatoptions = new stdClass
;
778 $formatoptions->noclean
= true;
779 $formatoptions->para
= false;
780 if (empty($question->questiontextformat
)) {
781 $format = FORMAT_MOODLE
;
783 $format = $question->questiontextformat
;
785 return format_text(stripslashes($question->questiontext
), $format, $formatoptions);