MDL-20927 fixed module login issue
[moodle.git] / question / format.php
blob70b1cda21c5ef4bf6b1e6e45ed5adcc50d89064b
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 $realfilename = '';
19 var $matchgrades = 'error';
20 var $catfromfile = 0;
21 var $contextfromfile = 0;
22 var $cattofile = 0;
23 var $contexttofile = 0;
24 var $questionids = array();
25 var $importerrors = 0;
26 var $stoponerror = true;
27 var $translator = null;
28 var $canaccessbackupdata = true;
31 // functions to indicate import/export functionality
32 // override to return true if implemented
34 function provide_import() {
35 return false;
38 function provide_export() {
39 return false;
42 // Accessor methods
44 /**
45 * set the category
46 * @param object category the category object
48 function setCategory( $category ) {
49 if (count($this->questions)){
50 debugging('You shouldn\'t call setCategory after setQuestions');
52 $this->category = $category;
55 /**
56 * Set the specific questions to export. Should not include questions with
57 * parents (sub questions of cloze question type).
58 * Only used for question export.
59 * @param array of question objects
61 function setQuestions( $questions ) {
62 if ($this->category !== null){
63 debugging('You shouldn\'t call setQuestions after setCategory');
65 $this->questions = $questions;
68 /**
69 * set the course class variable
70 * @param course object Moodle course variable
72 function setCourse( $course ) {
73 $this->course = $course;
75 /**
76 * set an array of contexts.
77 * @param array $contexts Moodle course variable
79 function setContexts($contexts) {
80 $this->contexts = $contexts;
81 $this->translator = new context_to_string_translator($this->contexts);
84 /**
85 * set the filename
86 * @param string filename name of file to import/export
88 function setFilename( $filename ) {
89 $this->filename = $filename;
92 /**
93 * set the "real" filename
94 * (this is what the user typed, regardless of wha happened next)
95 * @param string realfilename name of file as typed by user
97 function setRealfilename( $realfilename ) {
98 $this->realfilename = $realfilename;
102 * set matchgrades
103 * @param string matchgrades error or nearest for grades
105 function setMatchgrades( $matchgrades ) {
106 $this->matchgrades = $matchgrades;
110 * set catfromfile
111 * @param bool catfromfile allow categories embedded in import file
113 function setCatfromfile( $catfromfile ) {
114 $this->catfromfile = $catfromfile;
118 * set contextfromfile
119 * @param bool $contextfromfile allow contexts embedded in import file
121 function setContextfromfile($contextfromfile) {
122 $this->contextfromfile = $contextfromfile;
126 * set cattofile
127 * @param bool cattofile exports categories within export file
129 function setCattofile( $cattofile ) {
130 $this->cattofile = $cattofile;
133 * set contexttofile
134 * @param bool cattofile exports categories within export file
136 function setContexttofile($contexttofile) {
137 $this->contexttofile = $contexttofile;
141 * set stoponerror
142 * @param bool stoponerror stops database write if any errors reported
144 function setStoponerror( $stoponerror ) {
145 $this->stoponerror = $stoponerror;
149 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
150 * where export files are saved.
152 function set_can_access_backupdata($canaccess) {
153 $this->canaccessbackupdata = $canaccess;
156 /***********************
157 * IMPORTING FUNCTIONS
158 ***********************/
161 * Handle parsing error
163 function error( $message, $text='', $questionname='' ) {
164 $importerrorquestion = get_string('importerrorquestion','quiz');
166 echo "<div class=\"importerror\">\n";
167 echo "<strong>$importerrorquestion $questionname</strong>";
168 if (!empty($text)) {
169 $text = s($text);
170 echo "<blockquote>$text</blockquote>\n";
172 echo "<strong>$message</strong>\n";
173 echo "</div>";
175 $this->importerrors++;
179 * Import for questiontype plugins
180 * Do not override.
181 * @param data mixed The segment of data containing the question
182 * @param question object processed (so far) by standard import code if appropriate
183 * @param extra mixed any additional format specific data that may be passed by the format
184 * @param qtypehint hint about a question type from format
185 * @return object question object suitable for save_options() or false if cannot handle
187 function try_importing_using_qtypes( $data, $question=null, $extra=null, $qtypehint='') {
188 global $QTYPES;
190 // work out what format we are using
191 $formatname = substr(get_class($this), strlen('qformat_'));
192 $methodname = "import_from_$formatname";
194 //first try importing using a hint from format
195 if (!empty($qtypehint)) {
196 $qtype = $QTYPES[$qtypehint];
197 if (is_object($qtype) && method_exists($qtype, $methodname)) {
198 $question = $qtype->$methodname($data, $question, $this, $extra);
199 if ($question) {
200 return $question;
205 // loop through installed questiontypes checking for
206 // function to handle this question
207 foreach ($QTYPES as $qtype) {
208 if (method_exists( $qtype, $methodname)) {
209 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
210 return $question;
214 return false;
218 * Perform any required pre-processing
219 * @return boolean success
221 function importpreprocess() {
222 return true;
226 * Process the file
227 * This method should not normally be overidden
228 * @return boolean success
230 function importprocess() {
231 global $USER;
233 // reset the timer in case file upload was slow
234 @set_time_limit();
236 // STAGE 1: Parse the file
237 notify( get_string('parsingquestions','quiz') );
239 if (! $lines = $this->readdata($this->filename)) {
240 notify( get_string('cannotread','quiz') );
241 return false;
244 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
245 notify( get_string('noquestionsinfile','quiz') );
246 return false;
249 // STAGE 2: Write data to database
250 notify( get_string('importingquestions','quiz',$this->count_questions($questions)) );
252 // check for errors before we continue
253 if ($this->stoponerror and ($this->importerrors>0)) {
254 notify( get_string('importparseerror','quiz') );
255 return true;
258 // get list of valid answer grades
259 $grades = get_grade_options();
260 $gradeoptionsfull = $grades->gradeoptionsfull;
262 // check answer grades are valid
263 // (now need to do this here because of 'stop on error': MDL-10689)
264 $gradeerrors = 0;
265 $goodquestions = array();
266 foreach ($questions as $question) {
267 if (!empty($question->fraction) and (is_array($question->fraction))) {
268 $fractions = $question->fraction;
269 $answersvalid = true; // in case they are!
270 foreach ($fractions as $key => $fraction) {
271 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
272 if ($newfraction===false) {
273 $answersvalid = false;
275 else {
276 $fractions[$key] = $newfraction;
279 if (!$answersvalid) {
280 notify(get_string('matcherror', 'quiz'));
281 ++$gradeerrors;
282 continue;
284 else {
285 $question->fraction = $fractions;
288 $goodquestions[] = $question;
290 $questions = $goodquestions;
292 // check for errors before we continue
293 if ($this->stoponerror and ($gradeerrors>0)) {
294 return false;
297 // count number of questions processed
298 $count = 0;
300 foreach ($questions as $question) { // Process and store each question
302 // reset the php timeout
303 @set_time_limit();
305 // check for category modifiers
306 if ($question->qtype=='category') {
307 if ($this->catfromfile) {
308 // find/create category object
309 $catpath = $question->category;
310 $newcategory = $this->create_category_path( $catpath, '/');
311 if (!empty($newcategory)) {
312 $this->category = $newcategory;
315 continue;
318 $count++;
320 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
322 $question->category = $this->category->id;
323 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
325 $question->createdby = $USER->id;
326 $question->timecreated = time();
328 if (!$question->id = insert_record("question", $question)) {
329 error( get_string('cannotinsert','quiz') );
332 $this->questionids[] = $question->id;
334 // Now to save all the answers and type-specific options
336 global $QTYPES;
337 $result = $QTYPES[$question->qtype]
338 ->save_question_options($question);
340 if (!empty($result->error)) {
341 notify($result->error);
342 return false;
345 if (!empty($result->notice)) {
346 notify($result->notice);
347 return true;
350 // Give the question a unique version stamp determined by question_hash()
351 set_field('question', 'version', question_hash($question), 'id', $question->id);
353 return true;
356 * Count all non-category questions in the questions array.
358 * @param array questions An array of question objects.
359 * @return int The count.
362 function count_questions($questions) {
363 $count = 0;
364 if (!is_array($questions)) {
365 return $count;
367 foreach ($questions as $question) {
368 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
369 continue;
371 $count++;
373 return $count;
377 * find and/or create the category described by a delimited list
378 * e.g. $course$/tom/dick/harry or tom/dick/harry
380 * removes any context string no matter whether $getcontext is set
381 * but if $getcontext is set then ignore the context and use selected category context.
383 * @param string catpath delimited category path
384 * @param string delimiter path delimiting character
385 * @param int courseid course to search for categories
386 * @return mixed category object or null if fails
388 function create_category_path($catpath, $delimiter='/') {
389 $catpath = clean_param($catpath, PARAM_PATH);
390 $catnames = explode($delimiter, $catpath);
391 $parent = 0;
392 $category = null;
394 // check for context id in path, it might not be there in pre 1.9 exports
395 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
396 if ($matchcount==1) {
397 $contextid = $this->translator->string_to_context($matches[1]);
398 array_shift($catnames);
399 } else {
400 $contextid = FALSE;
402 if ($this->contextfromfile && ($contextid !== FALSE)){
403 $context = get_context_instance_by_id($contextid);
404 require_capability('moodle/question:add', $context);
405 } else {
406 $context = get_context_instance_by_id($this->category->contextid);
408 foreach ($catnames as $catname) {
409 if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) {
410 $parent = $category->id;
411 } else {
412 require_capability('moodle/question:managecategory', $context);
413 // create the new category
414 $category = new object;
415 $category->contextid = $context->id;
416 $category->name = $catname;
417 $category->info = '';
418 $category->parent = $parent;
419 $category->sortorder = 999;
420 $category->stamp = make_unique_id_code();
421 if (!($id = insert_record('question_categories', $category))) {
422 error( "cannot create new category - $catname" );
424 $category->id = $id;
425 $parent = $id;
428 return $category;
432 * Return complete file within an array, one item per line
433 * @param string filename name of file
434 * @return mixed contents array or false on failure
436 function readdata($filename) {
437 if (is_readable($filename)) {
438 $filearray = file($filename);
440 /// Check for Macintosh OS line returns (ie file on one line), and fix
441 if (preg_match("/\r/", $filearray[0]) AND !preg_match("/\n/", $filearray[0])) {
442 return explode("\r", $filearray[0]);
443 } else {
444 return $filearray;
447 return false;
451 * Parses an array of lines into an array of questions,
452 * where each item is a question object as defined by
453 * readquestion(). Questions are defined as anything
454 * between blank lines.
456 * If your format does not use blank lines as a delimiter
457 * then you will need to override this method. Even then
458 * try to use readquestion for each question
459 * @param array lines array of lines from readdata
460 * @return array array of question objects
462 function readquestions($lines) {
464 $questions = array();
465 $currentquestion = array();
467 foreach ($lines as $line) {
468 $line = trim($line);
469 if (empty($line)) {
470 if (!empty($currentquestion)) {
471 if ($question = $this->readquestion($currentquestion)) {
472 $questions[] = $question;
474 $currentquestion = array();
476 } else {
477 $currentquestion[] = $line;
481 if (!empty($currentquestion)) { // There may be a final question
482 if ($question = $this->readquestion($currentquestion)) {
483 $questions[] = $question;
487 return $questions;
492 * return an "empty" question
493 * Somewhere to specify question parameters that are not handled
494 * by import but are required db fields.
495 * This should not be overridden.
496 * @return object default question
498 function defaultquestion() {
499 global $CFG;
501 $question = new stdClass();
502 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
503 $question->defaultgrade = 1;
504 $question->image = "";
505 $question->usecase = 0;
506 $question->multiplier = array();
507 $question->generalfeedback = '';
508 $question->correctfeedback = '';
509 $question->partiallycorrectfeedback = '';
510 $question->incorrectfeedback = '';
511 $question->answernumbering = 'abc';
512 $question->penalty = 0.1;
513 $question->length = 1;
515 // this option in case the questiontypes class wants
516 // to know where the data came from
517 $question->export_process = true;
518 $question->import_process = true;
520 return $question;
524 * Given the data known to define a question in
525 * this format, this function converts it into a question
526 * object suitable for processing and insertion into Moodle.
528 * If your format does not use blank lines to delimit questions
529 * (e.g. an XML format) you must override 'readquestions' too
530 * @param $lines mixed data that represents question
531 * @return object question object
533 function readquestion($lines) {
535 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
536 echo "<p>$formatnotimplemented</p>";
538 return NULL;
542 * Override if any post-processing is required
543 * @return boolean success
545 function importpostprocess() {
546 return true;
550 * Import an image file encoded in base64 format
551 * @param string path path (in course data) to store picture
552 * @param string base64 encoded picture
553 * @return string filename (nb. collisions are handled)
555 function importimagefile( $path, $base64 ) {
556 global $CFG;
558 // all this to get the destination directory
559 // and filename!
560 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
561 $path_parts = pathinfo( $fullpath );
562 $destination = $path_parts['dirname'];
563 $file = clean_filename( $path_parts['basename'] );
565 // check if path exists
566 check_dir_exists($destination, true, true );
568 // detect and fix any filename collision - get unique filename
569 $newfiles = resolve_filename_collisions( $destination, array($file) );
570 $newfile = $newfiles[0];
572 // convert and save file contents
573 if (!$content = base64_decode( $base64 )) {
574 return '';
576 $newfullpath = "$destination/$newfile";
577 if (!$fh = fopen( $newfullpath, 'w' )) {
578 return '';
580 if (!fwrite( $fh, $content )) {
581 return '';
583 fclose( $fh );
585 // return the (possibly) new filename
586 $newfile = preg_replace("#{$CFG->dataroot}/{$this->course->id}/#", '',$newfullpath);
587 return $newfile;
591 /*******************
592 * EXPORT FUNCTIONS
593 *******************/
596 * Provide export functionality for plugin questiontypes
597 * Do not override
598 * @param name questiontype name
599 * @param question object data to export
600 * @param extra mixed any addition format specific data needed
601 * @return string the data to append to export or false if error (or unhandled)
603 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
604 global $QTYPES;
606 // work out the name of format in use
607 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
608 $methodname = "export_to_$formatname";
610 if (array_key_exists( $name, $QTYPES )) {
611 $qtype = $QTYPES[ $name ];
612 if (method_exists( $qtype, $methodname )) {
613 if ($data = $qtype->$methodname( $question, $this, $extra )) {
614 return $data;
618 return false;
622 * Return the files extension appropriate for this type
623 * override if you don't want .txt
624 * @return string file extension
626 function export_file_extension() {
627 return ".txt";
631 * Do any pre-processing that may be required
632 * @param boolean success
634 function exportpreprocess() {
635 return true;
639 * Enable any processing to be done on the content
640 * just prior to the file being saved
641 * default is to do nothing
642 * @param string output text
643 * @param string processed output text
645 function presave_process( $content ) {
646 return $content;
650 * Do the export
651 * For most types this should not need to be overrided
652 * @return boolean success
654 function exportprocess() {
655 global $CFG;
657 // create a directory for the exports (if not already existing)
658 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
659 error( get_string('cannotcreatepath','quiz',$export_dir) );
661 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
663 // get the questions (from database) in this category
664 // only get q's with no parents (no cloze subquestions specifically)
665 if ($this->category){
666 $questions = get_questions_category( $this->category, true );
667 } else {
668 $questions = $this->questions;
671 notify( get_string('exportingquestions','quiz') );
672 $count = 0;
674 // results are first written into string (and then to a file)
675 // so create/initialize the string here
676 $expout = "";
678 // track which category questions are in
679 // if it changes we will record the category change in the output
680 // file if selected. 0 means that it will get printed before the 1st question
681 $trackcategory = 0;
683 // iterate through questions
684 foreach($questions as $question) {
686 // do not export hidden questions
687 if (!empty($question->hidden)) {
688 continue;
691 // do not export random questions
692 if ($question->qtype==RANDOM) {
693 continue;
696 // check if we need to record category change
697 if ($this->cattofile) {
698 if ($question->category != $trackcategory) {
699 $trackcategory = $question->category;
700 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
702 // create 'dummy' question for category export
703 $dummyquestion = new object;
704 $dummyquestion->qtype = 'category';
705 $dummyquestion->category = $categoryname;
706 $dummyquestion->name = "switch category to $categoryname";
707 $dummyquestion->id = 0;
708 $dummyquestion->questiontextformat = '';
709 $expout .= $this->writequestion( $dummyquestion ) . "\n";
713 // export the question displaying message
714 $count++;
715 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
716 if (question_has_capability_on($question, 'view', $question->category)){
717 $expout .= $this->writequestion( $question ) . "\n";
721 // continue path for following error checks
722 $course = $this->course;
723 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
725 // did we actually process anything
726 if ($count==0) {
727 print_error( 'noquestions','quiz',$continuepath );
730 // final pre-process on exported data
731 $expout = $this->presave_process( $expout );
733 // write file
734 $filepath = $path."/".$this->filename . $this->export_file_extension();
735 if (!$fh=fopen($filepath,"w")) {
736 print_error( 'cannotopen','quiz',$continuepath,$filepath );
738 if (!fwrite($fh, $expout, strlen($expout) )) {
739 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
741 fclose($fh);
742 return true;
746 * get the category as a path (e.g., tom/dick/harry)
747 * @param int id the id of the most nested catgory
748 * @param string delimiter the delimiter you want
749 * @return string the path
751 function get_category_path($id, $delimiter='/', $includecontext = true) {
752 $path = '';
753 if (!$firstcategory = get_record('question_categories','id',$id)) {
754 error( "Error getting category record from db - " . $id );
756 $category = $firstcategory;
757 $contextstring = $this->translator->context_to_string($category->contextid);
758 do {
759 $name = $category->name;
760 $id = $category->parent;
761 if (!empty($path)) {
762 $path = "{$name}{$delimiter}{$path}";
764 else {
765 $path = $name;
767 } while ($category = get_record( 'question_categories','id',$id ));
769 if ($includecontext){
770 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
772 return $path;
776 * Do an post-processing that may be required
777 * @return boolean success
779 function exportpostprocess() {
780 return true;
784 * convert a single question object into text output in the given
785 * format.
786 * This must be overriden
787 * @param object question question object
788 * @return mixed question export text or null if not implemented
790 function writequestion($question) {
791 // if not overidden, then this is an error.
792 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
793 echo "<p>$formatnotimplemented</p>";
794 return NULL;
798 * get directory into which export is going
799 * @return string file path
801 function question_get_export_dir() {
802 global $USER;
803 if ($this->canaccessbackupdata) {
804 $dirname = get_string("exportfilename","quiz");
805 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
806 } else {
807 $path = 'temp/questionexport/' . $USER->id;
809 return $path;
813 * where question specifies a moodle (text) format this
814 * performs the conversion.
816 function format_question_text($question) {
817 $formatoptions = new stdClass;
818 $formatoptions->noclean = true;
819 $formatoptions->para = false;
820 if (empty($question->questiontextformat)) {
821 $format = FORMAT_MOODLE;
822 } else {
823 $format = $question->questiontextformat;
825 return format_text(stripslashes($question->questiontext), $format, $formatoptions);