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 $realfilename = '';
19 var $matchgrades = 'error';
21 var $contextfromfile = 0;
23 var $contexttofile = 0;
24 var $questionids = array();
25 var $importerrors = 0;
26 var $stoponerror = true;
27 var $translator = null;
28 var $canaccessbackupdata = true;
31 // functions to indicate import/export functionality
32 // override to return true if implemented
34 function provide_import() {
38 function provide_export() {
46 * @param object category the category object
48 function setCategory( $category ) {
49 if (count($this->questions
)){
50 debugging('You shouldn\'t call setCategory after setQuestions');
52 $this->category
= $category;
56 * Set the specific questions to export. Should not include questions with
57 * parents (sub questions of cloze question type).
58 * Only used for question export.
59 * @param array of question objects
61 function setQuestions( $questions ) {
62 if ($this->category
!== null){
63 debugging('You shouldn\'t call setQuestions after setCategory');
65 $this->questions
= $questions;
69 * set the course class variable
70 * @param course object Moodle course variable
72 function setCourse( $course ) {
73 $this->course
= $course;
76 * set an array of contexts.
77 * @param array $contexts Moodle course variable
79 function setContexts($contexts) {
80 $this->contexts
= $contexts;
81 $this->translator
= new context_to_string_translator($this->contexts
);
86 * @param string filename name of file to import/export
88 function setFilename( $filename ) {
89 $this->filename
= $filename;
93 * set the "real" filename
94 * (this is what the user typed, regardless of wha happened next)
95 * @param string realfilename name of file as typed by user
97 function setRealfilename( $realfilename ) {
98 $this->realfilename
= $realfilename;
103 * @param string matchgrades error or nearest for grades
105 function setMatchgrades( $matchgrades ) {
106 $this->matchgrades
= $matchgrades;
111 * @param bool catfromfile allow categories embedded in import file
113 function setCatfromfile( $catfromfile ) {
114 $this->catfromfile
= $catfromfile;
118 * set contextfromfile
119 * @param bool $contextfromfile allow contexts embedded in import file
121 function setContextfromfile($contextfromfile) {
122 $this->contextfromfile
= $contextfromfile;
127 * @param bool cattofile exports categories within export file
129 function setCattofile( $cattofile ) {
130 $this->cattofile
= $cattofile;
134 * @param bool cattofile exports categories within export file
136 function setContexttofile($contexttofile) {
137 $this->contexttofile
= $contexttofile;
142 * @param bool stoponerror stops database write if any errors reported
144 function setStoponerror( $stoponerror ) {
145 $this->stoponerror
= $stoponerror;
149 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
150 * where export files are saved.
152 function set_can_access_backupdata($canaccess) {
153 $this->canaccessbackupdata
= $canaccess;
156 /***********************
157 * IMPORTING FUNCTIONS
158 ***********************/
161 * Handle parsing error
163 function error( $message, $text='', $questionname='' ) {
164 $importerrorquestion = get_string('importerrorquestion','quiz');
166 echo "<div class=\"importerror\">\n";
167 echo "<strong>$importerrorquestion $questionname</strong>";
170 echo "<blockquote>$text</blockquote>\n";
172 echo "<strong>$message</strong>\n";
175 $this->importerrors++
;
179 * Import for questiontype plugins
181 * @param data mixed The segment of data containing the question
182 * @param question object processed (so far) by standard import code if appropriate
183 * @param extra mixed any additional format specific data that may be passed by the format
184 * @param qtypehint hint about a question type from format
185 * @return object question object suitable for save_options() or false if cannot handle
187 function try_importing_using_qtypes( $data, $question=null, $extra=null, $qtypehint='') {
190 // work out what format we are using
191 $formatname = substr(get_class($this), strlen('qformat_'));
192 $methodname = "import_from_$formatname";
194 //first try importing using a hint from format
195 if (!empty($qtypehint)) {
196 $qtype = $QTYPES[$qtypehint];
197 if (is_object($qtype) && method_exists($qtype, $methodname)) {
198 $question = $qtype->$methodname($data, $question, $this, $extra);
205 // loop through installed questiontypes checking for
206 // function to handle this question
207 foreach ($QTYPES as $qtype) {
208 if (method_exists( $qtype, $methodname)) {
209 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
218 * Perform any required pre-processing
219 * @return boolean success
221 function importpreprocess() {
227 * This method should not normally be overidden
228 * @return boolean success
230 function importprocess() {
233 // reset the timer in case file upload was slow
236 // STAGE 1: Parse the file
237 notify( get_string('parsingquestions','quiz') );
239 if (! $lines = $this->readdata($this->filename
)) {
240 notify( get_string('cannotread','quiz') );
244 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
245 notify( get_string('noquestionsinfile','quiz') );
249 // STAGE 2: Write data to database
250 notify( get_string('importingquestions','quiz',$this->count_questions($questions)) );
252 // check for errors before we continue
253 if ($this->stoponerror
and ($this->importerrors
>0)) {
254 notify( get_string('importparseerror','quiz') );
258 // get list of valid answer grades
259 $grades = get_grade_options();
260 $gradeoptionsfull = $grades->gradeoptionsfull
;
262 // check answer grades are valid
263 // (now need to do this here because of 'stop on error': MDL-10689)
265 $goodquestions = array();
266 foreach ($questions as $question) {
267 if (!empty($question->fraction
) and (is_array($question->fraction
))) {
268 $fractions = $question->fraction
;
269 $answersvalid = true; // in case they are!
270 foreach ($fractions as $key => $fraction) {
271 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades
);
272 if ($newfraction===false) {
273 $answersvalid = false;
276 $fractions[$key] = $newfraction;
279 if (!$answersvalid) {
280 notify(get_string('matcherror', 'quiz'));
285 $question->fraction
= $fractions;
288 $goodquestions[] = $question;
290 $questions = $goodquestions;
292 // check for errors before we continue
293 if ($this->stoponerror
and ($gradeerrors>0)) {
297 // count number of questions processed
300 foreach ($questions as $question) { // Process and store each question
302 // reset the php timeout
305 // check for category modifiers
306 if ($question->qtype
=='category') {
307 if ($this->catfromfile
) {
308 // find/create category object
309 $catpath = $question->category
;
310 $newcategory = $this->create_category_path($catpath);
311 if (!empty($newcategory)) {
312 $this->category
= $newcategory;
320 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
322 $question->category
= $this->category
->id
;
323 $question->stamp
= make_unique_id_code(); // Set the unique code (not to be changed)
325 $question->createdby
= $USER->id
;
326 $question->timecreated
= time();
328 if (!$question->id
= insert_record("question", $question)) {
329 error( get_string('cannotinsert','quiz') );
332 $this->questionids
[] = $question->id
;
334 // Now to save all the answers and type-specific options
337 $result = $QTYPES[$question->qtype
]
338 ->save_question_options($question);
340 if (!empty($result->error
)) {
341 notify($result->error
);
345 if (!empty($result->notice
)) {
346 notify($result->notice
);
350 // Give the question a unique version stamp determined by question_hash()
351 set_field('question', 'version', question_hash($question), 'id', $question->id
);
356 * Count all non-category questions in the questions array.
358 * @param array questions An array of question objects.
359 * @return int The count.
362 function count_questions($questions) {
364 if (!is_array($questions)) {
367 foreach ($questions as $question) {
368 if (!is_object($question) ||
!isset($question->qtype
) ||
($question->qtype
== 'category')) {
377 * find and/or create the category described by a delimited list
378 * e.g. $course$/tom/dick/harry or tom/dick/harry
380 * removes any context string no matter whether $getcontext is set
381 * but if $getcontext is set then ignore the context and use selected category context.
383 * @param string catpath delimited category path
384 * @param int courseid course to search for categories
385 * @return mixed category object or null if fails
387 function create_category_path($catpath) {
388 $catnames = $this->split_category_path($catpath);
392 // check for context id in path, it might not be there in pre 1.9 exports
393 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
394 if ($matchcount == 1) {
395 $contextid = $this->translator
->string_to_context($matches[1]);
396 array_shift($catnames);
401 if ($this->contextfromfile
&& $contextid !== false) {
402 $context = get_context_instance_by_id($contextid);
403 require_capability('moodle/question:add', $context);
405 $context = get_context_instance_by_id($this->category
->contextid
);
408 // Now create any categories that need to be created.
409 foreach ($catnames as $catname) {
410 if ($category = get_record('question_categories', 'name', $catname, 'contextid', $context->id
, 'parent', $parent)) {
411 $parent = $category->id
;
413 require_capability('moodle/question:managecategory', $context);
414 // create the new category
415 $category = new object;
416 $category->contextid
= $context->id
;
417 $category->name
= $catname;
418 $category->info
= '';
419 $category->parent
= $parent;
420 $category->sortorder
= 999;
421 $category->stamp
= make_unique_id_code();
422 if (!($id = insert_record('question_categories', $category))) {
423 error( "cannot create new category - $catname" );
433 * Return complete file within an array, one item per line
434 * @param string filename name of file
435 * @return mixed contents array or false on failure
437 function readdata($filename) {
438 if (is_readable($filename)) {
439 $filearray = file($filename);
441 /// Check for Macintosh OS line returns (ie file on one line), and fix
442 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
443 return explode("\r", $filearray[0]);
452 * Parses an array of lines into an array of questions,
453 * where each item is a question object as defined by
454 * readquestion(). Questions are defined as anything
455 * between blank lines.
457 * If your format does not use blank lines as a delimiter
458 * then you will need to override this method. Even then
459 * try to use readquestion for each question
460 * @param array lines array of lines from readdata
461 * @return array array of question objects
463 function readquestions($lines) {
465 $questions = array();
466 $currentquestion = array();
468 foreach ($lines as $line) {
471 if (!empty($currentquestion)) {
472 if ($question = $this->readquestion($currentquestion)) {
473 $questions[] = $question;
475 $currentquestion = array();
478 $currentquestion[] = $line;
482 if (!empty($currentquestion)) { // There may be a final question
483 if ($question = $this->readquestion($currentquestion)) {
484 $questions[] = $question;
493 * return an "empty" question
494 * Somewhere to specify question parameters that are not handled
495 * by import but are required db fields.
496 * This should not be overridden.
497 * @return object default question
499 function defaultquestion() {
502 $question = new stdClass();
503 $question->shuffleanswers
= $CFG->quiz_shuffleanswers
;
504 $question->defaultgrade
= 1;
505 $question->image
= "";
506 $question->usecase
= 0;
507 $question->multiplier
= array();
508 $question->generalfeedback
= '';
509 $question->correctfeedback
= '';
510 $question->partiallycorrectfeedback
= '';
511 $question->incorrectfeedback
= '';
512 $question->answernumbering
= 'abc';
513 $question->penalty
= 0.1;
514 $question->length
= 1;
516 // this option in case the questiontypes class wants
517 // to know where the data came from
518 $question->export_process
= true;
519 $question->import_process
= true;
525 * Given the data known to define a question in
526 * this format, this function converts it into a question
527 * object suitable for processing and insertion into Moodle.
529 * If your format does not use blank lines to delimit questions
530 * (e.g. an XML format) you must override 'readquestions' too
531 * @param $lines mixed data that represents question
532 * @return object question object
534 function readquestion($lines) {
536 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
537 echo "<p>$formatnotimplemented</p>";
543 * Override if any post-processing is required
544 * @return boolean success
546 function importpostprocess() {
551 * Import an image file encoded in base64 format
552 * @param string path path (in course data) to store picture
553 * @param string base64 encoded picture
554 * @return string filename (nb. collisions are handled)
556 function importimagefile( $path, $base64 ) {
559 // all this to get the destination directory
561 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
562 $path_parts = pathinfo( $fullpath );
563 $destination = $path_parts['dirname'];
564 $file = clean_filename( $path_parts['basename'] );
566 // check if path exists
567 check_dir_exists($destination, true, true );
569 // detect and fix any filename collision - get unique filename
570 $newfiles = resolve_filename_collisions( $destination, array($file) );
571 $newfile = $newfiles[0];
573 // convert and save file contents
574 if (!$content = base64_decode( $base64 )) {
577 $newfullpath = "$destination/$newfile";
578 if (!$fh = fopen( $newfullpath, 'w' )) {
581 if (!fwrite( $fh, $content )) {
586 // return the (possibly) new filename
587 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
597 * Provide export functionality for plugin questiontypes
599 * @param name questiontype name
600 * @param question object data to export
601 * @param extra mixed any addition format specific data needed
602 * @return string the data to append to export or false if error (or unhandled)
604 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
607 // work out the name of format in use
608 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
609 $methodname = "export_to_$formatname";
611 if (array_key_exists( $name, $QTYPES )) {
612 $qtype = $QTYPES[ $name ];
613 if (method_exists( $qtype, $methodname )) {
614 if ($data = $qtype->$methodname( $question, $this, $extra )) {
623 * Return the files extension appropriate for this type
624 * override if you don't want .txt
625 * @return string file extension
627 function export_file_extension() {
632 * Do any pre-processing that may be required
633 * @param boolean success
635 function exportpreprocess() {
640 * Enable any processing to be done on the content
641 * just prior to the file being saved
642 * default is to do nothing
643 * @param string output text
644 * @param string processed output text
646 function presave_process( $content ) {
652 * For most types this should not need to be overrided
653 * @return boolean success
655 function exportprocess() {
658 // create a directory for the exports (if not already existing)
659 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
660 error( get_string('cannotcreatepath','quiz',$export_dir) );
662 $path = $CFG->dataroot
.'/'.$this->question_get_export_dir();
664 // get the questions (from database) in this category
665 // only get q's with no parents (no cloze subquestions specifically)
666 if ($this->category
){
667 $questions = get_questions_category( $this->category
, true );
669 $questions = $this->questions
;
672 notify( get_string('exportingquestions','quiz') );
675 // results are first written into string (and then to a file)
676 // so create/initialize the string here
679 // track which category questions are in
680 // if it changes we will record the category change in the output
681 // file if selected. 0 means that it will get printed before the 1st question
684 // iterate through questions
685 foreach($questions as $question) {
687 // do not export hidden questions
688 if (!empty($question->hidden
)) {
692 // do not export random questions
693 if ($question->qtype
==RANDOM
) {
697 // check if we need to record category change
698 if ($this->cattofile
) {
699 if ($question->category
!= $trackcategory) {
700 $trackcategory = $question->category
;
701 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile
);
703 // create 'dummy' question for category export
704 $dummyquestion = new object;
705 $dummyquestion->qtype
= 'category';
706 $dummyquestion->category
= $categoryname;
707 $dummyquestion->name
= 'Switch category to ' . $categoryname;
708 $dummyquestion->id
= 0;
709 $dummyquestion->questiontextformat
= '';
710 $expout .= $this->writequestion($dummyquestion) . "\n";
714 // export the question displaying message
716 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
717 if (question_has_capability_on($question, 'view', $question->category
)){
718 $expout .= $this->writequestion( $question ) . "\n";
722 // continue path for following error checks
723 $course = $this->course
;
724 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
726 // did we actually process anything
728 print_error( 'noquestions','quiz',$continuepath );
731 // final pre-process on exported data
732 $expout = $this->presave_process( $expout );
735 $filepath = $path."/".$this->filename
. $this->export_file_extension();
736 if (!$fh=fopen($filepath,"w")) {
737 print_error( 'cannotopen','quiz',$continuepath,$filepath );
739 if (!fwrite($fh, $expout, strlen($expout) )) {
740 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
747 * get the category as a path (e.g., tom/dick/harry)
748 * @param int id the id of the most nested catgory
749 * @return string the path
751 function get_category_path($id, $includecontext = true) {
753 if (!$category = get_record('question_categories','id',$id)) {
754 error('Error getting category record from db - ' . $id);
756 $contextstring = $this->translator
->context_to_string($category->contextid
);
758 $pathsections = array();
760 $pathsections[] = $category->name
;
761 $id = $category->parent
;
762 } while ($category = get_record('question_categories', 'id', $id));
764 if ($includecontext){
765 $pathsections[] = '$' . $contextstring . '$';
768 $path = $this->assemble_category_path(array_reverse($pathsections));
774 * Convert a list of category names, possibly preceeded by one of the
775 * context tokens like $course$, into a string representation of the
778 * Names are separated by / delimiters. And /s in the name are replaced by //.
780 * To reverse the process and split the paths into names, use
781 * {@link split_category_path()}.
783 * @param array $names
786 function assemble_category_path($names) {
787 $escapednames = array();
788 foreach ($names as $name) {
789 $escapedname = str_replace('/', '//', $name);
790 if (substr($escapedname, 0, 1) == '/') {
791 $escapedname = ' ' . $escapedname;
793 if (substr($escapedname, -1) == '/') {
794 $escapedname = $escapedname . ' ';
796 $escapednames[] = $escapedname;
798 return implode('/', $escapednames);
802 * Convert a string, as returned by {@link assemble_category_path()},
803 * back into an array of category names.
805 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
806 * which matches the cleaning in question/category_form.php. Not that this
807 * addslashes the names, ready for insertion into the database.
809 * @param string $path
810 * @return array of category names.
812 function split_category_path($path) {
813 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
815 foreach ($rawnames as $rawname) {
816 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG
);
822 * Do an post-processing that may be required
823 * @return boolean success
825 function exportpostprocess() {
830 * convert a single question object into text output in the given
832 * This must be overriden
833 * @param object question question object
834 * @return mixed question export text or null if not implemented
836 function writequestion($question) {
837 // if not overidden, then this is an error.
838 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
839 echo "<p>$formatnotimplemented</p>";
844 * get directory into which export is going
845 * @return string file path
847 function question_get_export_dir() {
849 if ($this->canaccessbackupdata
) {
850 $dirname = get_string("exportfilename","quiz");
851 $path = $this->course
->id
.'/backupdata/'.$dirname; // backupdata is protected directory
853 $path = 'temp/questionexport/' . $USER->id
;
859 * where question specifies a moodle (text) format this
860 * performs the conversion.
862 function format_question_text($question) {
863 $formatoptions = new stdClass
;
864 $formatoptions->noclean
= true;
865 $formatoptions->para
= false;
866 if (empty($question->questiontextformat
)) {
867 $format = FORMAT_MOODLE
;
869 $format = $question->questiontextformat
;
871 return format_text(stripslashes($question->questiontext
), $format, $formatoptions);