Typo: should be $COURSE not $course it seems
[moodle-linuxchix.git] / question / format.php
blob0222c6c4b119e778a7fcb61d3030919ab1529715
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 $count = 0;
215 foreach ($questions as $question) { // Process and store each question
217 // reset the php timeout
218 @set_time_limit();
220 // check for category modifiers
221 if ($question->qtype=='category') {
222 if ($this->catfromfile) {
223 // find/create category object
224 $catpath = $question->category;
225 $newcategory = $this->create_category_path( $catpath, '/');
226 if (!empty($newcategory)) {
227 $this->category = $newcategory;
230 continue;
233 $count++;
235 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
237 // check for answer grades validity (must match fixed list of grades)
238 if (!empty($question->fraction) and (is_array($question->fraction))) {
239 $fractions = $question->fraction;
240 $answersvalid = true; // in case they are!
241 foreach ($fractions as $key => $fraction) {
242 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
243 if ($newfraction===false) {
244 $answersvalid = false;
246 else {
247 $fractions[$key] = $newfraction;
250 if (!$answersvalid) {
251 notify(get_string('matcherror', 'quiz'));
252 continue;
254 else {
255 $question->fraction = $fractions;
259 $question->category = $this->category->id;
260 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
262 $question->createdby = $USER->id;
263 $question->timecreated = time();
265 if (!$question->id = insert_record("question", $question)) {
266 error( get_string('cannotinsert','quiz') );
269 $this->questionids[] = $question->id;
271 // Now to save all the answers and type-specific options
273 global $QTYPES;
274 $result = $QTYPES[$question->qtype]
275 ->save_question_options($question);
277 if (!empty($result->error)) {
278 notify($result->error);
279 return false;
282 if (!empty($result->notice)) {
283 notify($result->notice);
284 return true;
287 // Give the question a unique version stamp determined by question_hash()
288 set_field('question', 'version', question_hash($question), 'id', $question->id);
290 return true;
293 * find and/or create the category described by a delimited list
294 * e.g. $course$/tom/dick/harry or tom/dick/harry
296 * removes any context string no matter whether $getcontext is set
297 * but if $getcontext is set then ignore the context and use selected category context.
299 * @param string catpath delimited category path
300 * @param string delimiter path delimiting character
301 * @param int courseid course to search for categories
302 * @return mixed category object or null if fails
304 function create_category_path($catpath, $delimiter='/') {
305 $catpath = clean_param($catpath, PARAM_PATH);
306 $catnames = explode($delimiter, $catpath);
307 $parent = 0;
308 $category = null;
309 if (FALSE !== preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches)){
310 $contextid = $this->translator->string_to_context($matches[1]);
311 array_shift($catnames);
312 } else {
313 $contextid = FALSE;
315 if ($this->contextfromfile && ($contextid !== FALSE)){
316 $context = get_context_instance_by_id($contextid);
317 require_capability('moodle/question:add', $context);
318 } else {
319 $context = get_context_instance_by_id($this->category->contextid);
321 foreach ($catnames as $catname) {
322 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) {
323 $parent = $category->id;
324 } else {
325 require_capability('moodle/question:managecategory', $context);
326 // create the new category
327 $category = new object;
328 $category->contextid = $context->id;
329 $category->name = $catname;
330 $category->info = '';
331 $category->parent = $parent;
332 $category->sortorder = 999;
333 $category->stamp = make_unique_id_code();
334 if (!($id = insert_record('question_categories', $category))) {
335 error( "cannot create new category - $catname" );
337 $category->id = $id;
338 $parent = $id;
341 return $category;
344 * Return complete file within an array, one item per line
345 * @param string filename name of file
346 * @return mixed contents array or false on failure
348 function readdata($filename) {
349 if (is_readable($filename)) {
350 $filearray = file($filename);
352 /// Check for Macintosh OS line returns (ie file on one line), and fix
353 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
354 return explode("\r", $filearray[0]);
355 } else {
356 return $filearray;
359 return false;
363 * Parses an array of lines into an array of questions,
364 * where each item is a question object as defined by
365 * readquestion(). Questions are defined as anything
366 * between blank lines.
368 * If your format does not use blank lines as a delimiter
369 * then you will need to override this method. Even then
370 * try to use readquestion for each question
371 * @param array lines array of lines from readdata
372 * @return array array of question objects
374 function readquestions($lines) {
376 $questions = array();
377 $currentquestion = array();
379 foreach ($lines as $line) {
380 $line = trim($line);
381 if (empty($line)) {
382 if (!empty($currentquestion)) {
383 if ($question = $this->readquestion($currentquestion)) {
384 $questions[] = $question;
386 $currentquestion = array();
388 } else {
389 $currentquestion[] = $line;
393 if (!empty($currentquestion)) { // There may be a final question
394 if ($question = $this->readquestion($currentquestion)) {
395 $questions[] = $question;
399 return $questions;
404 * return an "empty" question
405 * Somewhere to specify question parameters that are not handled
406 * by import but are required db fields.
407 * This should not be overridden.
408 * @return object default question
410 function defaultquestion() {
411 global $CFG;
413 $question = new stdClass();
414 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
415 $question->defaultgrade = 1;
416 $question->image = "";
417 $question->usecase = 0;
418 $question->multiplier = array();
419 $question->generalfeedback = '';
420 $question->correctfeedback = '';
421 $question->partiallycorrectfeedback = '';
422 $question->incorrectfeedback = '';
423 $question->answernumbering = 'abc';
424 $question->penalty = 0.1;
426 // this option in case the questiontypes class wants
427 // to know where the data came from
428 $question->export_process = true;
429 $question->import_process = true;
431 return $question;
435 * Given the data known to define a question in
436 * this format, this function converts it into a question
437 * object suitable for processing and insertion into Moodle.
439 * If your format does not use blank lines to delimit questions
440 * (e.g. an XML format) you must override 'readquestions' too
441 * @param $lines mixed data that represents question
442 * @return object question object
444 function readquestion($lines) {
446 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
447 echo "<p>$formatnotimplemented</p>";
449 return NULL;
453 * Override if any post-processing is required
454 * @return boolean success
456 function importpostprocess() {
457 return true;
461 * Import an image file encoded in base64 format
462 * @param string path path (in course data) to store picture
463 * @param string base64 encoded picture
464 * @return string filename (nb. collisions are handled)
466 function importimagefile( $path, $base64 ) {
467 global $CFG;
469 // all this to get the destination directory
470 // and filename!
471 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
472 $path_parts = pathinfo( $fullpath );
473 $destination = $path_parts['dirname'];
474 $file = clean_filename( $path_parts['basename'] );
476 // check if path exists
477 check_dir_exists($destination, true, true );
479 // detect and fix any filename collision - get unique filename
480 $newfiles = resolve_filename_collisions( $destination, array($file) );
481 $newfile = $newfiles[0];
483 // convert and save file contents
484 if (!$content = base64_decode( $base64 )) {
485 return '';
487 $newfullpath = "$destination/$newfile";
488 if (!$fh = fopen( $newfullpath, 'w' )) {
489 return '';
491 if (!fwrite( $fh, $content )) {
492 return '';
494 fclose( $fh );
496 // return the (possibly) new filename
497 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
498 return $newfile;
501 /*******************
502 * EXPORT FUNCTIONS
503 *******************/
506 * Provide export functionality for plugin questiontypes
507 * Do not override
508 * @param name questiontype name
509 * @param question object data to export
510 * @param extra mixed any addition format specific data needed
511 * @return string the data to append to export or false if error (or unhandled)
513 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
514 global $QTYPES;
516 // work out the name of format in use
517 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
518 $methodname = "export_to_$formatname";
520 if (array_key_exists( $name, $QTYPES )) {
521 $qtype = $QTYPES[ $name ];
522 if (method_exists( $qtype, $methodname )) {
523 if ($data = $qtype->$methodname( $question, $this, $extra )) {
524 return $data;
528 return false;
532 * Return the files extension appropriate for this type
533 * override if you don't want .txt
534 * @return string file extension
536 function export_file_extension() {
537 return ".txt";
541 * Do any pre-processing that may be required
542 * @param boolean success
544 function exportpreprocess() {
545 return true;
549 * Enable any processing to be done on the content
550 * just prior to the file being saved
551 * default is to do nothing
552 * @param string output text
553 * @param string processed output text
555 function presave_process( $content ) {
556 return $content;
560 * Do the export
561 * For most types this should not need to be overrided
562 * @return boolean success
564 function exportprocess() {
565 global $CFG;
567 // create a directory for the exports (if not already existing)
568 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
569 error( get_string('cannotcreatepath','quiz',$export_dir) );
571 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
573 // get the questions (from database) in this category
574 // only get q's with no parents (no cloze subquestions specifically)
575 $questions = get_questions_category( $this->category, true );
577 notify( get_string('exportingquestions','quiz') );
578 if (!count($questions)) {
579 notify( get_string('noquestions','quiz') );
580 return false;
582 $count = 0;
584 // results are first written into string (and then to a file)
585 // so create/initialize the string here
586 $expout = "";
588 // track which category questions are in
589 // if it changes we will record the category change in the output
590 // file if selected. 0 means that it will get printed before the 1st question
591 $trackcategory = 0;
593 // iterate through questions
594 foreach($questions as $question) {
596 // do not export hidden questions
597 if (!empty($question->hidden)) {
598 continue;
601 // do not export random questions
602 if ($question->qtype==RANDOM) {
603 continue;
606 // check if we need to record category change
607 if ($this->cattofile) {
608 if ($question->category != $trackcategory) {
609 $trackcategory = $question->category;
610 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
612 // create 'dummy' question for category export
613 $dummyquestion = new object;
614 $dummyquestion->qtype = 'category';
615 $dummyquestion->category = $categoryname;
616 $dummyquestion->name = "switch category to $categoryname";
617 $dummyquestion->id = 0;
618 $dummyquestion->questiontextformat = '';
619 $expout .= $this->writequestion( $dummyquestion ) . "\n";
623 // export the question displaying message
624 $count++;
625 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
626 $expout .= $this->writequestion( $question ) . "\n";
629 // final pre-process on exported data
630 $expout = $this->presave_process( $expout );
632 // write file
633 $filepath = $path."/".$this->filename . $this->export_file_extension();
634 if (!$fh=fopen($filepath,"w")) {
635 error( get_string('cannotopen','quiz',$filepath) );
637 if (!fwrite($fh, $expout, strlen($expout) )) {
638 error( get_string('cannotwrite','quiz',$filepath) );
640 fclose($fh);
641 return true;
644 * get the category as a path (e.g., tom/dick/harry)
645 * @param int id the id of the most nested catgory
646 * @param string delimiter the delimiter you want
647 * @return string the path
649 function get_category_path($id, $delimiter='/', $includecontext = true) {
650 $path = '';
651 if (!$firstcategory = get_record('question_categories','id',$id)) {
652 print_error( "Error getting category record from db - $id" );
654 $category = $firstcategory;
655 $contextstring = $this->translator->context_to_string($category->contextid);
656 do {
657 $name = $category->name;
658 $id = $category->parent;
659 if (!empty($path)) {
660 $path = "{$name}{$delimiter}{$path}";
662 else {
663 $path = $name;
665 } while ($category = get_record( 'question_categories','id',$id ));
667 if ($includecontext){
668 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
670 return $path;
674 * Do an post-processing that may be required
675 * @return boolean success
677 function exportpostprocess() {
678 return true;
682 * convert a single question object into text output in the given
683 * format.
684 * This must be overriden
685 * @param object question question object
686 * @return mixed question export text or null if not implemented
688 function writequestion($question) {
689 // if not overidden, then this is an error.
690 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
691 echo "<p>$formatnotimplemented</p>";
692 return NULL;
696 * get directory into which export is going
697 * @return string file path
699 function question_get_export_dir() {
700 $dirname = get_string("exportfilename","quiz");
701 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
702 return $path;
706 * where question specifies a moodle (text) format this
707 * performs the conversion.
709 function format_question_text($question) {
710 $formatoptions = new stdClass;
711 $formatoptions->noclean = true;
712 $formatoptions->para = false;
713 if (empty($question->questiontextformat)) {
714 $format = FORMAT_MOODLE;
715 } else {
716 $format = $question->questiontextformat;
718 return format_text(stripslashes($question->questiontext), $format, $formatoptions);