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;
17 var $matchgrades = 'error';
20 var $questionids = array();
21 var $importerrors = 0;
22 var $stoponerror = true;
24 // functions to indicate import/export functionality
25 // override to return true if implemented
27 function provide_import() {
31 function provide_export() {
39 * @param object category the category object
41 function setCategory( $category ) {
42 $this->category
= $category;
46 * set the course class variable
47 * @param course object Moodle course variable
49 function setCourse( $course ) {
50 $this->course
= $course;
55 * @param string filename name of file to import/export
57 function setFilename( $filename ) {
58 $this->filename
= $filename;
63 * @param string matchgrades error or nearest for grades
65 function setMatchgrades( $matchgrades ) {
66 $this->matchgrades
= $matchgrades;
71 * @param bool catfromfile allow categories embedded in import file
73 function setCatfromfile( $catfromfile ) {
74 $this->catfromfile
= $catfromfile;
79 * @param bool cattofile exports categories within export file
81 function setCattofile( $cattofile ) {
82 $this->cattofile
= $cattofile;
87 * @param bool stoponerror stops database write if any errors reported
89 function setStoponerror( $stoponerror ) {
90 $this->stoponerror
= $stoponerror;
93 /***********************
95 ***********************/
98 * Handle parsing error
100 function error( $message, $text='', $questionname='' ) {
101 $importerrorquestion = get_string('importerrorquestion','quiz');
103 echo "<div class=\"importerror\">\n";
104 echo "<strong>$importerrorquestion $questionname</strong>";
107 echo "<blockquote>$text</blockquote>\n";
109 echo "<strong>$message</strong>\n";
112 $this->importerrors++
;
116 * Import for questiontype plugins
118 * @param data mixed The segment of data containing the question
119 * @param question object processed (so far) by standard import code if appropriate
120 * @param extra mixed any additional format specific data that may be passed by the format
121 * @return object question object suitable for save_options() or false if cannot handle
123 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
126 // work out what format we are using
127 $formatname = substr( get_class( $this ), strlen('qformat_'));
128 $methodname = "import_from_$formatname";
130 // loop through installed questiontypes checking for
131 // function to handle this question
132 foreach ($QTYPES as $qtype) {
133 if (method_exists( $qtype, $methodname)) {
134 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
143 * Perform any required pre-processing
144 * @return boolean success
146 function importpreprocess() {
152 * This method should not normally be overidden
153 * @return boolean success
155 function importprocess() {
157 // reset the timer in case file upload was slow
160 // STAGE 1: Parse the file
161 notify( get_string('parsingquestions','quiz') );
163 if (! $lines = $this->readdata($this->filename
)) {
164 notify( get_string('cannotread','quiz') );
168 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
169 notify( get_string('noquestionsinfile','quiz') );
173 // STAGE 2: Write data to database
174 notify( get_string('importingquestions','quiz',count($questions)) );
176 // check for errors before we continue
177 if ($this->stoponerror
and ($this->importerrors
>0)) {
181 // get list of valid answer grades
182 $grades = get_grade_options();
183 $gradeoptionsfull = $grades->gradeoptionsfull
;
187 foreach ($questions as $question) { // Process and store each question
189 // reset the php timeout
192 // check for category modifiers
193 if ($question->qtype
=='category') {
194 if ($this->catfromfile
) {
195 // find/create category object
196 $catpath = $question->category
;
197 $newcategory = create_category_path( $catpath, '/', $this->course
->id
);
198 if (!empty($newcategory)) {
199 $this->category
= $newcategory;
207 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
209 // check for answer grades validity (must match fixed list of grades)
210 if (!empty($question->fraction
) and (is_array($question->fraction
))) {
211 $fractions = $question->fraction
;
212 $answersvalid = true; // in case they are!
213 foreach ($fractions as $key => $fraction) {
214 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades
);
215 if ($newfraction===false) {
216 $answersvalid = false;
219 $fractions[$key] = $newfraction;
222 if (!$answersvalid) {
223 notify(get_string('matcherror', 'quiz'));
227 $question->fraction
= $fractions;
231 $question->category
= $this->category
->id
;
232 $question->stamp
= make_unique_id_code(); // Set the unique code (not to be changed)
234 if (!$question->id
= insert_record("question", $question)) {
235 error( get_string('cannotinsert','quiz') );
238 $this->questionids
[] = $question->id
;
240 // Now to save all the answers and type-specific options
243 $result = $QTYPES[$question->qtype
]
244 ->save_question_options($question);
246 if (!empty($result->error
)) {
247 notify($result->error
);
251 if (!empty($result->notice
)) {
252 notify($result->notice
);
256 // Give the question a unique version stamp determined by question_hash()
257 set_field('question', 'version', question_hash($question), 'id', $question->id
);
263 * Return complete file within an array, one item per line
264 * @param string filename name of file
265 * @return mixed contents array or false on failure
267 function readdata($filename) {
268 if (is_readable($filename)) {
269 $filearray = file($filename);
271 /// Check for Macintosh OS line returns (ie file on one line), and fix
272 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
273 return explode("\r", $filearray[0]);
282 * Parses an array of lines into an array of questions,
283 * where each item is a question object as defined by
284 * readquestion(). Questions are defined as anything
285 * between blank lines.
287 * If your format does not use blank lines as a delimiter
288 * then you will need to override this method. Even then
289 * try to use readquestion for each question
290 * @param array lines array of lines from readdata
291 * @return array array of question objects
293 function readquestions($lines) {
295 $questions = array();
296 $currentquestion = array();
298 foreach ($lines as $line) {
301 if (!empty($currentquestion)) {
302 if ($question = $this->readquestion($currentquestion)) {
303 $questions[] = $question;
305 $currentquestion = array();
308 $currentquestion[] = $line;
312 if (!empty($currentquestion)) { // There may be a final question
313 if ($question = $this->readquestion($currentquestion)) {
314 $questions[] = $question;
323 * return an "empty" question
324 * Somewhere to specify question parameters that are not handled
325 * by import but are required db fields.
326 * This should not be overridden.
327 * @return object default question
329 function defaultquestion() {
332 $question = new stdClass();
333 $question->shuffleanswers
= $CFG->quiz_shuffleanswers
;
334 $question->defaultgrade
= 1;
335 $question->image
= "";
336 $question->usecase
= 0;
337 $question->multiplier
= array();
338 $question->generalfeedback
= '';
339 $question->correctfeedback
= '';
340 $question->partiallycorrectfeedback
= '';
341 $question->incorrectfeedback
= '';
342 $question->answernumbering
= 'abc';
343 $question->penalty
= 0.1;
345 // this option in case the questiontypes class wants
346 // to know where the data came from
347 $question->export_process
= true;
348 $question->import_process
= true;
354 * Given the data known to define a question in
355 * this format, this function converts it into a question
356 * object suitable for processing and insertion into Moodle.
358 * If your format does not use blank lines to delimit questions
359 * (e.g. an XML format) you must override 'readquestions' too
360 * @param $lines mixed data that represents question
361 * @return object question object
363 function readquestion($lines) {
365 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
366 echo "<p>$formatnotimplemented</p>";
372 * Override if any post-processing is required
373 * @return boolean success
375 function importpostprocess() {
380 * Import an image file encoded in base64 format
381 * @param string path path (in course data) to store picture
382 * @param string base64 encoded picture
383 * @return string filename (nb. collisions are handled)
385 function importimagefile( $path, $base64 ) {
388 // all this to get the destination directory
390 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
391 $path_parts = pathinfo( $fullpath );
392 $destination = $path_parts['dirname'];
393 $file = clean_filename( $path_parts['basename'] );
395 // check if path exists
396 check_dir_exists($destination, true, true );
398 // detect and fix any filename collision - get unique filename
399 $newfiles = resolve_filename_collisions( $destination, array($file) );
400 $newfile = $newfiles[0];
402 // convert and save file contents
403 if (!$content = base64_decode( $base64 )) {
406 $newfullpath = "$destination/$newfile";
407 if (!$fh = fopen( $newfullpath, 'w' )) {
410 if (!fwrite( $fh, $content )) {
415 // return the (possibly) new filename
416 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
425 * Provide export functionality for plugin questiontypes
427 * @param name questiontype name
428 * @param question object data to export
429 * @param extra mixed any addition format specific data needed
430 * @return string the data to append to export or false if error (or unhandled)
432 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
435 // work out the name of format in use
436 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
437 $methodname = "export_to_$formatname";
439 if (array_key_exists( $name, $QTYPES )) {
440 $qtype = $QTYPES[ $name ];
441 if (method_exists( $qtype, $methodname )) {
442 if ($data = $qtype->$methodname( $question, $this, $extra )) {
451 * Return the files extension appropriate for this type
452 * override if you don't want .txt
453 * @return string file extension
455 function export_file_extension() {
460 * Do any pre-processing that may be required
461 * @param boolean success
463 function exportpreprocess() {
468 * Enable any processing to be done on the content
469 * just prior to the file being saved
470 * default is to do nothing
471 * @param string output text
472 * @param string processed output text
474 function presave_process( $content ) {
480 * For most types this should not need to be overrided
481 * @return boolean success
483 function exportprocess() {
486 // create a directory for the exports (if not already existing)
487 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
488 error( get_string('cannotcreatepath','quiz',$export_dir) );
490 $path = $CFG->dataroot
.'/'.$this->question_get_export_dir();
492 // get the questions (from database) in this category
493 // only get q's with no parents (no cloze subquestions specifically)
494 $questions = get_questions_category( $this->category
, true );
496 notify( get_string('exportingquestions','quiz') );
497 if (!count($questions)) {
498 notify( get_string('noquestions','quiz') );
503 // results are first written into string (and then to a file)
504 // so create/initialize the string here
507 // track which category questions are in
508 // if it changes we will record the category change in the output
509 // file if selected. 0 means that it will get printed before the 1st question
512 // iterate through questions
513 foreach($questions as $question) {
515 // do not export hidden questions
516 if (!empty($question->hidden
)) {
520 // do not export random questions
521 if ($question->qtype
==RANDOM
) {
525 // check if we need to record category change
526 if ($this->cattofile
) {
527 if ($question->category
!= $trackcategory) {
528 $trackcategory = $question->category
;
529 $categoryname = get_category_path( $trackcategory );
531 // create 'dummy' question for category export
532 $dummyquestion = new object;
533 $dummyquestion->qtype
= 'category';
534 $dummyquestion->category
= $categoryname;
535 $dummyquestion->name
= "switch category to $categoryname";
536 $dummyquestion->id
= 0;
537 $dummyquestion->questiontextformat
= '';
538 $expout .= $this->writequestion( $dummyquestion ) . "\n";
542 // export the question displaying message
544 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
545 $expout .= $this->writequestion( $question ) . "\n";
548 // final pre-process on exported data
549 $expout = $this->presave_process( $expout );
552 $filepath = $path."/".$this->filename
. $this->export_file_extension();
553 if (!$fh=fopen($filepath,"w")) {
554 error( get_string('cannotopen','quiz',$filepath) );
556 if (!fwrite($fh, $expout, strlen($expout) )) {
557 error( get_string('cannotwrite','quiz',$filepath) );
564 * Do an post-processing that may be required
565 * @return boolean success
567 function exportpostprocess() {
572 * convert a single question object into text output in the given
574 * This must be overriden
575 * @param object question question object
576 * @return mixed question export text or null if not implemented
578 function writequestion($question) {
579 // if not overidden, then this is an error.
580 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
581 echo "<p>$formatnotimplemented</p>";
587 * get directory into which export is going
588 * @return string file path
590 function question_get_export_dir() {
591 $dirname = get_string("exportfilename","quiz");
592 $path = $this->course
->id
.'/backupdata/'.$dirname; // backupdata is protected directory
597 * where question specifies a moodle (text) format this
598 * performs the conversion.
600 function format_question_text($question) {
601 $formatoptions = new stdClass
;
602 $formatoptions->noclean
= true;
603 $formatoptions->para
= false;
604 if (empty($question->questiontextformat
)) {
605 $format = FORMAT_MOODLE
;
607 $format = $question->questiontextformat
;
609 return format_text(stripslashes($question->questiontext
), $format, $formatoptions);