merged from 1.9 :: MDL-12191 :: workaround with JavaScript to add "haslayouttabel...
[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
1e3d6fd8 202 notify( get_string('importingquestions','quiz',count($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
260 $catpath = $question->category;
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 }
271e6dec 306 /**
307 * find and/or create the category described by a delimited list
308 * e.g. $course$/tom/dick/harry or tom/dick/harry
309 *
310 * removes any context string no matter whether $getcontext is set
311 * but if $getcontext is set then ignore the context and use selected category context.
312 *
313 * @param string catpath delimited category path
314 * @param string delimiter path delimiting character
315 * @param int courseid course to search for categories
316 * @return mixed category object or null if fails
317 */
318 function create_category_path($catpath, $delimiter='/') {
319 $catpath = clean_param($catpath, PARAM_PATH);
320 $catnames = explode($delimiter, $catpath);
321 $parent = 0;
322 $category = null;
323 if (FALSE !== preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches)){
324 $contextid = $this->translator->string_to_context($matches[1]);
325 array_shift($catnames);
326 } else {
327 $contextid = FALSE;
328 }
329 if ($this->contextfromfile && ($contextid !== FALSE)){
330 $context = get_context_instance_by_id($contextid);
331 require_capability('moodle/question:add', $context);
332 } else {
333 $context = get_context_instance_by_id($this->category->contextid);
334 }
335 foreach ($catnames as $catname) {
336 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) {
337 $parent = $category->id;
338 } else {
339 require_capability('moodle/question:managecategory', $context);
340 // create the new category
341 $category = new object;
342 $category->contextid = $context->id;
343 $category->name = $catname;
344 $category->info = '';
345 $category->parent = $parent;
346 $category->sortorder = 999;
347 $category->stamp = make_unique_id_code();
348 if (!($id = insert_record('question_categories', $category))) {
349 error( "cannot create new category - $catname" );
350 }
351 $category->id = $id;
352 $parent = $id;
353 }
354 }
355 return $category;
356 }
f3701561 357 /**
358 * Return complete file within an array, one item per line
359 * @param string filename name of file
360 * @return mixed contents array or false on failure
361 */
aca318e1 362 function readdata($filename) {
aca318e1 363 if (is_readable($filename)) {
364 $filearray = file($filename);
365
366 /// Check for Macintosh OS line returns (ie file on one line), and fix
367 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
368 return explode("\r", $filearray[0]);
369 } else {
370 return $filearray;
371 }
372 }
373 return false;
374 }
375
f3701561 376 /**
271e6dec 377 * Parses an array of lines into an array of questions,
378 * where each item is a question object as defined by
379 * readquestion(). Questions are defined as anything
f3701561 380 * between blank lines.
381 *
382 * If your format does not use blank lines as a delimiter
383 * then you will need to override this method. Even then
384 * try to use readquestion for each question
385 * @param array lines array of lines from readdata
386 * @return array array of question objects
387 */
aca318e1 388 function readquestions($lines) {
271e6dec 389
aca318e1 390 $questions = array();
391 $currentquestion = array();
392
393 foreach ($lines as $line) {
394 $line = trim($line);
395 if (empty($line)) {
396 if (!empty($currentquestion)) {
397 if ($question = $this->readquestion($currentquestion)) {
398 $questions[] = $question;
399 }
400 $currentquestion = array();
401 }
402 } else {
403 $currentquestion[] = $line;
404 }
405 }
406
407 if (!empty($currentquestion)) { // There may be a final question
408 if ($question = $this->readquestion($currentquestion)) {
409 $questions[] = $question;
410 }
411 }
412
413 return $questions;
414 }
415
416
f3701561 417 /**
418 * return an "empty" question
419 * Somewhere to specify question parameters that are not handled
420 * by import but are required db fields.
421 * This should not be overridden.
422 * @return object default question
271e6dec 423 */
aca318e1 424 function defaultquestion() {
b0679efa 425 global $CFG;
271e6dec 426
aca318e1 427 $question = new stdClass();
271e6dec 428 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
aca318e1 429 $question->defaultgrade = 1;
430 $question->image = "";
431 $question->usecase = 0;
432 $question->multiplier = array();
172f6d95 433 $question->generalfeedback = '';
08892d5b 434 $question->correctfeedback = '';
435 $question->partiallycorrectfeedback = '';
436 $question->incorrectfeedback = '';
5931ea94 437 $question->answernumbering = 'abc';
46013523 438 $question->penalty = 0.1;
aca318e1 439
5fd8f999 440 // this option in case the questiontypes class wants
441 // to know where the data came from
442 $question->export_process = true;
093414d2 443 $question->import_process = true;
5fd8f999 444
aca318e1 445 return $question;
446 }
447
f3701561 448 /**
271e6dec 449 * Given the data known to define a question in
450 * this format, this function converts it into a question
f3701561 451 * object suitable for processing and insertion into Moodle.
452 *
453 * If your format does not use blank lines to delimit questions
454 * (e.g. an XML format) you must override 'readquestions' too
455 * @param $lines mixed data that represents question
456 * @return object question object
457 */
aca318e1 458 function readquestion($lines) {
aca318e1 459
1e3d6fd8 460 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
461 echo "<p>$formatnotimplemented</p>";
aca318e1 462
463 return NULL;
464 }
465
f3701561 466 /**
467 * Override if any post-processing is required
468 * @return boolean success
469 */
aca318e1 470 function importpostprocess() {
aca318e1 471 return true;
472 }
473
f3701561 474 /**
475 * Import an image file encoded in base64 format
476 * @param string path path (in course data) to store picture
477 * @param string base64 encoded picture
478 * @return string filename (nb. collisions are handled)
479 */
d08e16b2 480 function importimagefile( $path, $base64 ) {
d08e16b2 481 global $CFG;
482
483 // all this to get the destination directory
484 // and filename!
485 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
486 $path_parts = pathinfo( $fullpath );
487 $destination = $path_parts['dirname'];
488 $file = clean_filename( $path_parts['basename'] );
489
71735794 490 // check if path exists
491 check_dir_exists($destination, true, true );
492
d08e16b2 493 // detect and fix any filename collision - get unique filename
271e6dec 494 $newfiles = resolve_filename_collisions( $destination, array($file) );
d08e16b2 495 $newfile = $newfiles[0];
496
497 // convert and save file contents
498 if (!$content = base64_decode( $base64 )) {
46013523 499 return '';
d08e16b2 500 }
501 $newfullpath = "$destination/$newfile";
502 if (!$fh = fopen( $newfullpath, 'w' )) {
46013523 503 return '';
d08e16b2 504 }
505 if (!fwrite( $fh, $content )) {
46013523 506 return '';
d08e16b2 507 }
508 fclose( $fh );
509
510 // return the (possibly) new filename
71735794 511 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
d08e16b2 512 return $newfile;
513 }
514
f3701561 515/*******************
516 * EXPORT FUNCTIONS
517 *******************/
aca318e1 518
271e6dec 519 /**
a41e3287 520 * Provide export functionality for plugin questiontypes
521 * Do not override
522 * @param name questiontype name
271e6dec 523 * @param question object data to export
a41e3287 524 * @param extra mixed any addition format specific data needed
525 * @return string the data to append to export or false if error (or unhandled)
526 */
527 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
528 global $QTYPES;
529
530 // work out the name of format in use
531 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
532 $methodname = "export_to_$formatname";
533
534 if (array_key_exists( $name, $QTYPES )) {
535 $qtype = $QTYPES[ $name ];
536 if (method_exists( $qtype, $methodname )) {
537 if ($data = $qtype->$methodname( $question, $this, $extra )) {
538 return $data;
539 }
540 }
541 }
542 return false;
543 }
544
f3701561 545 /**
546 * Return the files extension appropriate for this type
547 * override if you don't want .txt
548 * @return string file extension
549 */
aca318e1 550 function export_file_extension() {
aca318e1 551 return ".txt";
552 }
553
f3701561 554 /**
555 * Do any pre-processing that may be required
556 * @param boolean success
557 */
08892d5b 558 function exportpreprocess() {
aca318e1 559 return true;
560 }
561
f3701561 562 /**
563 * Enable any processing to be done on the content
564 * just prior to the file being saved
565 * default is to do nothing
566 * @param string output text
567 * @param string processed output text
568 */
aca318e1 569 function presave_process( $content ) {
aca318e1 570 return $content;
571 }
572
f3701561 573 /**
574 * Do the export
575 * For most types this should not need to be overrided
576 * @return boolean success
577 */
08892d5b 578 function exportprocess() {
aca318e1 579 global $CFG;
580
581 // create a directory for the exports (if not already existing)
1367cb8d 582 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
583 error( get_string('cannotcreatepath','quiz',$export_dir) );
aca318e1 584 }
1367cb8d 585 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 586
587 // get the questions (from database) in this category
588 // only get q's with no parents (no cloze subquestions specifically)
589 $questions = get_questions_category( $this->category, true );
590
1e3d6fd8 591 notify( get_string('exportingquestions','quiz') );
aca318e1 592 $count = 0;
593
594 // results are first written into string (and then to a file)
595 // so create/initialize the string here
596 $expout = "";
271e6dec 597
f1abd39f 598 // track which category questions are in
599 // if it changes we will record the category change in the output
600 // file if selected. 0 means that it will get printed before the 1st question
601 $trackcategory = 0;
aca318e1 602
603 // iterate through questions
604 foreach($questions as $question) {
271e6dec 605
a9b16aff 606 // do not export hidden questions
607 if (!empty($question->hidden)) {
608 continue;
609 }
610
611 // do not export random questions
612 if ($question->qtype==RANDOM) {
613 continue;
614 }
271e6dec 615
f1abd39f 616 // check if we need to record category change
617 if ($this->cattofile) {
618 if ($question->category != $trackcategory) {
271e6dec 619 $trackcategory = $question->category;
620 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
621
f1abd39f 622 // create 'dummy' question for category export
623 $dummyquestion = new object;
624 $dummyquestion->qtype = 'category';
625 $dummyquestion->category = $categoryname;
626 $dummyquestion->name = "switch category to $categoryname";
627 $dummyquestion->id = 0;
628 $dummyquestion->questiontextformat = '';
629 $expout .= $this->writequestion( $dummyquestion ) . "\n";
271e6dec 630 }
631 }
f1abd39f 632
633 // export the question displaying message
634 $count++;
5b0dc681 635 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
0647e82b 636 if (question_has_capability_on($question, 'view', $question->category)){
637 $expout .= $this->writequestion( $question ) . "\n";
638 }
a9b16aff 639 }
aca318e1 640
2c6d2c88 641 // continue path for following error checks
642 $course = $this->course;
643 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
644
645 // did we actually process anything
646 if ($count==0) {
647 print_error( 'noquestions','quiz',$continuepath );
648 }
649
aca318e1 650 // final pre-process on exported data
651 $expout = $this->presave_process( $expout );
271e6dec 652
aca318e1 653 // write file
08892d5b 654 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 655 if (!$fh=fopen($filepath,"w")) {
2c6d2c88 656 print_error( 'cannotopen','quiz',$continuepath,$filepath );
aca318e1 657 }
f1abd39f 658 if (!fwrite($fh, $expout, strlen($expout) )) {
2c6d2c88 659 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
aca318e1 660 }
661 fclose($fh);
aca318e1 662 return true;
663 }
271e6dec 664 /**
665 * get the category as a path (e.g., tom/dick/harry)
666 * @param int id the id of the most nested catgory
667 * @param string delimiter the delimiter you want
668 * @return string the path
669 */
670 function get_category_path($id, $delimiter='/', $includecontext = true) {
671 $path = '';
672 if (!$firstcategory = get_record('question_categories','id',$id)) {
673 print_error( "Error getting category record from db - $id" );
674 }
675 $category = $firstcategory;
676 $contextstring = $this->translator->context_to_string($category->contextid);
677 do {
678 $name = $category->name;
679 $id = $category->parent;
680 if (!empty($path)) {
681 $path = "{$name}{$delimiter}{$path}";
682 }
683 else {
684 $path = $name;
685 }
686 } while ($category = get_record( 'question_categories','id',$id ));
687
688 if ($includecontext){
689 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
690 }
691 return $path;
692 }
aca318e1 693
f3701561 694 /**
695 * Do an post-processing that may be required
696 * @return boolean success
697 */
aca318e1 698 function exportpostprocess() {
aca318e1 699 return true;
700 }
701
f3701561 702 /**
703 * convert a single question object into text output in the given
704 * format.
705 * This must be overriden
706 * @param object question question object
707 * @return mixed question export text or null if not implemented
708 */
aca318e1 709 function writequestion($question) {
1e3d6fd8 710 // if not overidden, then this is an error.
711 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
712 echo "<p>$formatnotimplemented</p>";
aca318e1 713 return NULL;
714 }
715
f3701561 716 /**
271e6dec 717 * get directory into which export is going
f3701561 718 * @return string file path
719 */
1367cb8d 720 function question_get_export_dir() {
721 $dirname = get_string("exportfilename","quiz");
722 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
723 return $path;
724 }
725
f3701561 726 /**
727 * where question specifies a moodle (text) format this
728 * performs the conversion.
729 */
5b0dc681 730 function format_question_text($question) {
731 $formatoptions = new stdClass;
732 $formatoptions->noclean = true;
733 $formatoptions->para = false;
734 if (empty($question->questiontextformat)) {
735 $format = FORMAT_MOODLE;
736 } else {
737 $format = $question->questiontextformat;
738 }
739 return format_text(stripslashes($question->questiontext), $format, $formatoptions);
740 }
271e6dec 741
742
aca318e1 743}
744
745?>