MDL-10181, user management improvements, adding improvements to bulk user upload...
[moodle.git] / question / format.php
CommitLineData
271e6dec 1<?php // $Id$
4323d029 2/**
3 * Base class for question import and export formats.
4 *
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
4323d029 10 */
f5565b69 11class qformat_default {
aca318e1 12
f1abd39f 13 var $displayerrors = true;
aca318e1 14 var $category = NULL;
15 var $course = NULL;
08892d5b 16 var $filename = '';
17 var $matchgrades = 'error';
18 var $catfromfile = 0;
271e6dec 19 var $contextfromfile = 0;
f1abd39f 20 var $cattofile = 0;
271e6dec 21 var $contexttofile = 0;
aca318e1 22 var $questionids = array();
f3701561 23 var $importerrors = 0;
24 var $stoponerror = true;
271e6dec 25 var $translator = null;
26
aca318e1 27
28// functions to indicate import/export functionality
29// override to return true if implemented
30
31 function provide_import() {
32 return false;
33 }
34
35 function provide_export() {
36 return false;
37 }
38
08892d5b 39// Accessor methods
aca318e1 40
08892d5b 41 /**
42 * set the category
43 * @param object category the category object
44 */
45 function setCategory( $category ) {
46 $this->category = $category;
47 }
aca318e1 48
08892d5b 49 /**
50 * set the course class variable
51 * @param course object Moodle course variable
52 */
53 function setCourse( $course ) {
aca318e1 54 $this->course = $course;
08892d5b 55 }
271e6dec 56 /**
57 * set an array of contexts.
58 * @param array $contexts Moodle course variable
59 */
60 function setContexts($contexts) {
61 $this->contexts = $contexts;
62 $this->translator = new context_to_string_translator($this->contexts);
63 }
aca318e1 64
08892d5b 65 /**
66 * set the filename
67 * @param string filename name of file to import/export
68 */
69 function setFilename( $filename ) {
70 $this->filename = $filename;
71 }
72
73 /**
74 * set matchgrades
75 * @param string matchgrades error or nearest for grades
76 */
77 function setMatchgrades( $matchgrades ) {
78 $this->matchgrades = $matchgrades;
aca318e1 79 }
80
76f0a334 81 /**
08892d5b 82 * set catfromfile
83 * @param bool catfromfile allow categories embedded in import file
76f0a334 84 */
08892d5b 85 function setCatfromfile( $catfromfile ) {
86 $this->catfromfile = $catfromfile;
87 }
271e6dec 88
89 /**
90 * set contextfromfile
91 * @param bool $contextfromfile allow contexts embedded in import file
92 */
93 function setContextfromfile($contextfromfile) {
94 $this->contextfromfile = $contextfromfile;
95 }
96
f1abd39f 97 /**
98 * set cattofile
99 * @param bool cattofile exports categories within export file
100 */
101 function setCattofile( $cattofile ) {
102 $this->cattofile = $cattofile;
271e6dec 103 }
104 /**
105 * set contexttofile
106 * @param bool cattofile exports categories within export file
107 */
108 function setContexttofile($contexttofile) {
109 $this->contexttofile = $contexttofile;
110 }
aca318e1 111
f3701561 112 /**
113 * set stoponerror
114 * @param bool stoponerror stops database write if any errors reported
115 */
116 function setStoponerror( $stoponerror ) {
117 $this->stoponerror = $stoponerror;
118 }
119
120/***********************
121 * IMPORTING FUNCTIONS
122 ***********************/
123
124 /**
125 * Handle parsing error
126 */
127 function error( $message, $text='', $questionname='' ) {
cdeabc06 128 $importerrorquestion = get_string('importerrorquestion','quiz');
129
f3701561 130 echo "<div class=\"importerror\">\n";
cdeabc06 131 echo "<strong>$importerrorquestion $questionname</strong>";
f3701561 132 if (!empty($text)) {
133 $text = s($text);
134 echo "<blockquote>$text</blockquote>\n";
135 }
136 echo "<strong>$message</strong>\n";
137 echo "</div>";
138
139 $this->importerrors++;
140 }
08892d5b 141
271e6dec 142 /**
a41e3287 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
149 */
150 function try_importing_using_qtypes( $data, $question=null, $extra=null ) {
151 global $QTYPES;
152
153 // work out what format we are using
154 $formatname = substr( get_class( $this ), strlen('qformat_'));
155 $methodname = "import_from_$formatname";
156
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;
163 }
164 }
271e6dec 165 }
166 return false;
a41e3287 167 }
168
08892d5b 169 /**
170 * Perform any required pre-processing
f3701561 171 * @return boolean success
08892d5b 172 */
173 function importpreprocess() {
174 return true;
175 }
176
177 /**
178 * Process the file
179 * This method should not normally be overidden
f3701561 180 * @return boolean success
08892d5b 181 */
182 function importprocess() {
271e6dec 183 global $USER;
f3701561 184
67c12527 185 // reset the timer in case file upload was slow
186 @set_time_limit();
187
f3701561 188 // STAGE 1: Parse the file
189 notify( get_string('parsingquestions','quiz') );
271e6dec 190
08892d5b 191 if (! $lines = $this->readdata($this->filename)) {
1e3d6fd8 192 notify( get_string('cannotread','quiz') );
aca318e1 193 return false;
194 }
195
196 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
1e3d6fd8 197 notify( get_string('noquestionsinfile','quiz') );
aca318e1 198 return false;
199 }
200
f3701561 201 // STAGE 2: Write data to database
1e3d6fd8 202 notify( get_string('importingquestions','quiz',count($questions)) );
aca318e1 203
f3701561 204 // check for errors before we continue
205 if ($this->stoponerror and ($this->importerrors>0)) {
206 return false;
207 }
208
76f0a334 209 // get list of valid answer grades
210 $grades = get_grade_options();
211 $gradeoptionsfull = $grades->gradeoptionsfull;
212
aca318e1 213 $count = 0;
214
215 foreach ($questions as $question) { // Process and store each question
08892d5b 216
271e6dec 217 // reset the php timeout
67c12527 218 @set_time_limit();
219
08892d5b 220 // check for category modifiers
221 if ($question->qtype=='category') {
222 if ($this->catfromfile) {
223 // find/create category object
224 $catpath = $question->category;
271e6dec 225 $newcategory = $this->create_category_path( $catpath, '/');
08892d5b 226 if (!empty($newcategory)) {
227 $this->category = $newcategory;
228 }
229 }
271e6dec 230 continue;
08892d5b 231 }
232
aca318e1 233 $count++;
234
5b0dc681 235 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
aca318e1 236
76f0a334 237 // check for answer grades validity (must match fixed list of grades)
08892d5b 238 if (!empty($question->fraction) and (is_array($question->fraction))) {
656ee8c6 239 $fractions = $question->fraction;
2d52056f 240 $answersvalid = true; // in case they are!
241 foreach ($fractions as $key => $fraction) {
08892d5b 242 $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades);
2d52056f 243 if ($newfraction===false) {
244 $answersvalid = false;
245 }
246 else {
247 $fractions[$key] = $newfraction;
248 }
249 }
250 if (!$answersvalid) {
eedb2494 251 notify(get_string('matcherror', 'quiz'));
2d52056f 252 continue;
76f0a334 253 }
254 else {
2d52056f 255 $question->fraction = $fractions;
76f0a334 256 }
257 }
76f0a334 258
aca318e1 259 $question->category = $this->category->id;
260 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 261
271e6dec 262 $question->createdby = $USER->id;
263 $question->timecreated = time();
264
062f1125 265 if (!$question->id = insert_record("question", $question)) {
1e3d6fd8 266 error( get_string('cannotinsert','quiz') );
aca318e1 267 }
268
269 $this->questionids[] = $question->id;
270
271 // Now to save all the answers and type-specific options
272
273 global $QTYPES;
274 $result = $QTYPES[$question->qtype]
275 ->save_question_options($question);
276
277 if (!empty($result->error)) {
278 notify($result->error);
279 return false;
280 }
281
282 if (!empty($result->notice)) {
283 notify($result->notice);
284 return true;
285 }
cbe20043 286
287 // Give the question a unique version stamp determined by question_hash()
288 set_field('question', 'version', question_hash($question), 'id', $question->id);
aca318e1 289 }
290 return true;
291 }
271e6dec 292 /**
293 * find and/or create the category described by a delimited list
294 * e.g. $course$/tom/dick/harry or tom/dick/harry
295 *
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.
298 *
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
303 */
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;
314 }
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);
320 }
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" );
336 }
337 $category->id = $id;
338 $parent = $id;
339 }
340 }
341 return $category;
342 }
f3701561 343 /**
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
347 */
aca318e1 348 function readdata($filename) {
aca318e1 349 if (is_readable($filename)) {
350 $filearray = file($filename);
351
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;
357 }
358 }
359 return false;
360 }
361
f3701561 362 /**
271e6dec 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
f3701561 366 * between blank lines.
367 *
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
373 */
aca318e1 374 function readquestions($lines) {
271e6dec 375
aca318e1 376 $questions = array();
377 $currentquestion = array();
378
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;
385 }
386 $currentquestion = array();
387 }
388 } else {
389 $currentquestion[] = $line;
390 }
391 }
392
393 if (!empty($currentquestion)) { // There may be a final question
394 if ($question = $this->readquestion($currentquestion)) {
395 $questions[] = $question;
396 }
397 }
398
399 return $questions;
400 }
401
402
f3701561 403 /**
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
271e6dec 409 */
aca318e1 410 function defaultquestion() {
b0679efa 411 global $CFG;
271e6dec 412
aca318e1 413 $question = new stdClass();
271e6dec 414 $question->shuffleanswers = $CFG->quiz_shuffleanswers;
aca318e1 415 $question->defaultgrade = 1;
416 $question->image = "";
417 $question->usecase = 0;
418 $question->multiplier = array();
172f6d95 419 $question->generalfeedback = '';
08892d5b 420 $question->correctfeedback = '';
421 $question->partiallycorrectfeedback = '';
422 $question->incorrectfeedback = '';
5931ea94 423 $question->answernumbering = 'abc';
46013523 424 $question->penalty = 0.1;
aca318e1 425
5fd8f999 426 // this option in case the questiontypes class wants
427 // to know where the data came from
428 $question->export_process = true;
093414d2 429 $question->import_process = true;
5fd8f999 430
aca318e1 431 return $question;
432 }
433
f3701561 434 /**
271e6dec 435 * Given the data known to define a question in
436 * this format, this function converts it into a question
f3701561 437 * object suitable for processing and insertion into Moodle.
438 *
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
443 */
aca318e1 444 function readquestion($lines) {
aca318e1 445
1e3d6fd8 446 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
447 echo "<p>$formatnotimplemented</p>";
aca318e1 448
449 return NULL;
450 }
451
f3701561 452 /**
453 * Override if any post-processing is required
454 * @return boolean success
455 */
aca318e1 456 function importpostprocess() {
aca318e1 457 return true;
458 }
459
f3701561 460 /**
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)
465 */
d08e16b2 466 function importimagefile( $path, $base64 ) {
d08e16b2 467 global $CFG;
468
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'] );
475
71735794 476 // check if path exists
477 check_dir_exists($destination, true, true );
478
d08e16b2 479 // detect and fix any filename collision - get unique filename
271e6dec 480 $newfiles = resolve_filename_collisions( $destination, array($file) );
d08e16b2 481 $newfile = $newfiles[0];
482
483 // convert and save file contents
484 if (!$content = base64_decode( $base64 )) {
46013523 485 return '';
d08e16b2 486 }
487 $newfullpath = "$destination/$newfile";
488 if (!$fh = fopen( $newfullpath, 'w' )) {
46013523 489 return '';
d08e16b2 490 }
491 if (!fwrite( $fh, $content )) {
46013523 492 return '';
d08e16b2 493 }
494 fclose( $fh );
495
496 // return the (possibly) new filename
71735794 497 $newfile = ereg_replace("{$CFG->dataroot}/{$this->course->id}/", '',$newfullpath);
d08e16b2 498 return $newfile;
499 }
500
f3701561 501/*******************
502 * EXPORT FUNCTIONS
503 *******************/
aca318e1 504
271e6dec 505 /**
a41e3287 506 * Provide export functionality for plugin questiontypes
507 * Do not override
508 * @param name questiontype name
271e6dec 509 * @param question object data to export
a41e3287 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)
512 */
513 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
514 global $QTYPES;
515
516 // work out the name of format in use
517 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
518 $methodname = "export_to_$formatname";
519
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;
525 }
526 }
527 }
528 return false;
529 }
530
f3701561 531 /**
532 * Return the files extension appropriate for this type
533 * override if you don't want .txt
534 * @return string file extension
535 */
aca318e1 536 function export_file_extension() {
aca318e1 537 return ".txt";
538 }
539
f3701561 540 /**
541 * Do any pre-processing that may be required
542 * @param boolean success
543 */
08892d5b 544 function exportpreprocess() {
aca318e1 545 return true;
546 }
547
f3701561 548 /**
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
554 */
aca318e1 555 function presave_process( $content ) {
aca318e1 556 return $content;
557 }
558
f3701561 559 /**
560 * Do the export
561 * For most types this should not need to be overrided
562 * @return boolean success
563 */
08892d5b 564 function exportprocess() {
aca318e1 565 global $CFG;
566
567 // create a directory for the exports (if not already existing)
1367cb8d 568 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
569 error( get_string('cannotcreatepath','quiz',$export_dir) );
aca318e1 570 }
1367cb8d 571 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 572
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 );
576
1e3d6fd8 577 notify( get_string('exportingquestions','quiz') );
aca318e1 578 if (!count($questions)) {
1e3d6fd8 579 notify( get_string('noquestions','quiz') );
580 return false;
aca318e1 581 }
582 $count = 0;
583
584 // results are first written into string (and then to a file)
585 // so create/initialize the string here
586 $expout = "";
271e6dec 587
f1abd39f 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;
aca318e1 592
593 // iterate through questions
594 foreach($questions as $question) {
271e6dec 595
a9b16aff 596 // do not export hidden questions
597 if (!empty($question->hidden)) {
598 continue;
599 }
600
601 // do not export random questions
602 if ($question->qtype==RANDOM) {
603 continue;
604 }
271e6dec 605
f1abd39f 606 // check if we need to record category change
607 if ($this->cattofile) {
608 if ($question->category != $trackcategory) {
271e6dec 609 $trackcategory = $question->category;
610 $categoryname = $this->get_category_path($trackcategory, '/', $this->contexttofile);
611
f1abd39f 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";
271e6dec 620 }
621 }
f1abd39f 622
623 // export the question displaying message
624 $count++;
5b0dc681 625 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
f1abd39f 626 $expout .= $this->writequestion( $question ) . "\n";
a9b16aff 627 }
aca318e1 628
629 // final pre-process on exported data
630 $expout = $this->presave_process( $expout );
271e6dec 631
aca318e1 632 // write file
08892d5b 633 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 634 if (!$fh=fopen($filepath,"w")) {
1e3d6fd8 635 error( get_string('cannotopen','quiz',$filepath) );
aca318e1 636 }
f1abd39f 637 if (!fwrite($fh, $expout, strlen($expout) )) {
1e3d6fd8 638 error( get_string('cannotwrite','quiz',$filepath) );
aca318e1 639 }
640 fclose($fh);
aca318e1 641 return true;
642 }
271e6dec 643 /**
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
648 */
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" );
653 }
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}";
661 }
662 else {
663 $path = $name;
664 }
665 } while ($category = get_record( 'question_categories','id',$id ));
666
667 if ($includecontext){
668 $path = '$'.$contextstring.'$'."{$delimiter}{$path}";
669 }
670 return $path;
671 }
aca318e1 672
f3701561 673 /**
674 * Do an post-processing that may be required
675 * @return boolean success
676 */
aca318e1 677 function exportpostprocess() {
aca318e1 678 return true;
679 }
680
f3701561 681 /**
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
687 */
aca318e1 688 function writequestion($question) {
1e3d6fd8 689 // if not overidden, then this is an error.
690 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
691 echo "<p>$formatnotimplemented</p>";
aca318e1 692 return NULL;
693 }
694
f3701561 695 /**
271e6dec 696 * get directory into which export is going
f3701561 697 * @return string file path
698 */
1367cb8d 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;
703 }
704
f3701561 705 /**
706 * where question specifies a moodle (text) format this
707 * performs the conversion.
708 */
5b0dc681 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;
717 }
718 return format_text(stripslashes($question->questiontext), $format, $formatoptions);
719 }
271e6dec 720
721
aca318e1 722}
723
724?>