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 // check if path exists
369 check_dir_exists($destination, true, true );
371 // detect and fix any filename collision - get unique filename
372 $newfiles = resolve_filename_collisions( $destination, array($file) );
373 $newfile = $newfiles[0];
375 // convert and save file contents
376 if (!$content = base64_decode( $base64 )) {
379 $newfullpath = "$destination/$newfile";
380 if (!$fh = fopen( $newfullpath, 'w' )) {
383 if (!fwrite( $fh, $content )) {
388 // return the (possibly) new filename
389 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
398 * Return the files extension appropriate for this type
399 * override if you don't want .txt
400 * @return string file extension
402 function export_file_extension() {
407 * Do any pre-processing that may be required
408 * @param boolean success
410 function exportpreprocess() {
415 * Enable any processing to be done on the content
416 * just prior to the file being saved
417 * default is to do nothing
418 * @param string output text
419 * @param string processed output text
421 function presave_process( $content ) {
427 * For most types this should not need to be overrided
428 * @return boolean success
430 function exportprocess() {
433 // create a directory for the exports (if not already existing)
434 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
435 error( get_string('cannotcreatepath','quiz',$export_dir) );
437 $path = $CFG->dataroot
.'/'.$this->question_get_export_dir();
439 // get the questions (from database) in this category
440 // only get q's with no parents (no cloze subquestions specifically)
441 $questions = get_questions_category( $this->category
, true );
443 notify( get_string('exportingquestions','quiz') );
444 if (!count($questions)) {
445 notify( get_string('noquestions','quiz') );
450 // results are first written into string (and then to a file)
451 // so create/initialize the string here
454 // track which category questions are in
455 // if it changes we will record the category change in the output
456 // file if selected. 0 means that it will get printed before the 1st question
459 // iterate through questions
460 foreach($questions as $question) {
462 // do not export hidden questions
463 if (!empty($question->hidden
)) {
467 // do not export random questions
468 if ($question->qtype
==RANDOM
) {
472 // check if we need to record category change
473 if ($this->cattofile
) {
474 if ($question->category
!= $trackcategory) {
475 $trackcategory = $question->category
;
476 $categoryname = get_category_path( $trackcategory );
478 // create 'dummy' question for category export
479 $dummyquestion = new object;
480 $dummyquestion->qtype
= 'category';
481 $dummyquestion->category
= $categoryname;
482 $dummyquestion->name
= "switch category to $categoryname";
483 $dummyquestion->id
= 0;
484 $dummyquestion->questiontextformat
= '';
485 $expout .= $this->writequestion( $dummyquestion ) . "\n";
489 // export the question displaying message
491 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
492 $expout .= $this->writequestion( $question ) . "\n";
495 // final pre-process on exported data
496 $expout = $this->presave_process( $expout );
499 $filepath = $path."/".$this->filename
. $this->export_file_extension();
500 if (!$fh=fopen($filepath,"w")) {
501 error( get_string('cannotopen','quiz',$filepath) );
503 if (!fwrite($fh, $expout, strlen($expout) )) {
504 error( get_string('cannotwrite','quiz',$filepath) );
511 * Do an post-processing that may be required
512 * @return boolean success
514 function exportpostprocess() {
519 * convert a single question object into text output in the given
521 * This must be overriden
522 * @param object question question object
523 * @return mixed question export text or null if not implemented
525 function writequestion($question) {
526 // if not overidden, then this is an error.
527 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
528 echo "<p>$formatnotimplemented</p>";
534 * get directory into which export is going
535 * @return string file path
537 function question_get_export_dir() {
538 $dirname = get_string("exportfilename","quiz");
539 $path = $this->course
->id
.'/backupdata/'.$dirname; // backupdata is protected directory
544 * where question specifies a moodle (text) format this
545 * performs the conversion.
547 function format_question_text($question) {
548 $formatoptions = new stdClass
;
549 $formatoptions->noclean
= true;
550 $formatoptions->para
= false;
551 if (empty($question->questiontextformat
)) {
552 $format = FORMAT_MOODLE
;
554 $format = $question->questiontextformat
;
556 return format_text(stripslashes($question->questiontext
), $format, $formatoptions);