A couple of changes to Pierre's calculated question import/export
[moodle-linuxchix.git] / question / format.php
blob5619926b40b18ad1a732ff188f00ebb00556f161
1 <?php // $Id$
2 /**
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
10 *//** */
12 /**
13 * Base class for question import and export formats.
15 * Doesn't do everything on it's own -- it needs to be extended.
17 * @package questionbank
18 * @subpackage importexport
20 class qformat_default {
22 var $displayerrors = true;
23 var $category = NULL;
24 var $course = NULL;
25 var $filename = '';
26 var $matchgrades = 'error';
27 var $catfromfile = 0;
28 var $cattofile = 0;
29 var $questionids = array();
30 var $importerrors = 0;
31 var $stoponerror = true;
33 // functions to indicate import/export functionality
34 // override to return true if implemented
36 function provide_import() {
37 return false;
40 function provide_export() {
41 return false;
44 // Accessor methods
46 /**
47 * set the category
48 * @param object category the category object
50 function setCategory( $category ) {
51 $this->category = $category;
54 /**
55 * set the course class variable
56 * @param course object Moodle course variable
58 function setCourse( $course ) {
59 $this->course = $course;
62 /**
63 * set the filename
64 * @param string filename name of file to import/export
66 function setFilename( $filename ) {
67 $this->filename = $filename;
70 /**
71 * set matchgrades
72 * @param string matchgrades error or nearest for grades
74 function setMatchgrades( $matchgrades ) {
75 $this->matchgrades = $matchgrades;
78 /**
79 * set catfromfile
80 * @param bool catfromfile allow categories embedded in import file
82 function setCatfromfile( $catfromfile ) {
83 $this->catfromfile = $catfromfile;
86 /**
87 * set cattofile
88 * @param bool cattofile exports categories within export file
90 function setCattofile( $cattofile ) {
91 $this->cattofile = $cattofile;
94 /**
95 * set stoponerror
96 * @param bool stoponerror stops database write if any errors reported
98 function setStoponerror( $stoponerror ) {
99 $this->stoponerror = $stoponerror;
102 /***********************
103 * IMPORTING FUNCTIONS
104 ***********************/
107 * Handle parsing error
109 function error( $message, $text='', $questionname='' ) {
110 echo "<div class=\"importerror\">\n";
111 echo "<strong>Error in question $questionname</strong>";
112 if (!empty($text)) {
113 $text = s($text);
114 echo "<blockquote>$text</blockquote>\n";
116 echo "<strong>$message</strong>\n";
117 echo "</div>";
119 $this->importerrors++;
123 * Perform any required pre-processing
124 * @return boolean success
126 function importpreprocess() {
127 return true;
131 * Process the file
132 * This method should not normally be overidden
133 * @return boolean success
135 function importprocess() {
137 // STAGE 1: Parse the file
138 notify( get_string('parsingquestions','quiz') );
140 if (! $lines = $this->readdata($this->filename)) {
141 notify( get_string('cannotread','quiz') );
142 return false;
145 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
146 notify( get_string('noquestionsinfile','quiz') );
147 return false;
150 // STAGE 2: Write data to database
151 notify( get_string('importingquestions','quiz',count($questions)) );
153 // check for errors before we continue
154 if ($this->stoponerror and ($this->importerrors>0)) {
155 return false;
158 // get list of valid answer grades
159 $grades = get_grade_options();
160 $gradeoptionsfull = $grades->gradeoptionsfull;
162 $count = 0;
164 foreach ($questions as $question) { // Process and store each question
166 // check for category modifiers
167 if ($question->qtype=='category') {
168 if ($this->catfromfile) {
169 // find/create category object
170 $catpath = $question->category;
171 $newcategory = create_category_path( $catpath, '/', $this->course->id );
172 if (!empty($newcategory)) {
173 $this->category = $newcategory;
176 continue;
179 $count++;
181 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
183 // check for answer grades validity (must match fixed list of grades)
184 if (!empty($question->fraction) and (is_array($question->fraction))) {
185 $fractions = $question->fraction;
186 $answersvalid = true; // in case they are!
187 foreach ($fractions as $key => $fraction) {
188 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
189 if ($newfraction===false) {
190 $answersvalid = false;
192 else {
193 $fractions[$key] = $newfraction;
196 if (!$answersvalid) {
197 notify( get_string('matcherror','quiz') );
198 continue;
200 else {
201 $question->fraction = $fractions;
205 $question->category = $this->category->id;
206 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
208 if (!$question->id = insert_record("question", $question)) {
209 error( get_string('cannotinsert','quiz') );
212 $this->questionids[] = $question->id;
214 // Now to save all the answers and type-specific options
216 global $QTYPES;
217 $result = $QTYPES[$question->qtype]
218 ->save_question_options($question);
220 if (!empty($result->error)) {
221 notify($result->error);
222 return false;
225 if (!empty($result->notice)) {
226 notify($result->notice);
227 return true;
230 // Give the question a unique version stamp determined by question_hash()
231 set_field('question', 'version', question_hash($question), 'id', $question->id);
233 return true;
237 * Return complete file within an array, one item per line
238 * @param string filename name of file
239 * @return mixed contents array or false on failure
241 function readdata($filename) {
242 if (is_readable($filename)) {
243 $filearray = file($filename);
245 /// Check for Macintosh OS line returns (ie file on one line), and fix
246 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
247 return explode("\r", $filearray[0]);
248 } else {
249 return $filearray;
252 return false;
256 * Parses an array of lines into an array of questions,
257 * where each item is a question object as defined by
258 * readquestion(). Questions are defined as anything
259 * between blank lines.
261 * If your format does not use blank lines as a delimiter
262 * then you will need to override this method. Even then
263 * try to use readquestion for each question
264 * @param array lines array of lines from readdata
265 * @return array array of question objects
267 function readquestions($lines) {
269 $questions = array();
270 $currentquestion = array();
272 foreach ($lines as $line) {
273 $line = trim($line);
274 if (empty($line)) {
275 if (!empty($currentquestion)) {
276 if ($question = $this->readquestion($currentquestion)) {
277 $questions[] = $question;
279 $currentquestion = array();
281 } else {
282 $currentquestion[] = $line;
286 if (!empty($currentquestion)) { // There may be a final question
287 if ($question = $this->readquestion($currentquestion)) {
288 $questions[] = $question;
292 return $questions;
297 * return an "empty" question
298 * Somewhere to specify question parameters that are not handled
299 * by import but are required db fields.
300 * This should not be overridden.
301 * @return object default question
303 function defaultquestion() {
304 global $CFG;
306 $question = new stdClass();
307 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
308 $question->defaultgrade = 1;
309 $question->image = "";
310 $question->usecase = 0;
311 $question->multiplier = array();
312 $question->generalfeedback = '';
313 $question->correctfeedback = '';
314 $question->partiallycorrectfeedback = '';
315 $question->incorrectfeedback = '';
317 // this option in case the questiontypes class wants
318 // to know where the data came from
319 $question->export_process = true;
321 return $question;
325 * Given the data known to define a question in
326 * this format, this function converts it into a question
327 * object suitable for processing and insertion into Moodle.
329 * If your format does not use blank lines to delimit questions
330 * (e.g. an XML format) you must override 'readquestions' too
331 * @param $lines mixed data that represents question
332 * @return object question object
334 function readquestion($lines) {
336 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
337 echo "<p>$formatnotimplemented</p>";
339 return NULL;
343 * Override if any post-processing is required
344 * @return boolean success
346 function importpostprocess() {
347 return true;
351 * Import an image file encoded in base64 format
352 * @param string path path (in course data) to store picture
353 * @param string base64 encoded picture
354 * @return string filename (nb. collisions are handled)
356 function importimagefile( $path, $base64 ) {
357 global $CFG;
359 // all this to get the destination directory
360 // and filename!
361 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
362 $path_parts = pathinfo( $fullpath );
363 $destination = $path_parts['dirname'];
364 $file = clean_filename( $path_parts['basename'] );
366 // detect and fix any filename collision - get unique filename
367 $newfiles = resolve_filename_collisions( $destination, array($file) );
368 $newfile = $newfiles[0];
370 // convert and save file contents
371 if (!$content = base64_decode( $base64 )) {
372 return false;
374 $newfullpath = "$destination/$newfile";
375 if (!$fh = fopen( $newfullpath, 'w' )) {
376 return false;
378 if (!fwrite( $fh, $content )) {
379 return false;
381 fclose( $fh );
383 // return the (possibly) new filename
384 return $newfile;
387 /*******************
388 * EXPORT FUNCTIONS
389 *******************/
392 * Return the files extension appropriate for this type
393 * override if you don't want .txt
394 * @return string file extension
396 function export_file_extension() {
397 return ".txt";
401 * Do any pre-processing that may be required
402 * @param boolean success
404 function exportpreprocess() {
405 return true;
409 * Enable any processing to be done on the content
410 * just prior to the file being saved
411 * default is to do nothing
412 * @param string output text
413 * @param string processed output text
415 function presave_process( $content ) {
416 return $content;
420 * Do the export
421 * For most types this should not need to be overrided
422 * @return boolean success
424 function exportprocess() {
425 global $CFG;
427 // create a directory for the exports (if not already existing)
428 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
429 error( get_string('cannotcreatepath','quiz',$export_dir) );
431 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
433 // get the questions (from database) in this category
434 // only get q's with no parents (no cloze subquestions specifically)
435 $questions = get_questions_category( $this->category, true );
437 notify( get_string('exportingquestions','quiz') );
438 if (!count($questions)) {
439 notify( get_string('noquestions','quiz') );
440 return false;
442 $count = 0;
444 // results are first written into string (and then to a file)
445 // so create/initialize the string here
446 $expout = "";
448 // track which category questions are in
449 // if it changes we will record the category change in the output
450 // file if selected. 0 means that it will get printed before the 1st question
451 $trackcategory = 0;
453 // iterate through questions
454 foreach($questions as $question) {
456 // do not export hidden questions
457 if (!empty($question->hidden)) {
458 continue;
461 // do not export random questions
462 if ($question->qtype==RANDOM) {
463 continue;
466 // check if we need to record category change
467 if ($this->cattofile) {
468 if ($question->category != $trackcategory) {
469 $trackcategory = $question->category;
470 $categoryname = get_category_path( $trackcategory );
472 // create 'dummy' question for category export
473 $dummyquestion = new object;
474 $dummyquestion->qtype = 'category';
475 $dummyquestion->category = $categoryname;
476 $dummyquestion->name = "switch category to $categoryname";
477 $dummyquestion->id = 0;
478 $dummyquestion->questiontextformat = '';
479 $expout .= $this->writequestion( $dummyquestion ) . "\n";
483 // export the question displaying message
484 $count++;
485 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
486 $expout .= $this->writequestion( $question ) . "\n";
489 // final pre-process on exported data
490 $expout = $this->presave_process( $expout );
492 // write file
493 $filepath = $path."/".$this->filename . $this->export_file_extension();
494 if (!$fh=fopen($filepath,"w")) {
495 error( get_string('cannotopen','quiz',$filepath) );
497 if (!fwrite($fh, $expout, strlen($expout) )) {
498 error( get_string('cannotwrite','quiz',$filepath) );
500 fclose($fh);
501 return true;
505 * Do an post-processing that may be required
506 * @return boolean success
508 function exportpostprocess() {
509 return true;
513 * convert a single question object into text output in the given
514 * format.
515 * This must be overriden
516 * @param object question question object
517 * @return mixed question export text or null if not implemented
519 function writequestion($question) {
520 // if not overidden, then this is an error.
521 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
522 echo "<p>$formatnotimplemented</p>";
524 return NULL;
528 * get directory into which export is going
529 * @return string file path
531 function question_get_export_dir() {
532 $dirname = get_string("exportfilename","quiz");
533 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
534 return $path;
538 * where question specifies a moodle (text) format this
539 * performs the conversion.
541 function format_question_text($question) {
542 $formatoptions = new stdClass;
543 $formatoptions->noclean = true;
544 $formatoptions->para = false;
545 if (empty($question->questiontextformat)) {
546 $format = FORMAT_MOODLE;
547 } else {
548 $format = $question->questiontextformat;
550 return format_text(stripslashes($question->questiontext), $format, $formatoptions);