Issue:
[moodle-pu.git] / question / format.php
blob76220530f64553d57650aeb0c8273a4ff62ea71a
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 $contextfromfile = 0;
20 var $cattofile = 0;
21 var $contexttofile = 0;
22 var $questionids = array();
23 var $importerrors = 0;
24 var $stoponerror = true;
25 var $translator = null;
28 // functions to indicate import/export functionality
29 // override to return true if implemented
31 function provide_import() {
32 return false;
35 function provide_export() {
36 return false;
39 // Accessor methods
41 /**
42 * set the category
43 * @param object category the category object
45 function setCategory( $category ) {
46 $this->category = $category;
49 /**
50 * set the course class variable
51 * @param course object Moodle course variable
53 function setCourse( $course ) {
54 $this->course = $course;
56 /**
57 * set an array of contexts.
58 * @param array $contexts Moodle course variable
60 function setContexts($contexts) {
61 $this->contexts = $contexts;
62 $this->translator = new context_to_string_translator($this->contexts);
65 /**
66 * set the filename
67 * @param string filename name of file to import/export
69 function setFilename( $filename ) {
70 $this->filename = $filename;
73 /**
74 * set matchgrades
75 * @param string matchgrades error or nearest for grades
77 function setMatchgrades( $matchgrades ) {
78 $this->matchgrades = $matchgrades;
81 /**
82 * set catfromfile
83 * @param bool catfromfile allow categories embedded in import file
85 function setCatfromfile( $catfromfile ) {
86 $this->catfromfile = $catfromfile;
89 /**
90 * set contextfromfile
91 * @param bool $contextfromfile allow contexts embedded in import file
93 function setContextfromfile($contextfromfile) {
94 $this->contextfromfile = $contextfromfile;
97 /**
98 * set cattofile
99 * @param bool cattofile exports categories within export file
101 function setCattofile( $cattofile ) {
102 $this->cattofile = $cattofile;
105 * set contexttofile
106 * @param bool cattofile exports categories within export file
108 function setContexttofile($contexttofile) {
109 $this->contexttofile = $contexttofile;
113 * set stoponerror
114 * @param bool stoponerror stops database write if any errors reported
116 function setStoponerror( $stoponerror ) {
117 $this->stoponerror = $stoponerror;
120 /***********************
121 * IMPORTING FUNCTIONS
122 ***********************/
125 * Handle parsing error
127 function error( $message, $text='', $questionname='' ) {
128 $importerrorquestion = get_string('importerrorquestion','quiz');
130 echo "<div class=\"importerror\">\n";
131 echo "<strong>$importerrorquestion $questionname</strong>";
132 if (!empty($text)) {
133 $text = s($text);
134 echo "<blockquote>$text</blockquote>\n";
136 echo "<strong>$message</strong>\n";
137 echo "</div>";
139 $this->importerrors++;
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
150 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
151 global $QTYPES;
153 // work out what format we are using
154 $formatname = substr( get_class( $this ), strlen('qformat_'));
155 $methodname = "import_from_$formatname";
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;
166 return false;
170 * Perform any required pre-processing
171 * @return boolean success
173 function importpreprocess() {
174 return true;
178 * Process the file
179 * This method should not normally be overidden
180 * @return boolean success
182 function importprocess() {
183 global $USER;
185 // reset the timer in case file upload was slow
186 @set_time_limit();
188 // STAGE 1: Parse the file
189 notify( get_string('parsingquestions','quiz') );
191 if (! $lines = $this->readdata($this->filename)) {
192 notify( get_string('cannotread','quiz') );
193 return false;
196 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
197 notify( get_string('noquestionsinfile','quiz') );
198 return false;
201 // STAGE 2: Write data to database
202 notify( get_string('importingquestions','quiz',count($questions)) );
204 // check for errors before we continue
205 if ($this->stoponerror and ($this->importerrors>0)) {
206 return false;
209 // get list of valid answer grades
210 $grades = get_grade_options();
211 $gradeoptionsfull = $grades->gradeoptionsfull;
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;
226 else {
227 $fractions[$key] = $newfraction;
230 if (!$answersvalid) {
231 notify(get_string('matcherror', 'quiz'));
232 ++$gradeerrors;
233 continue;
235 else {
236 $question->fraction = $fractions;
239 $goodquestions[] = $question;
241 $questions = $goodquestions;
243 // check for errors before we continue
244 if ($this->stoponerror and ($gradeerrors>0)) {
245 return false;
248 // count number of questions processed
249 $count = 0;
251 foreach ($questions as $question) { // Process and store each question
253 // reset the php timeout
254 @set_time_limit();
256 // check for category modifiers
257 if ($question->qtype=='category') {
258 if ($this->catfromfile) {
259 // find/create category object
260 $catpath = $question->category;
261 $newcategory = $this->create_category_path( $catpath, '/');
262 if (!empty($newcategory)) {
263 $this->category = $newcategory;
266 continue;
269 $count++;
271 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
273 $question->category = $this->category->id;
274 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
276 $question->createdby = $USER->id;
277 $question->timecreated = time();
279 if (!$question->id = insert_record("question", $question)) {
280 error( get_string('cannotinsert','quiz') );
283 $this->questionids[] = $question->id;
285 // Now to save all the answers and type-specific options
287 global $QTYPES;
288 $result = $QTYPES[$question->qtype]
289 ->save_question_options($question);
291 if (!empty($result->error)) {
292 notify($result->error);
293 return false;
296 if (!empty($result->notice)) {
297 notify($result->notice);
298 return true;
301 // Give the question a unique version stamp determined by question_hash()
302 set_field('question', 'version', question_hash($question), 'id', $question->id);
304 return true;
307 * find and/or create the category described by a delimited list
308 * e.g. $course$/tom/dick/harry or tom/dick/harry
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.
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
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;
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);
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" );
351 $category->id = $id;
352 $parent = $id;
355 return $category;
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
362 function readdata($filename) {
363 if (is_readable($filename)) {
364 $filearray = file($filename);
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;
373 return false;
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
380 * between blank lines.
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
388 function readquestions($lines) {
390 $questions = array();
391 $currentquestion = array();
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;
400 $currentquestion = array();
402 } else {
403 $currentquestion[] = $line;
407 if (!empty($currentquestion)) { // There may be a final question
408 if ($question = $this->readquestion($currentquestion)) {
409 $questions[] = $question;
413 return $questions;
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
424 function defaultquestion() {
425 global $CFG;
427 $question = new stdClass();
428 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
429 $question->defaultgrade = 1;
430 $question->image = "";
431 $question->usecase = 0;
432 $question->multiplier = array();
433 $question->generalfeedback = '';
434 $question->correctfeedback = '';
435 $question->partiallycorrectfeedback = '';
436 $question->incorrectfeedback = '';
437 $question->answernumbering = 'abc';
438 $question->penalty = 0.1;
440 // this option in case the questiontypes class wants
441 // to know where the data came from
442 $question->export_process = true;
443 $question->import_process = true;
445 return $question;
449 * Given the data known to define a question in
450 * this format, this function converts it into a question
451 * object suitable for processing and insertion into Moodle.
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
458 function readquestion($lines) {
460 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
461 echo "<p>$formatnotimplemented</p>";
463 return NULL;
467 * Override if any post-processing is required
468 * @return boolean success
470 function importpostprocess() {
471 return true;
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)
480 function importimagefile( $path, $base64 ) {
481 global $CFG;
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'] );
490 // check if path exists
491 check_dir_exists($destination, true, true );
493 // detect and fix any filename collision - get unique filename
494 $newfiles = resolve_filename_collisions( $destination, array($file) );
495 $newfile = $newfiles[0];
497 // convert and save file contents
498 if (!$content = base64_decode( $base64 )) {
499 return '';
501 $newfullpath = "$destination/$newfile";
502 if (!$fh = fopen( $newfullpath, 'w' )) {
503 return '';
505 if (!fwrite( $fh, $content )) {
506 return '';
508 fclose( $fh );
510 // return the (possibly) new filename
511 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
512 return $newfile;
515 /*******************
516 * EXPORT FUNCTIONS
517 *******************/
520 * Provide export functionality for plugin questiontypes
521 * Do not override
522 * @param name questiontype name
523 * @param question object data to export
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)
527 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
528 global $QTYPES;
530 // work out the name of format in use
531 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
532 $methodname = "export_to_$formatname";
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;
542 return false;
546 * Return the files extension appropriate for this type
547 * override if you don't want .txt
548 * @return string file extension
550 function export_file_extension() {
551 return ".txt";
555 * Do any pre-processing that may be required
556 * @param boolean success
558 function exportpreprocess() {
559 return true;
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
569 function presave_process( $content ) {
570 return $content;
574 * Do the export
575 * For most types this should not need to be overrided
576 * @return boolean success
578 function exportprocess() {
579 global $CFG;
581 // create a directory for the exports (if not already existing)
582 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
583 error( get_string('cannotcreatepath','quiz',$export_dir) );
585 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
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 );
591 notify( get_string('exportingquestions','quiz') );
592 if (!count($questions)) {
593 notify( get_string('noquestions','quiz') );
594 return false;
596 $count = 0;
598 // results are first written into string (and then to a file)
599 // so create/initialize the string here
600 $expout = "";
602 // track which category questions are in
603 // if it changes we will record the category change in the output
604 // file if selected. 0 means that it will get printed before the 1st question
605 $trackcategory = 0;
607 // iterate through questions
608 foreach($questions as $question) {
610 // do not export hidden questions
611 if (!empty($question->hidden)) {
612 continue;
615 // do not export random questions
616 if ($question->qtype==RANDOM) {
617 continue;
620 // check if we need to record category change
621 if ($this->cattofile) {
622 if ($question->category != $trackcategory) {
623 $trackcategory = $question->category;
624 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
626 // create 'dummy' question for category export
627 $dummyquestion = new object;
628 $dummyquestion->qtype = 'category';
629 $dummyquestion->category = $categoryname;
630 $dummyquestion->name = "switch category to $categoryname";
631 $dummyquestion->id = 0;
632 $dummyquestion->questiontextformat = '';
633 $expout .= $this->writequestion( $dummyquestion ) . "\n";
637 // export the question displaying message
638 $count++;
639 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
640 if (question_has_capability_on($question, 'view', $question->category)){
641 $expout .= $this->writequestion( $question ) . "\n";
645 // final pre-process on exported data
646 $expout = $this->presave_process( $expout );
648 // write file
649 $filepath = $path."/".$this->filename . $this->export_file_extension();
650 if (!$fh=fopen($filepath,"w")) {
651 error( get_string('cannotopen','quiz',$filepath) );
653 if (!fwrite($fh, $expout, strlen($expout) )) {
654 error( get_string('cannotwrite','quiz',$filepath) );
656 fclose($fh);
657 return true;
660 * get the category as a path (e.g., tom/dick/harry)
661 * @param int id the id of the most nested catgory
662 * @param string delimiter the delimiter you want
663 * @return string the path
665 function get_category_path($id, $delimiter='/', $includecontext = true) {
666 $path = '';
667 if (!$firstcategory = get_record('question_categories','id',$id)) {
668 print_error( "Error getting category record from db - $id" );
670 $category = $firstcategory;
671 $contextstring = $this->translator->context_to_string($category->contextid);
672 do {
673 $name = $category->name;
674 $id = $category->parent;
675 if (!empty($path)) {
676 $path = "{$name}{$delimiter}{$path}";
678 else {
679 $path = $name;
681 } while ($category = get_record( 'question_categories','id',$id ));
683 if ($includecontext){
684 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
686 return $path;
690 * Do an post-processing that may be required
691 * @return boolean success
693 function exportpostprocess() {
694 return true;
698 * convert a single question object into text output in the given
699 * format.
700 * This must be overriden
701 * @param object question question object
702 * @return mixed question export text or null if not implemented
704 function writequestion($question) {
705 // if not overidden, then this is an error.
706 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
707 echo "<p>$formatnotimplemented</p>";
708 return NULL;
712 * get directory into which export is going
713 * @return string file path
715 function question_get_export_dir() {
716 $dirname = get_string("exportfilename","quiz");
717 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
718 return $path;
722 * where question specifies a moodle (text) format this
723 * performs the conversion.
725 function format_question_text($question) {
726 $formatoptions = new stdClass;
727 $formatoptions->noclean = true;
728 $formatoptions->para = false;
729 if (empty($question->questiontextformat)) {
730 $format = FORMAT_MOODLE;
731 } else {
732 $format = $question->questiontextformat;
734 return format_text(stripslashes($question->questiontext), $format, $formatoptions);