Changed grade_item so that its grademax is count(scale_items) and grademin is 1,...
[moodle-pu.git] / question / format.php
blob7d00f0852ca2e38ba8457d34a999c44541b9da4e
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 // 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 )) {
374 return '';
376 $newfullpath = "$destination/$newfile";
377 if (!$fh = fopen( $newfullpath, 'w' )) {
378 return '';
380 if (!fwrite( $fh, $content )) {
381 return '';
383 fclose( $fh );
385 // return the (possibly) new filename
386 return $newfile;
389 /*******************
390 * EXPORT FUNCTIONS
391 *******************/
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() {
399 return ".txt";
403 * Do any pre-processing that may be required
404 * @param boolean success
406 function exportpreprocess() {
407 return true;
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 ) {
418 return $content;
422 * Do the export
423 * For most types this should not need to be overrided
424 * @return boolean success
426 function exportprocess() {
427 global $CFG;
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') );
442 return false;
444 $count = 0;
446 // results are first written into string (and then to a file)
447 // so create/initialize the string here
448 $expout = "";
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
453 $trackcategory = 0;
455 // iterate through questions
456 foreach($questions as $question) {
458 // do not export hidden questions
459 if (!empty($question->hidden)) {
460 continue;
463 // do not export random questions
464 if ($question->qtype==RANDOM) {
465 continue;
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
486 $count++;
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 );
494 // write file
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) );
502 fclose($fh);
503 return true;
507 * Do an post-processing that may be required
508 * @return boolean success
510 function exportpostprocess() {
511 return true;
515 * convert a single question object into text output in the given
516 * format.
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>";
526 return NULL;
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
536 return $path;
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;
549 } else {
550 $format = $question->questiontextformat;
552 return format_text(stripslashes($question->questiontext), $format, $formatoptions);