removing $grade_item param from grade_grde methods - not needed anymore, assignment...
[moodle.git] / question / format.php
CommitLineData
aca318e1 1<?php // $Id$
4323d029 2/**
3 * Base class for question import and export formats.
4 *
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
4323d029 10 */
f5565b69 11class qformat_default {
aca318e1 12
f1abd39f 13 var $displayerrors = true;
aca318e1 14 var $category = NULL;
15 var $course = NULL;
08892d5b 16 var $filename = '';
17 var $matchgrades = 'error';
18 var $catfromfile = 0;
f1abd39f 19 var $cattofile = 0;
aca318e1 20 var $questionids = array();
f3701561 21 var $importerrors = 0;
22 var $stoponerror = true;
aca318e1 23
24// functions to indicate import/export functionality
25// override to return true if implemented
26
27 function provide_import() {
28 return false;
29 }
30
31 function provide_export() {
32 return false;
33 }
34
08892d5b 35// Accessor methods
aca318e1 36
08892d5b 37 /**
38 * set the category
39 * @param object category the category object
40 */
41 function setCategory( $category ) {
42 $this->category = $category;
43 }
aca318e1 44
08892d5b 45 /**
46 * set the course class variable
47 * @param course object Moodle course variable
48 */
49 function setCourse( $course ) {
aca318e1 50 $this->course = $course;
08892d5b 51 }
aca318e1 52
08892d5b 53 /**
54 * set the filename
55 * @param string filename name of file to import/export
56 */
57 function setFilename( $filename ) {
58 $this->filename = $filename;
59 }
60
61 /**
62 * set matchgrades
63 * @param string matchgrades error or nearest for grades
64 */
65 function setMatchgrades( $matchgrades ) {
66 $this->matchgrades = $matchgrades;
aca318e1 67 }
68
76f0a334 69 /**
08892d5b 70 * set catfromfile
71 * @param bool catfromfile allow categories embedded in import file
76f0a334 72 */
08892d5b 73 function setCatfromfile( $catfromfile ) {
74 $this->catfromfile = $catfromfile;
75 }
f1abd39f 76
77 /**
78 * set cattofile
79 * @param bool cattofile exports categories within export file
80 */
81 function setCattofile( $cattofile ) {
82 $this->cattofile = $cattofile;
83 }
aca318e1 84
f3701561 85 /**
86 * set stoponerror
87 * @param bool stoponerror stops database write if any errors reported
88 */
89 function setStoponerror( $stoponerror ) {
90 $this->stoponerror = $stoponerror;
91 }
92
93/***********************
94 * IMPORTING FUNCTIONS
95 ***********************/
96
97 /**
98 * Handle parsing error
99 */
100 function error( $message, $text='', $questionname='' ) {
cdeabc06 101 $importerrorquestion = get_string('importerrorquestion','quiz');
102
f3701561 103 echo "<div class=\"importerror\">\n";
cdeabc06 104 echo "<strong>$importerrorquestion $questionname</strong>";
f3701561 105 if (!empty($text)) {
106 $text = s($text);
107 echo "<blockquote>$text</blockquote>\n";
108 }
109 echo "<strong>$message</strong>\n";
110 echo "</div>";
111
112 $this->importerrors++;
113 }
08892d5b 114
115 /**
116 * Perform any required pre-processing
f3701561 117 * @return boolean success
08892d5b 118 */
119 function importpreprocess() {
120 return true;
121 }
122
123 /**
124 * Process the file
125 * This method should not normally be overidden
f3701561 126 * @return boolean success
08892d5b 127 */
128 function importprocess() {
f3701561 129
67c12527 130 // reset the timer in case file upload was slow
131 @set_time_limit();
132
f3701561 133 // STAGE 1: Parse the file
134 notify( get_string('parsingquestions','quiz') );
135
08892d5b 136 if (! $lines = $this->readdata($this->filename)) {
1e3d6fd8 137 notify( get_string('cannotread','quiz') );
aca318e1 138 return false;
139 }
140
141 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
1e3d6fd8 142 notify( get_string('noquestionsinfile','quiz') );
aca318e1 143 return false;
144 }
145
f3701561 146 // STAGE 2: Write data to database
1e3d6fd8 147 notify( get_string('importingquestions','quiz',count($questions)) );
aca318e1 148
f3701561 149 // check for errors before we continue
150 if ($this->stoponerror and ($this->importerrors>0)) {
151 return false;
152 }
153
76f0a334 154 // get list of valid answer grades
155 $grades = get_grade_options();
156 $gradeoptionsfull = $grades->gradeoptionsfull;
157
aca318e1 158 $count = 0;
159
160 foreach ($questions as $question) { // Process and store each question
08892d5b 161
67c12527 162 // reset the php timeout
163 @set_time_limit();
164
08892d5b 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;
173 }
174 }
175 continue;
176 }
177
aca318e1 178 $count++;
179
5b0dc681 180 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
aca318e1 181
76f0a334 182 // check for answer grades validity (must match fixed list of grades)
08892d5b 183 if (!empty($question->fraction) and (is_array($question->fraction))) {
656ee8c6 184 $fractions = $question->fraction;
2d52056f 185 $answersvalid = true; // in case they are!
186 foreach ($fractions as $key => $fraction) {
08892d5b 187 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
2d52056f 188 if ($newfraction===false) {
189 $answersvalid = false;
190 }
191 else {
192 $fractions[$key] = $newfraction;
193 }
194 }
195 if (!$answersvalid) {
eedb2494 196 notify(get_string('matcherror', 'quiz'));
2d52056f 197 continue;
76f0a334 198 }
199 else {
2d52056f 200 $question->fraction = $fractions;
76f0a334 201 }
202 }
76f0a334 203
aca318e1 204 $question->category = $this->category->id;
205 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 206
062f1125 207 if (!$question->id = insert_record("question", $question)) {
1e3d6fd8 208 error( get_string('cannotinsert','quiz') );
aca318e1 209 }
210
211 $this->questionids[] = $question->id;
212
213 // Now to save all the answers and type-specific options
214
215 global $QTYPES;
216 $result = $QTYPES[$question->qtype]
217 ->save_question_options($question);
218
219 if (!empty($result->error)) {
220 notify($result->error);
221 return false;
222 }
223
224 if (!empty($result->notice)) {
225 notify($result->notice);
226 return true;
227 }
cbe20043 228
229 // Give the question a unique version stamp determined by question_hash()
230 set_field('question', 'version', question_hash($question), 'id', $question->id);
aca318e1 231 }
232 return true;
233 }
234
f3701561 235 /**
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
239 */
aca318e1 240 function readdata($filename) {
aca318e1 241 if (is_readable($filename)) {
242 $filearray = file($filename);
243
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;
249 }
250 }
251 return false;
252 }
253
f3701561 254 /**
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.
259 *
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
265 */
aca318e1 266 function readquestions($lines) {
aca318e1 267
268 $questions = array();
269 $currentquestion = array();
270
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;
277 }
278 $currentquestion = array();
279 }
280 } else {
281 $currentquestion[] = $line;
282 }
283 }
284
285 if (!empty($currentquestion)) { // There may be a final question
286 if ($question = $this->readquestion($currentquestion)) {
287 $questions[] = $question;
288 }
289 }
290
291 return $questions;
292 }
293
294
f3701561 295 /**
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
301 */
aca318e1 302 function defaultquestion() {
b0679efa 303 global $CFG;
304
aca318e1 305 $question = new stdClass();
b0679efa 306 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
aca318e1 307 $question->defaultgrade = 1;
308 $question->image = "";
309 $question->usecase = 0;
310 $question->multiplier = array();
172f6d95 311 $question->generalfeedback = '';
08892d5b 312 $question->correctfeedback = '';
313 $question->partiallycorrectfeedback = '';
314 $question->incorrectfeedback = '';
5931ea94 315 $question->answernumbering = 'abc';
46013523 316 $question->penalty = 0.1;
aca318e1 317
5fd8f999 318 // this option in case the questiontypes class wants
319 // to know where the data came from
320 $question->export_process = true;
093414d2 321 $question->import_process = true;
5fd8f999 322
aca318e1 323 return $question;
324 }
325
f3701561 326 /**
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.
330 *
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
335 */
aca318e1 336 function readquestion($lines) {
aca318e1 337
1e3d6fd8 338 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
339 echo "<p>$formatnotimplemented</p>";
aca318e1 340
341 return NULL;
342 }
343
f3701561 344 /**
345 * Override if any post-processing is required
346 * @return boolean success
347 */
aca318e1 348 function importpostprocess() {
aca318e1 349 return true;
350 }
351
f3701561 352 /**
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)
357 */
d08e16b2 358 function importimagefile( $path, $base64 ) {
d08e16b2 359 global $CFG;
360
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'] );
367
71735794 368 // check if path exists
369 check_dir_exists($destination, true, true );
370
d08e16b2 371 // detect and fix any filename collision - get unique filename
372 $newfiles = resolve_filename_collisions( $destination, array($file) );
373 $newfile = $newfiles[0];
374
375 // convert and save file contents
376 if (!$content = base64_decode( $base64 )) {
46013523 377 return '';
d08e16b2 378 }
379 $newfullpath = "$destination/$newfile";
380 if (!$fh = fopen( $newfullpath, 'w' )) {
46013523 381 return '';
d08e16b2 382 }
383 if (!fwrite( $fh, $content )) {
46013523 384 return '';
d08e16b2 385 }
386 fclose( $fh );
387
388 // return the (possibly) new filename
71735794 389 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
d08e16b2 390 return $newfile;
391 }
392
f3701561 393/*******************
394 * EXPORT FUNCTIONS
395 *******************/
aca318e1 396
f3701561 397 /**
398 * Return the files extension appropriate for this type
399 * override if you don't want .txt
400 * @return string file extension
401 */
aca318e1 402 function export_file_extension() {
aca318e1 403 return ".txt";
404 }
405
f3701561 406 /**
407 * Do any pre-processing that may be required
408 * @param boolean success
409 */
08892d5b 410 function exportpreprocess() {
aca318e1 411 return true;
412 }
413
f3701561 414 /**
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
420 */
aca318e1 421 function presave_process( $content ) {
aca318e1 422 return $content;
423 }
424
f3701561 425 /**
426 * Do the export
427 * For most types this should not need to be overrided
428 * @return boolean success
429 */
08892d5b 430 function exportprocess() {
aca318e1 431 global $CFG;
432
433 // create a directory for the exports (if not already existing)
1367cb8d 434 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
435 error( get_string('cannotcreatepath','quiz',$export_dir) );
aca318e1 436 }
1367cb8d 437 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 438
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 );
442
1e3d6fd8 443 notify( get_string('exportingquestions','quiz') );
aca318e1 444 if (!count($questions)) {
1e3d6fd8 445 notify( get_string('noquestions','quiz') );
446 return false;
aca318e1 447 }
448 $count = 0;
449
450 // results are first written into string (and then to a file)
451 // so create/initialize the string here
452 $expout = "";
f1abd39f 453
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;
aca318e1 458
459 // iterate through questions
460 foreach($questions as $question) {
f1abd39f 461
a9b16aff 462 // do not export hidden questions
463 if (!empty($question->hidden)) {
464 continue;
465 }
466
467 // do not export random questions
468 if ($question->qtype==RANDOM) {
469 continue;
470 }
f1abd39f 471
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 );
477
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";
486 }
487 }
488
489 // export the question displaying message
490 $count++;
5b0dc681 491 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
f1abd39f 492 $expout .= $this->writequestion( $question ) . "\n";
a9b16aff 493 }
aca318e1 494
495 // final pre-process on exported data
496 $expout = $this->presave_process( $expout );
f1abd39f 497
aca318e1 498 // write file
08892d5b 499 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 500 if (!$fh=fopen($filepath,"w")) {
1e3d6fd8 501 error( get_string('cannotopen','quiz',$filepath) );
aca318e1 502 }
f1abd39f 503 if (!fwrite($fh, $expout, strlen($expout) )) {
1e3d6fd8 504 error( get_string('cannotwrite','quiz',$filepath) );
aca318e1 505 }
506 fclose($fh);
aca318e1 507 return true;
508 }
509
f3701561 510 /**
511 * Do an post-processing that may be required
512 * @return boolean success
513 */
aca318e1 514 function exportpostprocess() {
aca318e1 515 return true;
516 }
517
f3701561 518 /**
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
524 */
aca318e1 525 function writequestion($question) {
1e3d6fd8 526 // if not overidden, then this is an error.
527 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
528 echo "<p>$formatnotimplemented</p>";
aca318e1 529
530 return NULL;
531 }
532
f3701561 533 /**
534 * get directory into which export is going
535 * @return string file path
536 */
1367cb8d 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;
541 }
542
f3701561 543 /**
544 * where question specifies a moodle (text) format this
545 * performs the conversion.
546 */
5b0dc681 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;
555 }
556 return format_text(stripslashes($question->questiontext), $format, $formatoptions);
557 }
aca318e1 558}
559
560?>