MDL-23395, go straight to page editing page when title is not empyt and forceformat...
[moodle.git] / question / format.php
blob3748307deefa701d3864c9ae5f34607aa56281d0
1 <?php
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;
30 protected $importcontext = null;
32 // functions to indicate import/export functionality
33 // override to return true if implemented
35 function provide_import() {
36 return false;
39 function provide_export() {
40 return false;
43 // Accessor methods
45 /**
46 * set the category
47 * @param object category the category object
49 function setCategory( $category ) {
50 if (count($this->questions)){
51 debugging('You shouldn\'t call setCategory after setQuestions');
53 $this->category = $category;
56 /**
57 * Set the specific questions to export. Should not include questions with
58 * parents (sub questions of cloze question type).
59 * Only used for question export.
60 * @param array of question objects
62 function setQuestions( $questions ) {
63 if ($this->category !== null){
64 debugging('You shouldn\'t call setQuestions after setCategory');
66 $this->questions = $questions;
69 /**
70 * set the course class variable
71 * @param course object Moodle course variable
73 function setCourse( $course ) {
74 $this->course = $course;
76 /**
77 * set an array of contexts.
78 * @param array $contexts Moodle course variable
80 function setContexts($contexts) {
81 $this->contexts = $contexts;
82 $this->translator = new context_to_string_translator($this->contexts);
85 /**
86 * set the filename
87 * @param string filename name of file to import/export
89 function setFilename( $filename ) {
90 $this->filename = $filename;
93 /**
94 * set the "real" filename
95 * (this is what the user typed, regardless of wha happened next)
96 * @param string realfilename name of file as typed by user
98 function setRealfilename( $realfilename ) {
99 $this->realfilename = $realfilename;
103 * set matchgrades
104 * @param string matchgrades error or nearest for grades
106 function setMatchgrades( $matchgrades ) {
107 $this->matchgrades = $matchgrades;
111 * set catfromfile
112 * @param bool catfromfile allow categories embedded in import file
114 function setCatfromfile( $catfromfile ) {
115 $this->catfromfile = $catfromfile;
119 * set contextfromfile
120 * @param bool $contextfromfile allow contexts embedded in import file
122 function setContextfromfile($contextfromfile) {
123 $this->contextfromfile = $contextfromfile;
127 * set cattofile
128 * @param bool cattofile exports categories within export file
130 function setCattofile( $cattofile ) {
131 $this->cattofile = $cattofile;
134 * set contexttofile
135 * @param bool cattofile exports categories within export file
137 function setContexttofile($contexttofile) {
138 $this->contexttofile = $contexttofile;
142 * set stoponerror
143 * @param bool stoponerror stops database write if any errors reported
145 function setStoponerror( $stoponerror ) {
146 $this->stoponerror = $stoponerror;
150 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
151 * where export files are saved.
153 function set_can_access_backupdata($canaccess) {
154 $this->canaccessbackupdata = $canaccess;
157 /***********************
158 * IMPORTING FUNCTIONS
159 ***********************/
162 * Handle parsing error
164 function error( $message, $text='', $questionname='' ) {
165 $importerrorquestion = get_string('importerrorquestion','quiz');
167 echo "<div class=\"importerror\">\n";
168 echo "<strong>$importerrorquestion $questionname</strong>";
169 if (!empty($text)) {
170 $text = s($text);
171 echo "<blockquote>$text</blockquote>\n";
173 echo "<strong>$message</strong>\n";
174 echo "</div>";
176 $this->importerrors++;
180 * Import for questiontype plugins
181 * Do not override.
182 * @param data mixed The segment of data containing the question
183 * @param question object processed (so far) by standard import code if appropriate
184 * @param extra mixed any additional format specific data that may be passed by the format
185 * @param qtypehint hint about a question type from format
186 * @return object question object suitable for save_options() or false if cannot handle
188 function try_importing_using_qtypes( $data, $question=null, $extra=null, $qtypehint='') {
189 global $QTYPES;
191 // work out what format we are using
192 $formatname = substr(get_class($this), strlen('qformat_'));
193 $methodname = "import_from_$formatname";
195 //first try importing using a hint from format
196 if (!empty($qtypehint)) {
197 $qtype = $QTYPES[$qtypehint];
198 if (is_object($qtype) && method_exists($qtype, $methodname)) {
199 $question = $qtype->$methodname($data, $question, $this, $extra);
200 if ($question) {
201 return $question;
206 // loop through installed questiontypes checking for
207 // function to handle this question
208 foreach ($QTYPES as $qtype) {
209 if (method_exists( $qtype, $methodname)) {
210 if ($question = $qtype->$methodname( $data, $question, $this, $extra )) {
211 return $question;
215 return false;
219 * Perform any required pre-processing
220 * @return boolean success
222 function importpreprocess() {
223 return true;
227 * Process the file
228 * This method should not normally be overidden
229 * @param object $context
230 * @return boolean success
232 function importprocess($category) {
233 global $USER, $DB, $OUTPUT, $QTYPES;
235 $context = $category->context;
236 $this->importcontext = $context;
238 // reset the timer in case file upload was slow
239 set_time_limit(0);
241 // STAGE 1: Parse the file
242 echo $OUTPUT->notification( get_string('parsingquestions','quiz') );
244 if (! $lines = $this->readdata($this->filename)) {
245 echo $OUTPUT->notification( get_string('cannotread','quiz') );
246 return false;
249 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
250 echo $OUTPUT->notification( get_string('noquestionsinfile','quiz') );
251 return false;
254 // STAGE 2: Write data to database
255 echo $OUTPUT->notification( get_string('importingquestions','quiz',$this->count_questions($questions)) );
257 // check for errors before we continue
258 if ($this->stoponerror and ($this->importerrors>0)) {
259 echo $OUTPUT->notification( get_string('importparseerror','quiz') );
260 return true;
263 // get list of valid answer grades
264 $grades = get_grade_options();
265 $gradeoptionsfull = $grades->gradeoptionsfull;
267 // check answer grades are valid
268 // (now need to do this here because of 'stop on error': MDL-10689)
269 $gradeerrors = 0;
270 $goodquestions = array();
271 foreach ($questions as $question) {
273 if (!empty($question->fraction) and (is_array($question->fraction))) {
274 $fractions = $question->fraction;
275 $answersvalid = true; // in case they are!
276 foreach ($fractions as $key => $fraction) {
277 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
278 if ($newfraction===false) {
279 $answersvalid = false;
281 else {
282 $fractions[$key] = $newfraction;
285 if (!$answersvalid) {
286 echo $OUTPUT->notification(get_string('matcherror', 'quiz'));
287 ++$gradeerrors;
288 continue;
290 else {
291 $question->fraction = $fractions;
294 $goodquestions[] = $question;
296 $questions = $goodquestions;
298 // check for errors before we continue
299 if ($this->stoponerror and ($gradeerrors>0)) {
300 return false;
303 // count number of questions processed
304 $count = 0;
306 foreach ($questions as $question) { // Process and store each question
308 // reset the php timeout
309 @set_time_limit(0);
311 // check for category modifiers
312 if ($question->qtype=='category') {
313 if ($this->catfromfile) {
314 // find/create category object
315 $catpath = $question->category;
316 $newcategory = $this->create_category_path($catpath);
317 if (!empty($newcategory)) {
318 $this->category = $newcategory;
321 continue;
323 $question->context = $context;
325 $count++;
327 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
329 $question->category = $category->id;
330 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
332 $question->createdby = $USER->id;
333 $question->timecreated = time();
335 $question->id = $DB->insert_record('question', $question);
336 if (isset($question->questiontextfiles)) {
337 foreach ($question->questiontextfiles as $file) {
338 $QTYPES[$question->qtype]->import_file($context, 'question', 'questiontext', $question->id, $file);
341 if (isset($question->generalfeedbackfiles)) {
342 foreach ($question->generalfeedbackfiles as $file) {
343 $QTYPES[$question->qtype]->import_file($context, 'question', 'generalfeedback', $question->id, $file);
347 $this->questionids[] = $question->id;
349 // Now to save all the answers and type-specific options
351 $result = $QTYPES[$question->qtype]->save_question_options($question);
353 if (!empty($result->error)) {
354 echo $OUTPUT->notification($result->error);
355 return false;
358 if (!empty($result->notice)) {
359 echo $OUTPUT->notification($result->notice);
360 return true;
363 // Give the question a unique version stamp determined by question_hash()
364 $DB->set_field('question', 'version', question_hash($question), array('id'=>$question->id));
366 return true;
369 * Count all non-category questions in the questions array.
371 * @param array questions An array of question objects.
372 * @return int The count.
375 function count_questions($questions) {
376 $count = 0;
377 if (!is_array($questions)) {
378 return $count;
380 foreach ($questions as $question) {
381 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
382 continue;
384 $count++;
386 return $count;
390 * find and/or create the category described by a delimited list
391 * e.g. $course$/tom/dick/harry or tom/dick/harry
393 * removes any context string no matter whether $getcontext is set
394 * but if $getcontext is set then ignore the context and use selected category context.
396 * @param string catpath delimited category path
397 * @param int courseid course to search for categories
398 * @return mixed category object or null if fails
400 function create_category_path($catpath) {
401 global $DB;
402 $catnames = $this->split_category_path($catpath);
403 $parent = 0;
404 $category = null;
406 // check for context id in path, it might not be there in pre 1.9 exports
407 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
408 if ($matchcount==1) {
409 $contextid = $this->translator->string_to_context($matches[1]);
410 array_shift($catnames);
411 } else {
412 $contextid = false;
415 if ($this->contextfromfile && $contextid !== false) {
416 $context = get_context_instance_by_id($contextid);
417 require_capability('moodle/question:add', $context);
418 } else {
419 $context = get_context_instance_by_id($this->category->contextid);
422 // Now create any categories that need to be created.
423 foreach ($catnames as $catname) {
424 if ($category = $DB->get_record( 'question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
425 $parent = $category->id;
426 } else {
427 require_capability('moodle/question:managecategory', $context);
428 // create the new category
429 $category = new stdClass();
430 $category->contextid = $context->id;
431 $category->name = $catname;
432 $category->info = '';
433 $category->parent = $parent;
434 $category->sortorder = 999;
435 $category->stamp = make_unique_id_code();
436 $id = $DB->insert_record('question_categories', $category);
437 $category->id = $id;
438 $parent = $id;
441 return $category;
445 * Return complete file within an array, one item per line
446 * @param string filename name of file
447 * @return mixed contents array or false on failure
449 function readdata($filename) {
450 if (is_readable($filename)) {
451 $filearray = file($filename);
453 /// Check for Macintosh OS line returns (ie file on one line), and fix
454 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
455 return explode("\r", $filearray[0]);
456 } else {
457 return $filearray;
460 return false;
464 * Parses an array of lines into an array of questions,
465 * where each item is a question object as defined by
466 * readquestion(). Questions are defined as anything
467 * between blank lines.
469 * If your format does not use blank lines as a delimiter
470 * then you will need to override this method. Even then
471 * try to use readquestion for each question
472 * @param array lines array of lines from readdata
473 * @param object $context
474 * @return array array of question objects
476 function readquestions($lines, $context) {
478 $questions = array();
479 $currentquestion = array();
481 foreach ($lines as $line) {
482 $line = trim($line);
483 if (empty($line)) {
484 if (!empty($currentquestion)) {
485 if ($question = $this->readquestion($currentquestion)) {
486 $questions[] = $question;
488 $currentquestion = array();
490 } else {
491 $currentquestion[] = $line;
495 if (!empty($currentquestion)) { // There may be a final question
496 if ($question = $this->readquestion($currentquestion, $context)) {
497 $questions[] = $question;
501 return $questions;
506 * return an "empty" question
507 * Somewhere to specify question parameters that are not handled
508 * by import but are required db fields.
509 * This should not be overridden.
510 * @return object default question
512 function defaultquestion() {
513 global $CFG;
514 static $defaultshuffleanswers = null;
515 if (is_null($defaultshuffleanswers)) {
516 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
519 $question = new stdClass();
520 $question->shuffleanswers = $defaultshuffleanswers;
521 $question->defaultgrade = 1;
522 $question->image = "";
523 $question->usecase = 0;
524 $question->multiplier = array();
525 $question->generalfeedback = '';
526 $question->correctfeedback = '';
527 $question->partiallycorrectfeedback = '';
528 $question->incorrectfeedback = '';
529 $question->answernumbering = 'abc';
530 $question->penalty = 0.1;
531 $question->length = 1;
533 // this option in case the questiontypes class wants
534 // to know where the data came from
535 $question->export_process = true;
536 $question->import_process = true;
538 return $question;
542 * Given the data known to define a question in
543 * this format, this function converts it into a question
544 * object suitable for processing and insertion into Moodle.
546 * If your format does not use blank lines to delimit questions
547 * (e.g. an XML format) you must override 'readquestions' too
548 * @param $lines mixed data that represents question
549 * @return object question object
551 function readquestion($lines) {
553 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
554 echo "<p>$formatnotimplemented</p>";
556 return NULL;
560 * Override if any post-processing is required
561 * @return boolean success
563 function importpostprocess() {
564 return true;
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 stored_file
631 function exportprocess() {
632 global $CFG, $OUTPUT, $DB, $USER;
634 // get the questions (from database) in this category
635 // only get q's with no parents (no cloze subquestions specifically)
636 if ($this->category) {
637 $questions = get_questions_category( $this->category, true );
638 } else {
639 $questions = $this->questions;
642 //echo $OUTPUT->notification( get_string('exportingquestions','quiz') );
643 $count = 0;
645 // results are first written into string (and then to a file)
646 // so create/initialize the string here
647 $expout = "";
649 // track which category questions are in
650 // if it changes we will record the category change in the output
651 // file if selected. 0 means that it will get printed before the 1st question
652 $trackcategory = 0;
654 $fs = get_file_storage();
656 // iterate through questions
657 foreach($questions as $question) {
658 // used by file api
659 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$question->category));
660 $question->contextid = $contextid;
662 // do not export hidden questions
663 if (!empty($question->hidden)) {
664 continue;
667 // do not export random questions
668 if ($question->qtype==RANDOM) {
669 continue;
672 // check if we need to record category change
673 if ($this->cattofile) {
674 if ($question->category != $trackcategory) {
675 $trackcategory = $question->category;
676 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
678 // create 'dummy' question for category export
679 $dummyquestion = new stdClass();
680 $dummyquestion->qtype = 'category';
681 $dummyquestion->category = $categoryname;
682 $dummyquestion->name = 'Switch category to ' . $categoryname;
683 $dummyquestion->id = 0;
684 $dummyquestion->questiontextformat = '';
685 $dummyquestion->contextid = 0;
686 $expout .= $this->writequestion($dummyquestion) . "\n";
690 // export the question displaying message
691 $count++;
693 //echo '<hr />';
694 //echo $OUTPUT->container_start();
695 //echo '<strong>' . $count . '.</strong>&nbsp;';
696 //echo $this->format_question_text($question);
697 //echo $OUTPUT->container_end();
699 if (question_has_capability_on($question, 'view', $question->category)) {
700 // files used by questiontext
701 $files = $fs->get_area_files($contextid, 'question', 'questiontext', $question->id);
702 $question->questiontextfiles = $files;
703 // files used by generalfeedback
704 $files = $fs->get_area_files($contextid, 'question', 'generalfeedback', $question->id);
705 $question->generalfeedbackfiles = $files;
706 if (!empty($question->options->answers)) {
707 foreach ($question->options->answers as $answer) {
708 $files = $fs->get_area_files($contextid, 'question', 'answerfeedback', $answer->id);
709 $answer->feedbackfiles = $files;
713 $expout .= $this->writequestion($question, $contextid) . "\n";
717 // continue path for following error checks
718 $course = $this->course;
719 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
721 // did we actually process anything
722 if ($count==0) {
723 print_error( 'noquestions','quiz',$continuepath );
726 // final pre-process on exported data
727 $expout = $this->presave_process($expout);
728 return $expout;
732 * get the category as a path (e.g., tom/dick/harry)
733 * @param int id the id of the most nested catgory
734 * @return string the path
736 function get_category_path($id, $includecontext = true) {
737 global $DB;
739 if (!$category = $DB->get_record('question_categories',array('id' =>$id))) {
740 print_error('cannotfindcategory', 'error', '', $id);
742 $contextstring = $this->translator->context_to_string($category->contextid);
744 $pathsections = array();
745 do {
746 $pathsections[] = $category->name;
747 $id = $category->parent;
748 } while ($category = $DB->get_record( 'question_categories', array('id' => $id )));
750 if ($includecontext){
751 $pathsections[] = '$' . $contextstring . '$';
754 $path = $this->assemble_category_path(array_reverse($pathsections));
756 return $path;
760 * Convert a list of category names, possibly preceeded by one of the
761 * context tokens like $course$, into a string representation of the
762 * category path.
764 * Names are separated by / delimiters. And /s in the name are replaced by //.
766 * To reverse the process and split the paths into names, use
767 * {@link split_category_path()}.
769 * @param array $names
770 * @return string
772 protected function assemble_category_path($names) {
773 $escapednames = array();
774 foreach ($names as $name) {
775 $escapedname = str_replace('/', '//', $name);
776 if (substr($escapedname, 0, 1) == '/') {
777 $escapedname = ' ' . $escapedname;
779 if (substr($escapedname, -1) == '/') {
780 $escapedname = $escapedname . ' ';
782 $escapednames[] = $escapedname;
784 return implode('/', $escapednames);
788 * Convert a string, as returned by {@link assemble_category_path()},
789 * back into an array of category names.
791 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
792 * which matches the cleaning in question/category_form.php.
794 * @param string $path
795 * @return array of category names.
797 protected function split_category_path($path) {
798 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
799 $names = array();
800 foreach ($rawnames as $rawname) {
801 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
803 return $names;
807 * Do an post-processing that may be required
808 * @return boolean success
810 function exportpostprocess() {
811 return true;
815 * convert a single question object into text output in the given
816 * format.
817 * This must be overriden
818 * @param object question question object
819 * @return mixed question export text or null if not implemented
821 function writequestion($question) {
822 // if not overidden, then this is an error.
823 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
824 echo "<p>$formatnotimplemented</p>";
825 return NULL;
829 * get directory into which export is going
830 * @return string file path
832 function question_get_export_dir() {
833 global $USER;
834 if ($this->canaccessbackupdata) {
835 $dirname = get_string("exportfilename","quiz");
836 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
837 } else {
838 $path = 'temp/questionexport/' . $USER->id;
840 return $path;
844 * where question specifies a moodle (text) format this
845 * performs the conversion.
847 function format_question_text($question) {
848 global $DB;
849 $formatoptions = new stdClass;
850 $formatoptions->noclean = true;
851 $formatoptions->para = false;
852 if (empty($question->questiontextformat)) {
853 $format = FORMAT_MOODLE;
854 } else {
855 $format = $question->questiontextformat;
857 $text = $question->questiontext;
858 return format_text(html_to_text($text), $format, $formatoptions);
862 * convert files into text output in the given format.
863 * @param array
864 * @param string encoding method
865 * @return string $string
867 function writefiles($files, $encoding='base64') {
868 if (empty($files)) {
869 return '';
871 $string = '';
872 foreach ($files as $file) {
873 if ($file->is_directory()) {
874 continue;
876 $string .= '<file ';
877 $string .= ('name="' . $file->get_filename() . '"');
878 $string .= (' encoding="' . $encoding . '"');
879 $string .= '>';
880 $string .= base64_encode($file->get_content());
881 //$string .= 'base64';
882 $string .= '</file>';
884 return $string;