adding some strings
[moodle-linuxchix.git] / question / format.php
blob95f0a74851d33835fba14ee659c8817d73924a25
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
11 class qformat_default {
13 var $displayerrors = true;
14 var $category = NULL;
15 var $course = NULL;
16 var $filename = '';
17 var $matchgrades = 'error';
18 var $catfromfile = 0;
19 var $cattofile = 0;
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() {
28 return false;
31 function provide_export() {
32 return false;
35 // Accessor methods
37 /**
38 * set the category
39 * @param object category the category object
41 function setCategory( $category ) {
42 $this->category = $category;
45 /**
46 * set the course class variable
47 * @param course object Moodle course variable
49 function setCourse( $course ) {
50 $this->course = $course;
53 /**
54 * set the filename
55 * @param string filename name of file to import/export
57 function setFilename( $filename ) {
58 $this->filename = $filename;
61 /**
62 * set matchgrades
63 * @param string matchgrades error or nearest for grades
65 function setMatchgrades( $matchgrades ) {
66 $this->matchgrades = $matchgrades;
69 /**
70 * set catfromfile
71 * @param bool catfromfile allow categories embedded in import file
73 function setCatfromfile( $catfromfile ) {
74 $this->catfromfile = $catfromfile;
77 /**
78 * set cattofile
79 * @param bool cattofile exports categories within export file
81 function setCattofile( $cattofile ) {
82 $this->cattofile = $cattofile;
85 /**
86 * set stoponerror
87 * @param bool stoponerror stops database write if any errors reported
89 function setStoponerror( $stoponerror ) {
90 $this->stoponerror = $stoponerror;
93 /***********************
94 * IMPORTING FUNCTIONS
95 ***********************/
97 /**
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>";
105 if (!empty($text)) {
106 $text = s($text);
107 echo "<blockquote>$text</blockquote>\n";
109 echo "<strong>$message</strong>\n";
110 echo "</div>";
112 $this->importerrors++;
116 * Perform any required pre-processing
117 * @return boolean success
119 function importpreprocess() {
120 return true;
124 * Process the file
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
131 @set_time_limit();
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') );
138 return false;
141 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
142 notify( get_string('noquestionsinfile','quiz') );
143 return false;
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)) {
151 return false;
154 // get list of valid answer grades
155 $grades = get_grade_options();
156 $gradeoptionsfull = $grades->gradeoptionsfull;
158 $count = 0;
160 foreach ($questions as $question) { // Process and store each question
162 // reset the php timeout
163 @set_time_limit();
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;
175 continue;
178 $count++;
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;
191 else {
192 $fractions[$key] = $newfraction;
195 if (!$answersvalid) {
196 notify(get_string('matcherror', 'quiz'));
197 continue;
199 else {
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
215 global $QTYPES;
216 $result = $QTYPES[$question->qtype]
217 ->save_question_options($question);
219 if (!empty($result->error)) {
220 notify($result->error);
221 return false;
224 if (!empty($result->notice)) {
225 notify($result->notice);
226 return true;
229 // Give the question a unique version stamp determined by question_hash()
230 set_field('question', 'version', question_hash($question), 'id', $question->id);
232 return true;
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]);
247 } else {
248 return $filearray;
251 return false;
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) {
272 $line = trim($line);
273 if (empty($line)) {
274 if (!empty($currentquestion)) {
275 if ($question = $this->readquestion($currentquestion)) {
276 $questions[] = $question;
278 $currentquestion = array();
280 } else {
281 $currentquestion[] = $line;
285 if (!empty($currentquestion)) { // There may be a final question
286 if ($question = $this->readquestion($currentquestion)) {
287 $questions[] = $question;
291 return $questions;
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() {
303 global $CFG;
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;
323 return $question;
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>";
341 return NULL;
345 * Override if any post-processing is required
346 * @return boolean success
348 function importpostprocess() {
349 return true;
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 ) {
359 global $CFG;
361 // all this to get the destination directory
362 // and filename!
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 )) {
377 return '';
379 $newfullpath = "$destination/$newfile";
380 if (!$fh = fopen( $newfullpath, 'w' )) {
381 return '';
383 if (!fwrite( $fh, $content )) {
384 return '';
386 fclose( $fh );
388 // return the (possibly) new filename
389 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
390 return $newfile;
393 /*******************
394 * EXPORT FUNCTIONS
395 *******************/
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() {
403 return ".txt";
407 * Do any pre-processing that may be required
408 * @param boolean success
410 function exportpreprocess() {
411 return true;
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 ) {
422 return $content;
426 * Do the export
427 * For most types this should not need to be overrided
428 * @return boolean success
430 function exportprocess() {
431 global $CFG;
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') );
446 return false;
448 $count = 0;
450 // results are first written into string (and then to a file)
451 // so create/initialize the string here
452 $expout = "";
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
457 $trackcategory = 0;
459 // iterate through questions
460 foreach($questions as $question) {
462 // do not export hidden questions
463 if (!empty($question->hidden)) {
464 continue;
467 // do not export random questions
468 if ($question->qtype==RANDOM) {
469 continue;
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
490 $count++;
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 );
498 // write file
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) );
506 fclose($fh);
507 return true;
511 * Do an post-processing that may be required
512 * @return boolean success
514 function exportpostprocess() {
515 return true;
519 * convert a single question object into text output in the given
520 * format.
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>";
530 return NULL;
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
540 return $path;
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;
553 } else {
554 $format = $question->questiontextformat;
556 return format_text(stripslashes($question->questiontext), $format, $formatoptions);