MDL-9062 Created two new files so the unfinished conversion doesn't affect any curren...
[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
10 *//** */
aca318e1 11
4323d029 12/**
13 * Base class for question import and export formats.
14 *
15 * Doesn't do everything on it's own -- it needs to be extended.
16 *
17 * @package questionbank
18 * @subpackage importexport
19 */
f5565b69 20class qformat_default {
aca318e1 21
f1abd39f 22 var $displayerrors = true;
aca318e1 23 var $category = NULL;
24 var $course = NULL;
08892d5b 25 var $filename = '';
26 var $matchgrades = 'error';
27 var $catfromfile = 0;
f1abd39f 28 var $cattofile = 0;
aca318e1 29 var $questionids = array();
f3701561 30 var $importerrors = 0;
31 var $stoponerror = true;
aca318e1 32
33// functions to indicate import/export functionality
34// override to return true if implemented
35
36 function provide_import() {
37 return false;
38 }
39
40 function provide_export() {
41 return false;
42 }
43
08892d5b 44// Accessor methods
aca318e1 45
08892d5b 46 /**
47 * set the category
48 * @param object category the category object
49 */
50 function setCategory( $category ) {
51 $this->category = $category;
52 }
aca318e1 53
08892d5b 54 /**
55 * set the course class variable
56 * @param course object Moodle course variable
57 */
58 function setCourse( $course ) {
aca318e1 59 $this->course = $course;
08892d5b 60 }
aca318e1 61
08892d5b 62 /**
63 * set the filename
64 * @param string filename name of file to import/export
65 */
66 function setFilename( $filename ) {
67 $this->filename = $filename;
68 }
69
70 /**
71 * set matchgrades
72 * @param string matchgrades error or nearest for grades
73 */
74 function setMatchgrades( $matchgrades ) {
75 $this->matchgrades = $matchgrades;
aca318e1 76 }
77
76f0a334 78 /**
08892d5b 79 * set catfromfile
80 * @param bool catfromfile allow categories embedded in import file
76f0a334 81 */
08892d5b 82 function setCatfromfile( $catfromfile ) {
83 $this->catfromfile = $catfromfile;
84 }
f1abd39f 85
86 /**
87 * set cattofile
88 * @param bool cattofile exports categories within export file
89 */
90 function setCattofile( $cattofile ) {
91 $this->cattofile = $cattofile;
92 }
aca318e1 93
f3701561 94 /**
95 * set stoponerror
96 * @param bool stoponerror stops database write if any errors reported
97 */
98 function setStoponerror( $stoponerror ) {
99 $this->stoponerror = $stoponerror;
100 }
101
102/***********************
103 * IMPORTING FUNCTIONS
104 ***********************/
105
106 /**
107 * Handle parsing error
108 */
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";
115 }
116 echo "<strong>$message</strong>\n";
117 echo "</div>";
118
119 $this->importerrors++;
120 }
08892d5b 121
122 /**
123 * Perform any required pre-processing
f3701561 124 * @return boolean success
08892d5b 125 */
126 function importpreprocess() {
127 return true;
128 }
129
130 /**
131 * Process the file
132 * This method should not normally be overidden
f3701561 133 * @return boolean success
08892d5b 134 */
135 function importprocess() {
f3701561 136
137 // STAGE 1: Parse the file
138 notify( get_string('parsingquestions','quiz') );
139
08892d5b 140 if (! $lines = $this->readdata($this->filename)) {
1e3d6fd8 141 notify( get_string('cannotread','quiz') );
aca318e1 142 return false;
143 }
144
145 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
1e3d6fd8 146 notify( get_string('noquestionsinfile','quiz') );
aca318e1 147 return false;
148 }
149
f3701561 150 // STAGE 2: Write data to database
1e3d6fd8 151 notify( get_string('importingquestions','quiz',count($questions)) );
aca318e1 152
f3701561 153 // check for errors before we continue
154 if ($this->stoponerror and ($this->importerrors>0)) {
155 return false;
156 }
157
76f0a334 158 // get list of valid answer grades
159 $grades = get_grade_options();
160 $gradeoptionsfull = $grades->gradeoptionsfull;
161
aca318e1 162 $count = 0;
163
164 foreach ($questions as $question) { // Process and store each question
08892d5b 165
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;
174 }
175 }
176 continue;
177 }
178
aca318e1 179 $count++;
180
5b0dc681 181 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
aca318e1 182
76f0a334 183 // check for answer grades validity (must match fixed list of grades)
08892d5b 184 if (!empty($question->fraction) and (is_array($question->fraction))) {
656ee8c6 185 $fractions = $question->fraction;
2d52056f 186 $answersvalid = true; // in case they are!
187 foreach ($fractions as $key => $fraction) {
08892d5b 188 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
2d52056f 189 if ($newfraction===false) {
190 $answersvalid = false;
191 }
192 else {
193 $fractions[$key] = $newfraction;
194 }
195 }
196 if (!$answersvalid) {
197 notify( get_string('matcherror','quiz') );
198 continue;
76f0a334 199 }
200 else {
2d52056f 201 $question->fraction = $fractions;
76f0a334 202 }
203 }
76f0a334 204
aca318e1 205 $question->category = $this->category->id;
206 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 207
062f1125 208 if (!$question->id = insert_record("question", $question)) {
1e3d6fd8 209 error( get_string('cannotinsert','quiz') );
aca318e1 210 }
211
212 $this->questionids[] = $question->id;
213
214 // Now to save all the answers and type-specific options
215
216 global $QTYPES;
217 $result = $QTYPES[$question->qtype]
218 ->save_question_options($question);
219
220 if (!empty($result->error)) {
221 notify($result->error);
222 return false;
223 }
224
225 if (!empty($result->notice)) {
226 notify($result->notice);
227 return true;
228 }
cbe20043 229
230 // Give the question a unique version stamp determined by question_hash()
231 set_field('question', 'version', question_hash($question), 'id', $question->id);
aca318e1 232 }
233 return true;
234 }
235
f3701561 236 /**
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
240 */
aca318e1 241 function readdata($filename) {
aca318e1 242 if (is_readable($filename)) {
243 $filearray = file($filename);
244
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;
250 }
251 }
252 return false;
253 }
254
f3701561 255 /**
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.
260 *
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
266 */
aca318e1 267 function readquestions($lines) {
aca318e1 268
269 $questions = array();
270 $currentquestion = array();
271
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;
278 }
279 $currentquestion = array();
280 }
281 } else {
282 $currentquestion[] = $line;
283 }
284 }
285
286 if (!empty($currentquestion)) { // There may be a final question
287 if ($question = $this->readquestion($currentquestion)) {
288 $questions[] = $question;
289 }
290 }
291
292 return $questions;
293 }
294
295
f3701561 296 /**
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
302 */
aca318e1 303 function defaultquestion() {
b0679efa 304 global $CFG;
305
aca318e1 306 $question = new stdClass();
b0679efa 307 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
aca318e1 308 $question->defaultgrade = 1;
309 $question->image = "";
310 $question->usecase = 0;
311 $question->multiplier = array();
172f6d95 312 $question->generalfeedback = '';
08892d5b 313 $question->correctfeedback = '';
314 $question->partiallycorrectfeedback = '';
315 $question->incorrectfeedback = '';
aca318e1 316
317 return $question;
318 }
319
f3701561 320 /**
321 * Given the data known to define a question in
322 * this format, this function converts it into a question
323 * object suitable for processing and insertion into Moodle.
324 *
325 * If your format does not use blank lines to delimit questions
326 * (e.g. an XML format) you must override 'readquestions' too
327 * @param $lines mixed data that represents question
328 * @return object question object
329 */
aca318e1 330 function readquestion($lines) {
aca318e1 331
1e3d6fd8 332 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
333 echo "<p>$formatnotimplemented</p>";
aca318e1 334
335 return NULL;
336 }
337
f3701561 338 /**
339 * Override if any post-processing is required
340 * @return boolean success
341 */
aca318e1 342 function importpostprocess() {
aca318e1 343 return true;
344 }
345
f3701561 346 /**
347 * Import an image file encoded in base64 format
348 * @param string path path (in course data) to store picture
349 * @param string base64 encoded picture
350 * @return string filename (nb. collisions are handled)
351 */
d08e16b2 352 function importimagefile( $path, $base64 ) {
d08e16b2 353 global $CFG;
354
355 // all this to get the destination directory
356 // and filename!
357 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
358 $path_parts = pathinfo( $fullpath );
359 $destination = $path_parts['dirname'];
360 $file = clean_filename( $path_parts['basename'] );
361
362 // detect and fix any filename collision - get unique filename
363 $newfiles = resolve_filename_collisions( $destination, array($file) );
364 $newfile = $newfiles[0];
365
366 // convert and save file contents
367 if (!$content = base64_decode( $base64 )) {
368 return false;
369 }
370 $newfullpath = "$destination/$newfile";
371 if (!$fh = fopen( $newfullpath, 'w' )) {
372 return false;
373 }
374 if (!fwrite( $fh, $content )) {
375 return false;
376 }
377 fclose( $fh );
378
379 // return the (possibly) new filename
380 return $newfile;
381 }
382
f3701561 383/*******************
384 * EXPORT FUNCTIONS
385 *******************/
aca318e1 386
f3701561 387 /**
388 * Return the files extension appropriate for this type
389 * override if you don't want .txt
390 * @return string file extension
391 */
aca318e1 392 function export_file_extension() {
aca318e1 393 return ".txt";
394 }
395
f3701561 396 /**
397 * Do any pre-processing that may be required
398 * @param boolean success
399 */
08892d5b 400 function exportpreprocess() {
aca318e1 401 return true;
402 }
403
f3701561 404 /**
405 * Enable any processing to be done on the content
406 * just prior to the file being saved
407 * default is to do nothing
408 * @param string output text
409 * @param string processed output text
410 */
aca318e1 411 function presave_process( $content ) {
aca318e1 412 return $content;
413 }
414
f3701561 415 /**
416 * Do the export
417 * For most types this should not need to be overrided
418 * @return boolean success
419 */
08892d5b 420 function exportprocess() {
aca318e1 421 global $CFG;
422
423 // create a directory for the exports (if not already existing)
1367cb8d 424 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
425 error( get_string('cannotcreatepath','quiz',$export_dir) );
aca318e1 426 }
1367cb8d 427 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 428
429 // get the questions (from database) in this category
430 // only get q's with no parents (no cloze subquestions specifically)
431 $questions = get_questions_category( $this->category, true );
432
1e3d6fd8 433 notify( get_string('exportingquestions','quiz') );
aca318e1 434 if (!count($questions)) {
1e3d6fd8 435 notify( get_string('noquestions','quiz') );
436 return false;
aca318e1 437 }
438 $count = 0;
439
440 // results are first written into string (and then to a file)
441 // so create/initialize the string here
442 $expout = "";
f1abd39f 443
444 // track which category questions are in
445 // if it changes we will record the category change in the output
446 // file if selected. 0 means that it will get printed before the 1st question
447 $trackcategory = 0;
aca318e1 448
449 // iterate through questions
450 foreach($questions as $question) {
f1abd39f 451
a9b16aff 452 // do not export hidden questions
453 if (!empty($question->hidden)) {
454 continue;
455 }
456
457 // do not export random questions
458 if ($question->qtype==RANDOM) {
459 continue;
460 }
f1abd39f 461
462 // check if we need to record category change
463 if ($this->cattofile) {
464 if ($question->category != $trackcategory) {
465 $trackcategory = $question->category;
466 $categoryname = get_category_path( $trackcategory );
467
468 // create 'dummy' question for category export
469 $dummyquestion = new object;
470 $dummyquestion->qtype = 'category';
471 $dummyquestion->category = $categoryname;
472 $dummyquestion->name = "switch category to $categoryname";
473 $dummyquestion->id = 0;
474 $dummyquestion->questiontextformat = '';
475 $expout .= $this->writequestion( $dummyquestion ) . "\n";
476 }
477 }
478
479 // export the question displaying message
480 $count++;
5b0dc681 481 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
f1abd39f 482 $expout .= $this->writequestion( $question ) . "\n";
a9b16aff 483 }
aca318e1 484
485 // final pre-process on exported data
486 $expout = $this->presave_process( $expout );
f1abd39f 487
aca318e1 488 // write file
08892d5b 489 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 490 if (!$fh=fopen($filepath,"w")) {
1e3d6fd8 491 error( get_string('cannotopen','quiz',$filepath) );
aca318e1 492 }
f1abd39f 493 if (!fwrite($fh, $expout, strlen($expout) )) {
1e3d6fd8 494 error( get_string('cannotwrite','quiz',$filepath) );
aca318e1 495 }
496 fclose($fh);
aca318e1 497 return true;
498 }
499
f3701561 500 /**
501 * Do an post-processing that may be required
502 * @return boolean success
503 */
aca318e1 504 function exportpostprocess() {
aca318e1 505 return true;
506 }
507
f3701561 508 /**
509 * convert a single question object into text output in the given
510 * format.
511 * This must be overriden
512 * @param object question question object
513 * @return mixed question export text or null if not implemented
514 */
aca318e1 515 function writequestion($question) {
1e3d6fd8 516 // if not overidden, then this is an error.
517 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
518 echo "<p>$formatnotimplemented</p>";
aca318e1 519
520 return NULL;
521 }
522
f3701561 523 /**
524 * get directory into which export is going
525 * @return string file path
526 */
1367cb8d 527 function question_get_export_dir() {
528 $dirname = get_string("exportfilename","quiz");
529 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
530 return $path;
531 }
532
f3701561 533 /**
534 * where question specifies a moodle (text) format this
535 * performs the conversion.
536 */
5b0dc681 537 function format_question_text($question) {
538 $formatoptions = new stdClass;
539 $formatoptions->noclean = true;
540 $formatoptions->para = false;
541 if (empty($question->questiontextformat)) {
542 $format = FORMAT_MOODLE;
543 } else {
544 $format = $question->questiontextformat;
545 }
546 return format_text(stripslashes($question->questiontext), $format, $formatoptions);
547 }
aca318e1 548}
549
550?>