MDL-12463, do not backup mod gradeitems if not selected
[moodle.git] / question / format.php
CommitLineData
271e6dec 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;
271e6dec 19 var $contextfromfile = 0;
f1abd39f 20 var $cattofile = 0;
271e6dec 21 var $contexttofile = 0;
aca318e1 22 var $questionids = array();
f3701561 23 var $importerrors = 0;
24 var $stoponerror = true;
271e6dec 25 var $translator = null;
26
aca318e1 27
28// functions to indicate import/export functionality
29// override to return true if implemented
30
31 function provide_import() {
32 return false;
33 }
34
35 function provide_export() {
36 return false;
37 }
38
08892d5b 39// Accessor methods
aca318e1 40
08892d5b 41 /**
42 * set the category
43 * @param object category the category object
44 */
45 function setCategory( $category ) {
46 $this->category = $category;
47 }
aca318e1 48
08892d5b 49 /**
50 * set the course class variable
51 * @param course object Moodle course variable
52 */
53 function setCourse( $course ) {
aca318e1 54 $this->course = $course;
08892d5b 55 }
271e6dec 56 /**
57 * set an array of contexts.
58 * @param array $contexts Moodle course variable
59 */
60 function setContexts($contexts) {
61 $this->contexts = $contexts;
62 $this->translator = new context_to_string_translator($this->contexts);
63 }
aca318e1 64
08892d5b 65 /**
66 * set the filename
67 * @param string filename name of file to import/export
68 */
69 function setFilename( $filename ) {
70 $this->filename = $filename;
71 }
72
73 /**
74 * set matchgrades
75 * @param string matchgrades error or nearest for grades
76 */
77 function setMatchgrades( $matchgrades ) {
78 $this->matchgrades = $matchgrades;
aca318e1 79 }
80
76f0a334 81 /**
08892d5b 82 * set catfromfile
83 * @param bool catfromfile allow categories embedded in import file
76f0a334 84 */
08892d5b 85 function setCatfromfile( $catfromfile ) {
86 $this->catfromfile = $catfromfile;
87 }
271e6dec 88
89 /**
90 * set contextfromfile
91 * @param bool $contextfromfile allow contexts embedded in import file
92 */
93 function setContextfromfile($contextfromfile) {
94 $this->contextfromfile = $contextfromfile;
95 }
96
f1abd39f 97 /**
98 * set cattofile
99 * @param bool cattofile exports categories within export file
100 */
101 function setCattofile( $cattofile ) {
102 $this->cattofile = $cattofile;
271e6dec 103 }
104 /**
105 * set contexttofile
106 * @param bool cattofile exports categories within export file
107 */
108 function setContexttofile($contexttofile) {
109 $this->contexttofile = $contexttofile;
110 }
aca318e1 111
f3701561 112 /**
113 * set stoponerror
114 * @param bool stoponerror stops database write if any errors reported
115 */
116 function setStoponerror( $stoponerror ) {
117 $this->stoponerror = $stoponerror;
118 }
119
120/***********************
121 * IMPORTING FUNCTIONS
122 ***********************/
123
124 /**
125 * Handle parsing error
126 */
127 function error( $message, $text='', $questionname='' ) {
cdeabc06 128 $importerrorquestion = get_string('importerrorquestion','quiz');
129
f3701561 130 echo "<div class=\"importerror\">\n";
cdeabc06 131 echo "<strong>$importerrorquestion $questionname</strong>";
f3701561 132 if (!empty($text)) {
133 $text = s($text);
134 echo "<blockquote>$text</blockquote>\n";
135 }
136 echo "<strong>$message</strong>\n";
137 echo "</div>";
138
139 $this->importerrors++;
140 }
08892d5b 141
271e6dec 142 /**
a41e3287 143 * Import for questiontype plugins
144 * Do not override.
145 * @param data mixed The segment of data containing the question
146 * @param question object processed (so far) by standard import code if appropriate
147 * @param extra mixed any additional format specific data that may be passed by the format
148 * @return object question object suitable for save_options() or false if cannot handle
149 */
150 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
151 global $QTYPES;
152
153 // work out what format we are using
154 $formatname = substr( get_class( $this ), strlen('qformat_'));
155 $methodname = "import_from_$formatname";
156
157 // loop through installed questiontypes checking for
158 // function to handle this question
159 foreach ($QTYPES as $qtype) {
160 if (method_exists( $qtype, $methodname)) {
161 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
162 return $question;
163 }
164 }
271e6dec 165 }
166 return false;
a41e3287 167 }
168
08892d5b 169 /**
170 * Perform any required pre-processing
f3701561 171 * @return boolean success
08892d5b 172 */
173 function importpreprocess() {
174 return true;
175 }
176
177 /**
178 * Process the file
179 * This method should not normally be overidden
f3701561 180 * @return boolean success
08892d5b 181 */
182 function importprocess() {
271e6dec 183 global $USER;
f3701561 184
67c12527 185 // reset the timer in case file upload was slow
186 @set_time_limit();
187
f3701561 188 // STAGE 1: Parse the file
189 notify( get_string('parsingquestions','quiz') );
271e6dec 190
08892d5b 191 if (! $lines = $this->readdata($this->filename)) {
1e3d6fd8 192 notify( get_string('cannotread','quiz') );
aca318e1 193 return false;
194 }
195
196 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
1e3d6fd8 197 notify( get_string('noquestionsinfile','quiz') );
aca318e1 198 return false;
199 }
200
f3701561 201 // STAGE 2: Write data to database
ce2df288 202 notify( get_string('importingquestions','quiz',$this->count_questions($questions)) );
aca318e1 203
f3701561 204 // check for errors before we continue
205 if ($this->stoponerror and ($this->importerrors>0)) {
206 return false;
207 }
208
76f0a334 209 // get list of valid answer grades
210 $grades = get_grade_options();
211 $gradeoptionsfull = $grades->gradeoptionsfull;
212
c1828e0b 213 // check answer grades are valid
214 // (now need to do this here because of 'stop on error': MDL-10689)
215 $gradeerrors = 0;
216 $goodquestions = array();
217 foreach ($questions as $question) {
218 if (!empty($question->fraction) and (is_array($question->fraction))) {
219 $fractions = $question->fraction;
220 $answersvalid = true; // in case they are!
221 foreach ($fractions as $key => $fraction) {
222 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
223 if ($newfraction===false) {
224 $answersvalid = false;
225 }
226 else {
227 $fractions[$key] = $newfraction;
228 }
229 }
230 if (!$answersvalid) {
231 notify(get_string('matcherror', 'quiz'));
232 ++$gradeerrors;
233 continue;
234 }
235 else {
236 $question->fraction = $fractions;
237 }
238 }
239 $goodquestions[] = $question;
240 }
241 $questions = $goodquestions;
242
243 // check for errors before we continue
244 if ($this->stoponerror and ($gradeerrors>0)) {
245 return false;
246 }
247
248 // count number of questions processed
aca318e1 249 $count = 0;
250
251 foreach ($questions as $question) { // Process and store each question
08892d5b 252
271e6dec 253 // reset the php timeout
67c12527 254 @set_time_limit();
255
08892d5b 256 // check for category modifiers
257 if ($question->qtype=='category') {
258 if ($this->catfromfile) {
259 // find/create category object
488eaca4 260 $catpath = $question->category['text'][0]['#'];
271e6dec 261 $newcategory = $this->create_category_path( $catpath, '/');
08892d5b 262 if (!empty($newcategory)) {
263 $this->category = $newcategory;
264 }
265 }
271e6dec 266 continue;
08892d5b 267 }
268
aca318e1 269 $count++;
270
5b0dc681 271 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
aca318e1 272
273 $question->category = $this->category->id;
274 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 275
271e6dec 276 $question->createdby = $USER->id;
277 $question->timecreated = time();
278
062f1125 279 if (!$question->id = insert_record("question", $question)) {
1e3d6fd8 280 error( get_string('cannotinsert','quiz') );
aca318e1 281 }
282
283 $this->questionids[] = $question->id;
284
285 // Now to save all the answers and type-specific options
286
287 global $QTYPES;
288 $result = $QTYPES[$question->qtype]
289 ->save_question_options($question);
290
291 if (!empty($result->error)) {
292 notify($result->error);
293 return false;
294 }
295
296 if (!empty($result->notice)) {
297 notify($result->notice);
298 return true;
299 }
cbe20043 300
301 // Give the question a unique version stamp determined by question_hash()
302 set_field('question', 'version', question_hash($question), 'id', $question->id);
aca318e1 303 }
304 return true;
305 }
ce2df288 306 /**
307 * Count all non-category questions in the questions array.
308 *
309 * @param array questions An array of question objects.
310 * @return int The count.
311 *
312 */
313 function count_questions($questions) {
314 $count = 0;
315 if (!is_array($questions)) {
316 return $count;
317 }
318 foreach ($questions as $question) {
319 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
320 continue;
321 }
322 $count++;
323 }
324 return $count;
325 }
326
271e6dec 327 /**
328 * find and/or create the category described by a delimited list
329 * e.g. $course$/tom/dick/harry or tom/dick/harry
330 *
331 * removes any context string no matter whether $getcontext is set
332 * but if $getcontext is set then ignore the context and use selected category context.
333 *
334 * @param string catpath delimited category path
335 * @param string delimiter path delimiting character
336 * @param int courseid course to search for categories
337 * @return mixed category object or null if fails
338 */
339 function create_category_path($catpath, $delimiter='/') {
340 $catpath = clean_param($catpath, PARAM_PATH);
341 $catnames = explode($delimiter, $catpath);
342 $parent = 0;
343 $category = null;
344 if (FALSE !== preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches)){
345 $contextid = $this->translator->string_to_context($matches[1]);
346 array_shift($catnames);
347 } else {
348 $contextid = FALSE;
349 }
350 if ($this->contextfromfile && ($contextid !== FALSE)){
351 $context = get_context_instance_by_id($contextid);
352 require_capability('moodle/question:add', $context);
353 } else {
354 $context = get_context_instance_by_id($this->category->contextid);
355 }
356 foreach ($catnames as $catname) {
357 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) {
358 $parent = $category->id;
359 } else {
360 require_capability('moodle/question:managecategory', $context);
361 // create the new category
362 $category = new object;
363 $category->contextid = $context->id;
364 $category->name = $catname;
365 $category->info = '';
366 $category->parent = $parent;
367 $category->sortorder = 999;
368 $category->stamp = make_unique_id_code();
369 if (!($id = insert_record('question_categories', $category))) {
370 error( "cannot create new category - $catname" );
371 }
372 $category->id = $id;
373 $parent = $id;
374 }
375 }
376 return $category;
377 }
f3701561 378 /**
379 * Return complete file within an array, one item per line
380 * @param string filename name of file
381 * @return mixed contents array or false on failure
382 */
aca318e1 383 function readdata($filename) {
aca318e1 384 if (is_readable($filename)) {
385 $filearray = file($filename);
386
387 /// Check for Macintosh OS line returns (ie file on one line), and fix
388 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
389 return explode("\r", $filearray[0]);
390 } else {
391 return $filearray;
392 }
393 }
394 return false;
395 }
396
f3701561 397 /**
271e6dec 398 * Parses an array of lines into an array of questions,
399 * where each item is a question object as defined by
400 * readquestion(). Questions are defined as anything
f3701561 401 * between blank lines.
402 *
403 * If your format does not use blank lines as a delimiter
404 * then you will need to override this method. Even then
405 * try to use readquestion for each question
406 * @param array lines array of lines from readdata
407 * @return array array of question objects
408 */
aca318e1 409 function readquestions($lines) {
271e6dec 410
aca318e1 411 $questions = array();
412 $currentquestion = array();
413
414 foreach ($lines as $line) {
415 $line = trim($line);
416 if (empty($line)) {
417 if (!empty($currentquestion)) {
418 if ($question = $this->readquestion($currentquestion)) {
419 $questions[] = $question;
420 }
421 $currentquestion = array();
422 }
423 } else {
424 $currentquestion[] = $line;
425 }
426 }
427
428 if (!empty($currentquestion)) { // There may be a final question
429 if ($question = $this->readquestion($currentquestion)) {
430 $questions[] = $question;
431 }
432 }
433
434 return $questions;
435 }
436
437
f3701561 438 /**
439 * return an "empty" question
440 * Somewhere to specify question parameters that are not handled
441 * by import but are required db fields.
442 * This should not be overridden.
443 * @return object default question
271e6dec 444 */
aca318e1 445 function defaultquestion() {
b0679efa 446 global $CFG;
271e6dec 447
aca318e1 448 $question = new stdClass();
271e6dec 449 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
aca318e1 450 $question->defaultgrade = 1;
451 $question->image = "";
452 $question->usecase = 0;
453 $question->multiplier = array();
172f6d95 454 $question->generalfeedback = '';
08892d5b 455 $question->correctfeedback = '';
456 $question->partiallycorrectfeedback = '';
457 $question->incorrectfeedback = '';
5931ea94 458 $question->answernumbering = 'abc';
46013523 459 $question->penalty = 0.1;
aca318e1 460
5fd8f999 461 // this option in case the questiontypes class wants
462 // to know where the data came from
463 $question->export_process = true;
093414d2 464 $question->import_process = true;
5fd8f999 465
aca318e1 466 return $question;
467 }
468
f3701561 469 /**
271e6dec 470 * Given the data known to define a question in
471 * this format, this function converts it into a question
f3701561 472 * object suitable for processing and insertion into Moodle.
473 *
474 * If your format does not use blank lines to delimit questions
475 * (e.g. an XML format) you must override 'readquestions' too
476 * @param $lines mixed data that represents question
477 * @return object question object
478 */
aca318e1 479 function readquestion($lines) {
aca318e1 480
1e3d6fd8 481 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
482 echo "<p>$formatnotimplemented</p>";
aca318e1 483
484 return NULL;
485 }
486
f3701561 487 /**
488 * Override if any post-processing is required
489 * @return boolean success
490 */
aca318e1 491 function importpostprocess() {
aca318e1 492 return true;
493 }
494
f3701561 495 /**
496 * Import an image file encoded in base64 format
497 * @param string path path (in course data) to store picture
498 * @param string base64 encoded picture
499 * @return string filename (nb. collisions are handled)
500 */
d08e16b2 501 function importimagefile( $path, $base64 ) {
d08e16b2 502 global $CFG;
503
504 // all this to get the destination directory
505 // and filename!
506 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
507 $path_parts = pathinfo( $fullpath );
508 $destination = $path_parts['dirname'];
509 $file = clean_filename( $path_parts['basename'] );
510
71735794 511 // check if path exists
512 check_dir_exists($destination, true, true );
513
d08e16b2 514 // detect and fix any filename collision - get unique filename
271e6dec 515 $newfiles = resolve_filename_collisions( $destination, array($file) );
d08e16b2 516 $newfile = $newfiles[0];
517
518 // convert and save file contents
519 if (!$content = base64_decode( $base64 )) {
46013523 520 return '';
d08e16b2 521 }
522 $newfullpath = "$destination/$newfile";
523 if (!$fh = fopen( $newfullpath, 'w' )) {
46013523 524 return '';
d08e16b2 525 }
526 if (!fwrite( $fh, $content )) {
46013523 527 return '';
d08e16b2 528 }
529 fclose( $fh );
530
531 // return the (possibly) new filename
71735794 532 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
d08e16b2 533 return $newfile;
534 }
535
f3701561 536/*******************
537 * EXPORT FUNCTIONS
538 *******************/
aca318e1 539
271e6dec 540 /**
a41e3287 541 * Provide export functionality for plugin questiontypes
542 * Do not override
543 * @param name questiontype name
271e6dec 544 * @param question object data to export
a41e3287 545 * @param extra mixed any addition format specific data needed
546 * @return string the data to append to export or false if error (or unhandled)
547 */
548 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
549 global $QTYPES;
550
551 // work out the name of format in use
552 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
553 $methodname = "export_to_$formatname";
554
555 if (array_key_exists( $name, $QTYPES )) {
556 $qtype = $QTYPES[ $name ];
557 if (method_exists( $qtype, $methodname )) {
558 if ($data = $qtype->$methodname( $question, $this, $extra )) {
559 return $data;
560 }
561 }
562 }
563 return false;
564 }
565
f3701561 566 /**
567 * Return the files extension appropriate for this type
568 * override if you don't want .txt
569 * @return string file extension
570 */
aca318e1 571 function export_file_extension() {
aca318e1 572 return ".txt";
573 }
574
f3701561 575 /**
576 * Do any pre-processing that may be required
577 * @param boolean success
578 */
08892d5b 579 function exportpreprocess() {
aca318e1 580 return true;
581 }
582
f3701561 583 /**
584 * Enable any processing to be done on the content
585 * just prior to the file being saved
586 * default is to do nothing
587 * @param string output text
588 * @param string processed output text
589 */
aca318e1 590 function presave_process( $content ) {
aca318e1 591 return $content;
592 }
593
f3701561 594 /**
595 * Do the export
596 * For most types this should not need to be overrided
597 * @return boolean success
598 */
08892d5b 599 function exportprocess() {
aca318e1 600 global $CFG;
601
602 // create a directory for the exports (if not already existing)
1367cb8d 603 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
604 error( get_string('cannotcreatepath','quiz',$export_dir) );
aca318e1 605 }
1367cb8d 606 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 607
608 // get the questions (from database) in this category
609 // only get q's with no parents (no cloze subquestions specifically)
610 $questions = get_questions_category( $this->category, true );
611
1e3d6fd8 612 notify( get_string('exportingquestions','quiz') );
aca318e1 613 $count = 0;
614
615 // results are first written into string (and then to a file)
616 // so create/initialize the string here
617 $expout = "";
271e6dec 618
f1abd39f 619 // track which category questions are in
620 // if it changes we will record the category change in the output
621 // file if selected. 0 means that it will get printed before the 1st question
622 $trackcategory = 0;
aca318e1 623
624 // iterate through questions
625 foreach($questions as $question) {
271e6dec 626
a9b16aff 627 // do not export hidden questions
628 if (!empty($question->hidden)) {
629 continue;
630 }
631
632 // do not export random questions
633 if ($question->qtype==RANDOM) {
634 continue;
635 }
271e6dec 636
f1abd39f 637 // check if we need to record category change
638 if ($this->cattofile) {
639 if ($question->category != $trackcategory) {
271e6dec 640 $trackcategory = $question->category;
641 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
642
f1abd39f 643 // create 'dummy' question for category export
644 $dummyquestion = new object;
645 $dummyquestion->qtype = 'category';
646 $dummyquestion->category = $categoryname;
647 $dummyquestion->name = "switch category to $categoryname";
648 $dummyquestion->id = 0;
649 $dummyquestion->questiontextformat = '';
650 $expout .= $this->writequestion( $dummyquestion ) . "\n";
271e6dec 651 }
652 }
f1abd39f 653
654 // export the question displaying message
655 $count++;
5b0dc681 656 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
0647e82b 657 if (question_has_capability_on($question, 'view', $question->category)){
658 $expout .= $this->writequestion( $question ) . "\n";
659 }
a9b16aff 660 }
aca318e1 661
2c6d2c88 662 // continue path for following error checks
663 $course = $this->course;
664 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
665
666 // did we actually process anything
667 if ($count==0) {
668 print_error( 'noquestions','quiz',$continuepath );
669 }
670
aca318e1 671 // final pre-process on exported data
672 $expout = $this->presave_process( $expout );
271e6dec 673
aca318e1 674 // write file
08892d5b 675 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 676 if (!$fh=fopen($filepath,"w")) {
2c6d2c88 677 print_error( 'cannotopen','quiz',$continuepath,$filepath );
aca318e1 678 }
f1abd39f 679 if (!fwrite($fh, $expout, strlen($expout) )) {
2c6d2c88 680 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
aca318e1 681 }
682 fclose($fh);
aca318e1 683 return true;
684 }
271e6dec 685 /**
686 * get the category as a path (e.g., tom/dick/harry)
687 * @param int id the id of the most nested catgory
688 * @param string delimiter the delimiter you want
689 * @return string the path
690 */
691 function get_category_path($id, $delimiter='/', $includecontext = true) {
692 $path = '';
693 if (!$firstcategory = get_record('question_categories','id',$id)) {
694 print_error( "Error getting category record from db - $id" );
695 }
696 $category = $firstcategory;
697 $contextstring = $this->translator->context_to_string($category->contextid);
698 do {
699 $name = $category->name;
700 $id = $category->parent;
701 if (!empty($path)) {
702 $path = "{$name}{$delimiter}{$path}";
703 }
704 else {
705 $path = $name;
706 }
707 } while ($category = get_record( 'question_categories','id',$id ));
708
709 if ($includecontext){
710 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
711 }
712 return $path;
713 }
aca318e1 714
f3701561 715 /**
716 * Do an post-processing that may be required
717 * @return boolean success
718 */
aca318e1 719 function exportpostprocess() {
aca318e1 720 return true;
721 }
722
f3701561 723 /**
724 * convert a single question object into text output in the given
725 * format.
726 * This must be overriden
727 * @param object question question object
728 * @return mixed question export text or null if not implemented
729 */
aca318e1 730 function writequestion($question) {
1e3d6fd8 731 // if not overidden, then this is an error.
732 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
733 echo "<p>$formatnotimplemented</p>";
aca318e1 734 return NULL;
735 }
736
f3701561 737 /**
271e6dec 738 * get directory into which export is going
f3701561 739 * @return string file path
740 */
1367cb8d 741 function question_get_export_dir() {
742 $dirname = get_string("exportfilename","quiz");
743 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
744 return $path;
745 }
746
f3701561 747 /**
748 * where question specifies a moodle (text) format this
749 * performs the conversion.
750 */
5b0dc681 751 function format_question_text($question) {
752 $formatoptions = new stdClass;
753 $formatoptions->noclean = true;
754 $formatoptions->para = false;
755 if (empty($question->questiontextformat)) {
756 $format = FORMAT_MOODLE;
757 } else {
758 $format = $question->questiontextformat;
759 }
760 return format_text(stripslashes($question->questiontext), $format, $formatoptions);
761 }
271e6dec 762
763
aca318e1 764}
765
766?>