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 * Perform any required pre-processing
117 * @return boolean success
119 function importpreprocess() {
125 * This method should not normally be overidden
126 * @return boolean success
128 function importprocess() {
130 // reset the timer in case file upload was slow
133 // STAGE 1: Parse the file
134 notify( get_string('parsingquestions','quiz') );
136 if (! $lines = $this->readdata($this->filename
)) {
137 notify( get_string('cannotread','quiz') );
141 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
142 notify( get_string('noquestionsinfile','quiz') );
146 // STAGE 2: Write data to database
147 notify( get_string('importingquestions','quiz',count($questions)) );
149 // check for errors before we continue
150 if ($this->stoponerror
and ($this->importerrors
>0)) {
154 // get list of valid answer grades
155 $grades = get_grade_options();
156 $gradeoptionsfull = $grades->gradeoptionsfull
;
160 foreach ($questions as $question) { // Process and store each question
162 // reset the php timeout
165 // check for category modifiers
166 if ($question->qtype
=='category') {
167 if ($this->catfromfile
) {
168 // find/create category object
169 $catpath = $question->category
;
170 $newcategory = create_category_path( $catpath, '/', $this->course
->id
);
171 if (!empty($newcategory)) {
172 $this->category
= $newcategory;
180 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
182 // check for answer grades validity (must match fixed list of grades)
183 if (!empty($question->fraction
) and (is_array($question->fraction
))) {
184 $fractions = $question->fraction
;
185 $answersvalid = true; // in case they are!
186 foreach ($fractions as $key => $fraction) {
187 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades
);
188 if ($newfraction===false) {
189 $answersvalid = false;
192 $fractions[$key] = $newfraction;
195 if (!$answersvalid) {
196 notify(get_string('matcherror', 'quiz'));
200 $question->fraction
= $fractions;
204 $question->category
= $this->category
->id
;
205 $question->stamp
= make_unique_id_code(); // Set the unique code (not to be changed)
207 if (!$question->id
= insert_record("question", $question)) {
208 error( get_string('cannotinsert','quiz') );
211 $this->questionids
[] = $question->id
;
213 // Now to save all the answers and type-specific options
216 $result = $QTYPES[$question->qtype
]
217 ->save_question_options($question);
219 if (!empty($result->error
)) {
220 notify($result->error
);
224 if (!empty($result->notice
)) {
225 notify($result->notice
);
229 // Give the question a unique version stamp determined by question_hash()
230 set_field('question', 'version', question_hash($question), 'id', $question->id
);
236 * Return complete file within an array, one item per line
237 * @param string filename name of file
238 * @return mixed contents array or false on failure
240 function readdata($filename) {
241 if (is_readable($filename)) {
242 $filearray = file($filename);
244 /// Check for Macintosh OS line returns (ie file on one line), and fix
245 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
246 return explode("\r", $filearray[0]);
255 * Parses an array of lines into an array of questions,
256 * where each item is a question object as defined by
257 * readquestion(). Questions are defined as anything
258 * between blank lines.
260 * If your format does not use blank lines as a delimiter
261 * then you will need to override this method. Even then
262 * try to use readquestion for each question
263 * @param array lines array of lines from readdata
264 * @return array array of question objects
266 function readquestions($lines) {
268 $questions = array();
269 $currentquestion = array();
271 foreach ($lines as $line) {
274 if (!empty($currentquestion)) {
275 if ($question = $this->readquestion($currentquestion)) {
276 $questions[] = $question;
278 $currentquestion = array();
281 $currentquestion[] = $line;
285 if (!empty($currentquestion)) { // There may be a final question
286 if ($question = $this->readquestion($currentquestion)) {
287 $questions[] = $question;
296 * return an "empty" question
297 * Somewhere to specify question parameters that are not handled
298 * by import but are required db fields.
299 * This should not be overridden.
300 * @return object default question
302 function defaultquestion() {
305 $question = new stdClass();
306 $question->shuffleanswers
= $CFG->quiz_shuffleanswers
;
307 $question->defaultgrade
= 1;
308 $question->image
= "";
309 $question->usecase
= 0;
310 $question->multiplier
= array();
311 $question->generalfeedback
= '';
312 $question->correctfeedback
= '';
313 $question->partiallycorrectfeedback
= '';
314 $question->incorrectfeedback
= '';
315 $question->answernumbering
= 'abc';
316 $question->penalty
= 0.1;
318 // this option in case the questiontypes class wants
319 // to know where the data came from
320 $question->export_process
= true;
321 $question->import_process
= true;
327 * Given the data known to define a question in
328 * this format, this function converts it into a question
329 * object suitable for processing and insertion into Moodle.
331 * If your format does not use blank lines to delimit questions
332 * (e.g. an XML format) you must override 'readquestions' too
333 * @param $lines mixed data that represents question
334 * @return object question object
336 function readquestion($lines) {
338 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
339 echo "<p>$formatnotimplemented</p>";
345 * Override if any post-processing is required
346 * @return boolean success
348 function importpostprocess() {
353 * Import an image file encoded in base64 format
354 * @param string path path (in course data) to store picture
355 * @param string base64 encoded picture
356 * @return string filename (nb. collisions are handled)
358 function importimagefile( $path, $base64 ) {
361 // all this to get the destination directory
363 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
364 $path_parts = pathinfo( $fullpath );
365 $destination = $path_parts['dirname'];
366 $file = clean_filename( $path_parts['basename'] );
368 // detect and fix any filename collision - get unique filename
369 $newfiles = resolve_filename_collisions( $destination, array($file) );
370 $newfile = $newfiles[0];
372 // convert and save file contents
373 if (!$content = base64_decode( $base64 )) {
376 $newfullpath = "$destination/$newfile";
377 if (!$fh = fopen( $newfullpath, 'w' )) {
380 if (!fwrite( $fh, $content )) {
385 // return the (possibly) new filename
394 * Return the files extension appropriate for this type
395 * override if you don't want .txt
396 * @return string file extension
398 function export_file_extension() {
403 * Do any pre-processing that may be required
404 * @param boolean success
406 function exportpreprocess() {
411 * Enable any processing to be done on the content
412 * just prior to the file being saved
413 * default is to do nothing
414 * @param string output text
415 * @param string processed output text
417 function presave_process( $content ) {
423 * For most types this should not need to be overrided
424 * @return boolean success
426 function exportprocess() {
429 // create a directory for the exports (if not already existing)
430 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
431 error( get_string('cannotcreatepath','quiz',$export_dir) );
433 $path = $CFG->dataroot
.'/'.$this->question_get_export_dir();
435 // get the questions (from database) in this category
436 // only get q's with no parents (no cloze subquestions specifically)
437 $questions = get_questions_category( $this->category
, true );
439 notify( get_string('exportingquestions','quiz') );
440 if (!count($questions)) {
441 notify( get_string('noquestions','quiz') );
446 // results are first written into string (and then to a file)
447 // so create/initialize the string here
450 // track which category questions are in
451 // if it changes we will record the category change in the output
452 // file if selected. 0 means that it will get printed before the 1st question
455 // iterate through questions
456 foreach($questions as $question) {
458 // do not export hidden questions
459 if (!empty($question->hidden
)) {
463 // do not export random questions
464 if ($question->qtype
==RANDOM
) {
468 // check if we need to record category change
469 if ($this->cattofile
) {
470 if ($question->category
!= $trackcategory) {
471 $trackcategory = $question->category
;
472 $categoryname = get_category_path( $trackcategory );
474 // create 'dummy' question for category export
475 $dummyquestion = new object;
476 $dummyquestion->qtype
= 'category';
477 $dummyquestion->category
= $categoryname;
478 $dummyquestion->name
= "switch category to $categoryname";
479 $dummyquestion->id
= 0;
480 $dummyquestion->questiontextformat
= '';
481 $expout .= $this->writequestion( $dummyquestion ) . "\n";
485 // export the question displaying message
487 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
488 $expout .= $this->writequestion( $question ) . "\n";
491 // final pre-process on exported data
492 $expout = $this->presave_process( $expout );
495 $filepath = $path."/".$this->filename
. $this->export_file_extension();
496 if (!$fh=fopen($filepath,"w")) {
497 error( get_string('cannotopen','quiz',$filepath) );
499 if (!fwrite($fh, $expout, strlen($expout) )) {
500 error( get_string('cannotwrite','quiz',$filepath) );
507 * Do an post-processing that may be required
508 * @return boolean success
510 function exportpostprocess() {
515 * convert a single question object into text output in the given
517 * This must be overriden
518 * @param object question question object
519 * @return mixed question export text or null if not implemented
521 function writequestion($question) {
522 // if not overidden, then this is an error.
523 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
524 echo "<p>$formatnotimplemented</p>";
530 * get directory into which export is going
531 * @return string file path
533 function question_get_export_dir() {
534 $dirname = get_string("exportfilename","quiz");
535 $path = $this->course
->id
.'/backupdata/'.$dirname; // backupdata is protected directory
540 * where question specifies a moodle (text) format this
541 * performs the conversion.
543 function format_question_text($question) {
544 $formatoptions = new stdClass
;
545 $formatoptions->noclean
= true;
546 $formatoptions->para
= false;
547 if (empty($question->questiontextformat
)) {
548 $format = FORMAT_MOODLE
;
550 $format = $question->questiontextformat
;
552 return format_text(stripslashes($question->questiontext
), $format, $formatoptions);