Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / question / format.php
blobdddaa3a522a5f7e97c66a30721fb3a5202607331
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 $questions = array();
16 var $course = NULL;
17 var $filename = '';
18 var $matchgrades = 'error';
19 var $catfromfile = 0;
20 var $contextfromfile = 0;
21 var $cattofile = 0;
22 var $contexttofile = 0;
23 var $questionids = array();
24 var $importerrors = 0;
25 var $stoponerror = true;
26 var $translator = null;
27 var $canaccessbackupdata = true;
30 // functions to indicate import/export functionality
31 // override to return true if implemented
33 function provide_import() {
34 return false;
37 function provide_export() {
38 return false;
41 // Accessor methods
43 /**
44 * set the category
45 * @param object category the category object
47 function setCategory( $category ) {
48 if (count($this->questions)){
49 debugging('You shouldn\'t call setCategory after setQuestions');
51 $this->category = $category;
54 /**
55 * Set the specific questions to export. Should not include questions with
56 * parents (sub questions of cloze question type).
57 * Only used for question export.
58 * @param array of question objects
60 function setQuestions( $questions ) {
61 if ($this->category !== null){
62 debugging('You shouldn\'t call setQuestions after setCategory');
64 $this->questions = $questions;
67 /**
68 * set the course class variable
69 * @param course object Moodle course variable
71 function setCourse( $course ) {
72 $this->course = $course;
74 /**
75 * set an array of contexts.
76 * @param array $contexts Moodle course variable
78 function setContexts($contexts) {
79 $this->contexts = $contexts;
80 $this->translator = new context_to_string_translator($this->contexts);
83 /**
84 * set the filename
85 * @param string filename name of file to import/export
87 function setFilename( $filename ) {
88 $this->filename = $filename;
91 /**
92 * set matchgrades
93 * @param string matchgrades error or nearest for grades
95 function setMatchgrades( $matchgrades ) {
96 $this->matchgrades = $matchgrades;
99 /**
100 * set catfromfile
101 * @param bool catfromfile allow categories embedded in import file
103 function setCatfromfile( $catfromfile ) {
104 $this->catfromfile = $catfromfile;
108 * set contextfromfile
109 * @param bool $contextfromfile allow contexts embedded in import file
111 function setContextfromfile($contextfromfile) {
112 $this->contextfromfile = $contextfromfile;
116 * set cattofile
117 * @param bool cattofile exports categories within export file
119 function setCattofile( $cattofile ) {
120 $this->cattofile = $cattofile;
123 * set contexttofile
124 * @param bool cattofile exports categories within export file
126 function setContexttofile($contexttofile) {
127 $this->contexttofile = $contexttofile;
131 * set stoponerror
132 * @param bool stoponerror stops database write if any errors reported
134 function setStoponerror( $stoponerror ) {
135 $this->stoponerror = $stoponerror;
139 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
140 * where export files are saved.
142 function set_can_access_backupdata($canaccess) {
143 $this->canaccessbackupdata = $canaccess;
146 /***********************
147 * IMPORTING FUNCTIONS
148 ***********************/
151 * Handle parsing error
153 function error( $message, $text='', $questionname='' ) {
154 $importerrorquestion = get_string('importerrorquestion','quiz');
156 echo "<div class=\"importerror\">\n";
157 echo "<strong>$importerrorquestion $questionname</strong>";
158 if (!empty($text)) {
159 $text = s($text);
160 echo "<blockquote>$text</blockquote>\n";
162 echo "<strong>$message</strong>\n";
163 echo "</div>";
165 $this->importerrors++;
169 * Import for questiontype plugins
170 * Do not override.
171 * @param data mixed The segment of data containing the question
172 * @param question object processed (so far) by standard import code if appropriate
173 * @param extra mixed any additional format specific data that may be passed by the format
174 * @return object question object suitable for save_options() or false if cannot handle
176 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
177 global $QTYPES;
179 // work out what format we are using
180 $formatname = substr( get_class( $this ), strlen('qformat_'));
181 $methodname = "import_from_$formatname";
183 // loop through installed questiontypes checking for
184 // function to handle this question
185 foreach ($QTYPES as $qtype) {
186 if (method_exists( $qtype, $methodname)) {
187 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
188 return $question;
192 return false;
196 * Perform any required pre-processing
197 * @return boolean success
199 function importpreprocess() {
200 return true;
204 * Process the file
205 * This method should not normally be overidden
206 * @return boolean success
208 function importprocess() {
209 global $USER;
211 // reset the timer in case file upload was slow
212 @set_time_limit();
214 // STAGE 1: Parse the file
215 notify( get_string('parsingquestions','quiz') );
217 if (! $lines = $this->readdata($this->filename)) {
218 notify( get_string('cannotread','quiz') );
219 return false;
222 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
223 notify( get_string('noquestionsinfile','quiz') );
224 return false;
227 // STAGE 2: Write data to database
228 notify( get_string('importingquestions','quiz',$this->count_questions($questions)) );
230 // check for errors before we continue
231 if ($this->stoponerror and ($this->importerrors>0)) {
232 return false;
235 // get list of valid answer grades
236 $grades = get_grade_options();
237 $gradeoptionsfull = $grades->gradeoptionsfull;
239 // check answer grades are valid
240 // (now need to do this here because of 'stop on error': MDL-10689)
241 $gradeerrors = 0;
242 $goodquestions = array();
243 foreach ($questions as $question) {
244 if (!empty($question->fraction) and (is_array($question->fraction))) {
245 $fractions = $question->fraction;
246 $answersvalid = true; // in case they are!
247 foreach ($fractions as $key => $fraction) {
248 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
249 if ($newfraction===false) {
250 $answersvalid = false;
252 else {
253 $fractions[$key] = $newfraction;
256 if (!$answersvalid) {
257 notify(get_string('matcherror', 'quiz'));
258 ++$gradeerrors;
259 continue;
261 else {
262 $question->fraction = $fractions;
265 $goodquestions[] = $question;
267 $questions = $goodquestions;
269 // check for errors before we continue
270 if ($this->stoponerror and ($gradeerrors>0)) {
271 return false;
274 // count number of questions processed
275 $count = 0;
277 foreach ($questions as $question) { // Process and store each question
279 // reset the php timeout
280 @set_time_limit();
282 // check for category modifiers
283 if ($question->qtype=='category') {
284 if ($this->catfromfile) {
285 // find/create category object
286 $catpath = $question->category;
287 $newcategory = $this->create_category_path( $catpath, '/');
288 if (!empty($newcategory)) {
289 $this->category = $newcategory;
292 continue;
295 $count++;
297 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
299 $question->category = $this->category->id;
300 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
302 $question->createdby = $USER->id;
303 $question->timecreated = time();
305 if (!$question->id = insert_record("question", $question)) {
306 error( get_string('cannotinsert','quiz') );
309 $this->questionids[] = $question->id;
311 // Now to save all the answers and type-specific options
313 global $QTYPES;
314 $result = $QTYPES[$question->qtype]
315 ->save_question_options($question);
317 if (!empty($result->error)) {
318 notify($result->error);
319 return false;
322 if (!empty($result->notice)) {
323 notify($result->notice);
324 return true;
327 // Give the question a unique version stamp determined by question_hash()
328 set_field('question', 'version', question_hash($question), 'id', $question->id);
330 return true;
333 * Count all non-category questions in the questions array.
335 * @param array questions An array of question objects.
336 * @return int The count.
339 function count_questions($questions) {
340 $count = 0;
341 if (!is_array($questions)) {
342 return $count;
344 foreach ($questions as $question) {
345 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
346 continue;
348 $count++;
350 return $count;
354 * find and/or create the category described by a delimited list
355 * e.g. $course$/tom/dick/harry or tom/dick/harry
357 * removes any context string no matter whether $getcontext is set
358 * but if $getcontext is set then ignore the context and use selected category context.
360 * @param string catpath delimited category path
361 * @param string delimiter path delimiting character
362 * @param int courseid course to search for categories
363 * @return mixed category object or null if fails
365 function create_category_path($catpath, $delimiter='/') {
366 $catpath = clean_param($catpath, PARAM_PATH);
367 $catnames = explode($delimiter, $catpath);
368 $parent = 0;
369 $category = null;
371 // check for context id in path, it might not be there in pre 1.9 exports
372 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
373 if ($matchcount==1) {
374 $contextid = $this->translator->string_to_context($matches[1]);
375 array_shift($catnames);
376 } else {
377 $contextid = FALSE;
379 if ($this->contextfromfile && ($contextid !== FALSE)){
380 $context = get_context_instance_by_id($contextid);
381 require_capability('moodle/question:add', $context);
382 } else {
383 $context = get_context_instance_by_id($this->category->contextid);
385 foreach ($catnames as $catname) {
386 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) {
387 $parent = $category->id;
388 } else {
389 require_capability('moodle/question:managecategory', $context);
390 // create the new category
391 $category = new object;
392 $category->contextid = $context->id;
393 $category->name = $catname;
394 $category->info = '';
395 $category->parent = $parent;
396 $category->sortorder = 999;
397 $category->stamp = make_unique_id_code();
398 if (!($id = insert_record('question_categories', $category))) {
399 error( "cannot create new category - $catname" );
401 $category->id = $id;
402 $parent = $id;
405 return $category;
409 * Return complete file within an array, one item per line
410 * @param string filename name of file
411 * @return mixed contents array or false on failure
413 function readdata($filename) {
414 if (is_readable($filename)) {
415 $filearray = file($filename);
417 /// Check for Macintosh OS line returns (ie file on one line), and fix
418 if (ereg("\r", $filearray[0]) AND !ereg("\n", $filearray[0])) {
419 return explode("\r", $filearray[0]);
420 } else {
421 return $filearray;
424 return false;
428 * Parses an array of lines into an array of questions,
429 * where each item is a question object as defined by
430 * readquestion(). Questions are defined as anything
431 * between blank lines.
433 * If your format does not use blank lines as a delimiter
434 * then you will need to override this method. Even then
435 * try to use readquestion for each question
436 * @param array lines array of lines from readdata
437 * @return array array of question objects
439 function readquestions($lines) {
441 $questions = array();
442 $currentquestion = array();
444 foreach ($lines as $line) {
445 $line = trim($line);
446 if (empty($line)) {
447 if (!empty($currentquestion)) {
448 if ($question = $this->readquestion($currentquestion)) {
449 $questions[] = $question;
451 $currentquestion = array();
453 } else {
454 $currentquestion[] = $line;
458 if (!empty($currentquestion)) { // There may be a final question
459 if ($question = $this->readquestion($currentquestion)) {
460 $questions[] = $question;
464 return $questions;
469 * return an "empty" question
470 * Somewhere to specify question parameters that are not handled
471 * by import but are required db fields.
472 * This should not be overridden.
473 * @return object default question
475 function defaultquestion() {
476 global $CFG;
478 $question = new stdClass();
479 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
480 $question->defaultgrade = 1;
481 $question->image = "";
482 $question->usecase = 0;
483 $question->multiplier = array();
484 $question->generalfeedback = '';
485 $question->correctfeedback = '';
486 $question->partiallycorrectfeedback = '';
487 $question->incorrectfeedback = '';
488 $question->answernumbering = 'abc';
489 $question->penalty = 0.1;
490 $question->length = 1;
492 // this option in case the questiontypes class wants
493 // to know where the data came from
494 $question->export_process = true;
495 $question->import_process = true;
497 return $question;
501 * Given the data known to define a question in
502 * this format, this function converts it into a question
503 * object suitable for processing and insertion into Moodle.
505 * If your format does not use blank lines to delimit questions
506 * (e.g. an XML format) you must override 'readquestions' too
507 * @param $lines mixed data that represents question
508 * @return object question object
510 function readquestion($lines) {
512 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
513 echo "<p>$formatnotimplemented</p>";
515 return NULL;
519 * Override if any post-processing is required
520 * @return boolean success
522 function importpostprocess() {
523 return true;
527 * Import an image file encoded in base64 format
528 * @param string path path (in course data) to store picture
529 * @param string base64 encoded picture
530 * @return string filename (nb. collisions are handled)
532 function importimagefile( $path, $base64 ) {
533 global $CFG;
535 // all this to get the destination directory
536 // and filename!
537 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
538 $path_parts = pathinfo( $fullpath );
539 $destination = $path_parts['dirname'];
540 $file = clean_filename( $path_parts['basename'] );
542 // check if path exists
543 check_dir_exists($destination, true, true );
545 // detect and fix any filename collision - get unique filename
546 $newfiles = resolve_filename_collisions( $destination, array($file) );
547 $newfile = $newfiles[0];
549 // convert and save file contents
550 if (!$content = base64_decode( $base64 )) {
551 return '';
553 $newfullpath = "$destination/$newfile";
554 if (!$fh = fopen( $newfullpath, 'w' )) {
555 return '';
557 if (!fwrite( $fh, $content )) {
558 return '';
560 fclose( $fh );
562 // return the (possibly) new filename
563 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
564 return $newfile;
568 /*******************
569 * EXPORT FUNCTIONS
570 *******************/
573 * Provide export functionality for plugin questiontypes
574 * Do not override
575 * @param name questiontype name
576 * @param question object data to export
577 * @param extra mixed any addition format specific data needed
578 * @return string the data to append to export or false if error (or unhandled)
580 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
581 global $QTYPES;
583 // work out the name of format in use
584 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
585 $methodname = "export_to_$formatname";
587 if (array_key_exists( $name, $QTYPES )) {
588 $qtype = $QTYPES[ $name ];
589 if (method_exists( $qtype, $methodname )) {
590 if ($data = $qtype->$methodname( $question, $this, $extra )) {
591 return $data;
595 return false;
599 * Return the files extension appropriate for this type
600 * override if you don't want .txt
601 * @return string file extension
603 function export_file_extension() {
604 return ".txt";
608 * Do any pre-processing that may be required
609 * @param boolean success
611 function exportpreprocess() {
612 return true;
616 * Enable any processing to be done on the content
617 * just prior to the file being saved
618 * default is to do nothing
619 * @param string output text
620 * @param string processed output text
622 function presave_process( $content ) {
623 return $content;
627 * Do the export
628 * For most types this should not need to be overrided
629 * @return boolean success
631 function exportprocess() {
632 global $CFG;
634 // create a directory for the exports (if not already existing)
635 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
636 error( get_string('cannotcreatepath','quiz',$export_dir) );
638 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
640 // get the questions (from database) in this category
641 // only get q's with no parents (no cloze subquestions specifically)
642 if ($this->category){
643 $questions = get_questions_category( $this->category, true );
644 } else {
645 $questions = $this->questions;
648 notify( get_string('exportingquestions','quiz') );
649 $count = 0;
651 // results are first written into string (and then to a file)
652 // so create/initialize the string here
653 $expout = "";
655 // track which category questions are in
656 // if it changes we will record the category change in the output
657 // file if selected. 0 means that it will get printed before the 1st question
658 $trackcategory = 0;
660 // iterate through questions
661 foreach($questions as $question) {
663 // do not export hidden questions
664 if (!empty($question->hidden)) {
665 continue;
668 // do not export random questions
669 if ($question->qtype==RANDOM) {
670 continue;
673 // check if we need to record category change
674 if ($this->cattofile) {
675 if ($question->category != $trackcategory) {
676 $trackcategory = $question->category;
677 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
679 // create 'dummy' question for category export
680 $dummyquestion = new object;
681 $dummyquestion->qtype = 'category';
682 $dummyquestion->category = $categoryname;
683 $dummyquestion->name = "switch category to $categoryname";
684 $dummyquestion->id = 0;
685 $dummyquestion->questiontextformat = '';
686 $expout .= $this->writequestion( $dummyquestion ) . "\n";
690 // export the question displaying message
691 $count++;
692 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
693 if (question_has_capability_on($question, 'view', $question->category)){
694 $expout .= $this->writequestion( $question ) . "\n";
698 // continue path for following error checks
699 $course = $this->course;
700 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
702 // did we actually process anything
703 if ($count==0) {
704 print_error( 'noquestions','quiz',$continuepath );
707 // final pre-process on exported data
708 $expout = $this->presave_process( $expout );
710 // write file
711 $filepath = $path."/".$this->filename . $this->export_file_extension();
712 if (!$fh=fopen($filepath,"w")) {
713 print_error( 'cannotopen','quiz',$continuepath,$filepath );
715 if (!fwrite($fh, $expout, strlen($expout) )) {
716 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
718 fclose($fh);
719 return true;
723 * get the category as a path (e.g., tom/dick/harry)
724 * @param int id the id of the most nested catgory
725 * @param string delimiter the delimiter you want
726 * @return string the path
728 function get_category_path($id, $delimiter='/', $includecontext = true) {
729 $path = '';
730 if (!$firstcategory = get_record('question_categories','id',$id)) {
731 error( "Error getting category record from db - " . $id );
733 $category = $firstcategory;
734 $contextstring = $this->translator->context_to_string($category->contextid);
735 do {
736 $name = $category->name;
737 $id = $category->parent;
738 if (!empty($path)) {
739 $path = "{$name}{$delimiter}{$path}";
741 else {
742 $path = $name;
744 } while ($category = get_record( 'question_categories','id',$id ));
746 if ($includecontext){
747 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
749 return $path;
753 * Do an post-processing that may be required
754 * @return boolean success
756 function exportpostprocess() {
757 return true;
761 * convert a single question object into text output in the given
762 * format.
763 * This must be overriden
764 * @param object question question object
765 * @return mixed question export text or null if not implemented
767 function writequestion($question) {
768 // if not overidden, then this is an error.
769 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
770 echo "<p>$formatnotimplemented</p>";
771 return NULL;
775 * get directory into which export is going
776 * @return string file path
778 function question_get_export_dir() {
779 global $USER;
780 if ($this->canaccessbackupdata) {
781 $dirname = get_string("exportfilename","quiz");
782 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
783 } else {
784 $path = 'temp/questionexport/' . $USER->id;
786 return $path;
790 * where question specifies a moodle (text) format this
791 * performs the conversion.
793 function format_question_text($question) {
794 $formatoptions = new stdClass;
795 $formatoptions->noclean = true;
796 $formatoptions->para = false;
797 if (empty($question->questiontextformat)) {
798 $format = FORMAT_MOODLE;
799 } else {
800 $format = $question->questiontextformat;
802 return format_text(stripslashes($question->questiontext), $format, $formatoptions);