rss MDL-25076 made forum rss feeds that are displaying discussions instead of posts...
[moodle.git] / question / format.php
CommitLineData
aeb15530 1<?php
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;
2c44a3d3 15 var $questions = array();
aca318e1 16 var $course = NULL;
08892d5b 17 var $filename = '';
73b7b195 18 var $realfilename = '';
08892d5b 19 var $matchgrades = 'error';
20 var $catfromfile = 0;
271e6dec 21 var $contextfromfile = 0;
f1abd39f 22 var $cattofile = 0;
271e6dec 23 var $contexttofile = 0;
aca318e1 24 var $questionids = array();
f3701561 25 var $importerrors = 0;
26 var $stoponerror = true;
271e6dec 27 var $translator = null;
1b8b535d 28 var $canaccessbackupdata = true;
271e6dec 29
aca318e1 30
31// functions to indicate import/export functionality
32// override to return true if implemented
33
34 function provide_import() {
35 return false;
36 }
37
38 function provide_export() {
39 return false;
40 }
41
08892d5b 42// Accessor methods
aca318e1 43
08892d5b 44 /**
45 * set the category
46 * @param object category the category object
47 */
48 function setCategory( $category ) {
88bc20c3 49 if (count($this->questions)){
50 debugging('You shouldn\'t call setCategory after setQuestions');
51 }
08892d5b 52 $this->category = $category;
53 }
aca318e1 54
2c44a3d3 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
60 */
61 function setQuestions( $questions ) {
88bc20c3 62 if ($this->category !== null){
63 debugging('You shouldn\'t call setQuestions after setCategory');
64 }
2c44a3d3 65 $this->questions = $questions;
66 }
67
08892d5b 68 /**
69 * set the course class variable
70 * @param course object Moodle course variable
71 */
72 function setCourse( $course ) {
aca318e1 73 $this->course = $course;
08892d5b 74 }
271e6dec 75 /**
76 * set an array of contexts.
77 * @param array $contexts Moodle course variable
78 */
79 function setContexts($contexts) {
80 $this->contexts = $contexts;
81 $this->translator = new context_to_string_translator($this->contexts);
82 }
aca318e1 83
08892d5b 84 /**
85 * set the filename
86 * @param string filename name of file to import/export
87 */
88 function setFilename( $filename ) {
89 $this->filename = $filename;
90 }
88bc20c3 91
92 /**
73b7b195 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
96 */
97 function setRealfilename( $realfilename ) {
88bc20c3 98 $this->realfilename = $realfilename;
99 }
08892d5b 100
101 /**
102 * set matchgrades
103 * @param string matchgrades error or nearest for grades
104 */
105 function setMatchgrades( $matchgrades ) {
106 $this->matchgrades = $matchgrades;
aca318e1 107 }
108
76f0a334 109 /**
08892d5b 110 * set catfromfile
111 * @param bool catfromfile allow categories embedded in import file
76f0a334 112 */
08892d5b 113 function setCatfromfile( $catfromfile ) {
114 $this->catfromfile = $catfromfile;
115 }
271e6dec 116
117 /**
118 * set contextfromfile
119 * @param bool $contextfromfile allow contexts embedded in import file
120 */
121 function setContextfromfile($contextfromfile) {
122 $this->contextfromfile = $contextfromfile;
123 }
124
f1abd39f 125 /**
126 * set cattofile
127 * @param bool cattofile exports categories within export file
128 */
129 function setCattofile( $cattofile ) {
130 $this->cattofile = $cattofile;
271e6dec 131 }
132 /**
133 * set contexttofile
134 * @param bool cattofile exports categories within export file
135 */
136 function setContexttofile($contexttofile) {
137 $this->contexttofile = $contexttofile;
138 }
aca318e1 139
f3701561 140 /**
141 * set stoponerror
142 * @param bool stoponerror stops database write if any errors reported
143 */
144 function setStoponerror( $stoponerror ) {
145 $this->stoponerror = $stoponerror;
146 }
147
1b8b535d 148 /**
149 * @param boolean $canaccess Whether the current use can access the backup data folder. Determines
150 * where export files are saved.
151 */
152 function set_can_access_backupdata($canaccess) {
153 $this->canaccessbackupdata = $canaccess;
154 }
155
f3701561 156/***********************
157 * IMPORTING FUNCTIONS
158 ***********************/
159
160 /**
161 * Handle parsing error
162 */
163 function error( $message, $text='', $questionname='' ) {
cdeabc06 164 $importerrorquestion = get_string('importerrorquestion','quiz');
165
f3701561 166 echo "<div class=\"importerror\">\n";
cdeabc06 167 echo "<strong>$importerrorquestion $questionname</strong>";
f3701561 168 if (!empty($text)) {
169 $text = s($text);
170 echo "<blockquote>$text</blockquote>\n";
171 }
172 echo "<strong>$message</strong>\n";
173 echo "</div>";
174
175 $this->importerrors++;
176 }
08892d5b 177
271e6dec 178 /**
a41e3287 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
88bc20c3 184 * @param qtypehint hint about a question type from format
a41e3287 185 * @return object question object suitable for save_options() or false if cannot handle
186 */
88bc20c3 187 function try_importing_using_qtypes( $data, $question=null, $extra=null, $qtypehint='') {
a41e3287 188 global $QTYPES;
189
190 // work out what format we are using
88bc20c3 191 $formatname = substr(get_class($this), strlen('qformat_'));
a41e3287 192 $methodname = "import_from_$formatname";
193
88bc20c3 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;
201 }
202 }
203 }
204
a41e3287 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;
211 }
212 }
271e6dec 213 }
214 return false;
a41e3287 215 }
216
08892d5b 217 /**
218 * Perform any required pre-processing
f3701561 219 * @return boolean success
08892d5b 220 */
221 function importpreprocess() {
222 return true;
223 }
224
225 /**
226 * Process the file
227 * This method should not normally be overidden
f3701561 228 * @return boolean success
08892d5b 229 */
230 function importprocess() {
fef8f84e 231 global $USER, $DB, $OUTPUT;
f3701561 232
67c12527 233 // reset the timer in case file upload was slow
07ea9560 234 @set_time_limit(0);
67c12527 235
f3701561 236 // STAGE 1: Parse the file
fef8f84e 237 echo $OUTPUT->notification( get_string('parsingquestions','quiz') );
271e6dec 238
08892d5b 239 if (! $lines = $this->readdata($this->filename)) {
fef8f84e 240 echo $OUTPUT->notification( get_string('cannotread','quiz') );
aca318e1 241 return false;
242 }
243
244 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
fef8f84e 245 echo $OUTPUT->notification( get_string('noquestionsinfile','quiz') );
aca318e1 246 return false;
247 }
248
f3701561 249 // STAGE 2: Write data to database
fef8f84e 250 echo $OUTPUT->notification( get_string('importingquestions','quiz',$this->count_questions($questions)) );
aca318e1 251
f3701561 252 // check for errors before we continue
253 if ($this->stoponerror and ($this->importerrors>0)) {
fef8f84e 254 echo $OUTPUT->notification( get_string('importparseerror','quiz') );
10b4a508 255 return true;
f3701561 256 }
257
76f0a334 258 // get list of valid answer grades
259 $grades = get_grade_options();
260 $gradeoptionsfull = $grades->gradeoptionsfull;
261
c1828e0b 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;
274 }
275 else {
276 $fractions[$key] = $newfraction;
277 }
278 }
279 if (!$answersvalid) {
fef8f84e 280 echo $OUTPUT->notification(get_string('matcherror', 'quiz'));
c1828e0b 281 ++$gradeerrors;
282 continue;
283 }
284 else {
285 $question->fraction = $fractions;
286 }
287 }
288 $goodquestions[] = $question;
289 }
290 $questions = $goodquestions;
291
292 // check for errors before we continue
293 if ($this->stoponerror and ($gradeerrors>0)) {
294 return false;
295 }
296
297 // count number of questions processed
aca318e1 298 $count = 0;
299
300 foreach ($questions as $question) { // Process and store each question
08892d5b 301
271e6dec 302 // reset the php timeout
07ea9560 303 @set_time_limit(0);
67c12527 304
08892d5b 305 // check for category modifiers
306 if ($question->qtype=='category') {
307 if ($this->catfromfile) {
308 // find/create category object
40e71443 309 $catpath = $question->category;
728d60a1 310 $newcategory = $this->create_category_path($catpath);
08892d5b 311 if (!empty($newcategory)) {
312 $this->category = $newcategory;
313 }
314 }
271e6dec 315 continue;
08892d5b 316 }
317
aca318e1 318 $count++;
319
5b0dc681 320 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
aca318e1 321
322 $question->category = $this->category->id;
323 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 324
271e6dec 325 $question->createdby = $USER->id;
326 $question->timecreated = time();
327
bb4b6010 328 $question->id = $DB->insert_record("question", $question);
aca318e1 329
330 $this->questionids[] = $question->id;
331
332 // Now to save all the answers and type-specific options
333
334 global $QTYPES;
335 $result = $QTYPES[$question->qtype]
336 ->save_question_options($question);
337
338 if (!empty($result->error)) {
fef8f84e 339 echo $OUTPUT->notification($result->error);
aca318e1 340 return false;
341 }
342
343 if (!empty($result->notice)) {
fef8f84e 344 echo $OUTPUT->notification($result->notice);
aca318e1 345 return true;
346 }
cbe20043 347
348 // Give the question a unique version stamp determined by question_hash()
e5d7d1dc 349 $DB->set_field('question', 'version', question_hash($question), array('id'=>$question->id));
aca318e1 350 }
351 return true;
352 }
ce2df288 353 /**
354 * Count all non-category questions in the questions array.
f34488b2 355 *
ce2df288 356 * @param array questions An array of question objects.
357 * @return int The count.
f34488b2 358 *
ce2df288 359 */
360 function count_questions($questions) {
361 $count = 0;
362 if (!is_array($questions)) {
363 return $count;
364 }
365 foreach ($questions as $question) {
366 if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) {
367 continue;
368 }
369 $count++;
370 }
371 return $count;
372 }
373
271e6dec 374 /**
375 * find and/or create the category described by a delimited list
376 * e.g. $course$/tom/dick/harry or tom/dick/harry
377 *
378 * removes any context string no matter whether $getcontext is set
379 * but if $getcontext is set then ignore the context and use selected category context.
380 *
381 * @param string catpath delimited category path
271e6dec 382 * @param int courseid course to search for categories
383 * @return mixed category object or null if fails
384 */
728d60a1 385 function create_category_path($catpath) {
f34488b2 386 global $DB;
728d60a1 387 $catnames = $this->split_category_path($catpath);
271e6dec 388 $parent = 0;
389 $category = null;
88bc20c3 390
5ca9e32d 391 // check for context id in path, it might not be there in pre 1.9 exports
392 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
393 if ($matchcount==1) {
271e6dec 394 $contextid = $this->translator->string_to_context($matches[1]);
395 array_shift($catnames);
396 } else {
728d60a1 397 $contextid = false;
271e6dec 398 }
728d60a1
TH
399
400 if ($this->contextfromfile && $contextid !== false) {
271e6dec 401 $context = get_context_instance_by_id($contextid);
402 require_capability('moodle/question:add', $context);
403 } else {
404 $context = get_context_instance_by_id($this->category->contextid);
405 }
728d60a1
TH
406
407 // Now create any categories that need to be created.
271e6dec 408 foreach ($catnames as $catname) {
f34488b2 409 if ($category = $DB->get_record( 'question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
271e6dec 410 $parent = $category->id;
411 } else {
412 require_capability('moodle/question:managecategory', $context);
413 // create the new category
7f389342 414 $category = new stdClass();
271e6dec 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();
bf8e93d7 421 $id = $DB->insert_record('question_categories', $category);
271e6dec 422 $category->id = $id;
423 $parent = $id;
424 }
425 }
426 return $category;
427 }
3f5633df 428
f3701561 429 /**
430 * Return complete file within an array, one item per line
431 * @param string filename name of file
432 * @return mixed contents array or false on failure
433 */
aca318e1 434 function readdata($filename) {
aca318e1 435 if (is_readable($filename)) {
436 $filearray = file($filename);
437
438 /// Check for Macintosh OS line returns (ie file on one line), and fix
6dbcacee 439 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
aca318e1 440 return explode("\r", $filearray[0]);
441 } else {
442 return $filearray;
443 }
444 }
445 return false;
446 }
447
f3701561 448 /**
271e6dec 449 * Parses an array of lines into an array of questions,
450 * where each item is a question object as defined by
451 * readquestion(). Questions are defined as anything
f3701561 452 * between blank lines.
453 *
454 * If your format does not use blank lines as a delimiter
455 * then you will need to override this method. Even then
456 * try to use readquestion for each question
457 * @param array lines array of lines from readdata
458 * @return array array of question objects
459 */
aca318e1 460 function readquestions($lines) {
271e6dec 461
aca318e1 462 $questions = array();
463 $currentquestion = array();
464
465 foreach ($lines as $line) {
466 $line = trim($line);
467 if (empty($line)) {
468 if (!empty($currentquestion)) {
469 if ($question = $this->readquestion($currentquestion)) {
470 $questions[] = $question;
471 }
472 $currentquestion = array();
473 }
474 } else {
475 $currentquestion[] = $line;
476 }
477 }
478
479 if (!empty($currentquestion)) { // There may be a final question
480 if ($question = $this->readquestion($currentquestion)) {
481 $questions[] = $question;
482 }
483 }
484
485 return $questions;
486 }
487
488
f3701561 489 /**
490 * return an "empty" question
491 * Somewhere to specify question parameters that are not handled
492 * by import but are required db fields.
493 * This should not be overridden.
494 * @return object default question
271e6dec 495 */
aca318e1 496 function defaultquestion() {
b0679efa 497 global $CFG;
0cd46577 498 static $defaultshuffleanswers = null;
499 if (is_null($defaultshuffleanswers)) {
500 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
501 }
271e6dec 502
aca318e1 503 $question = new stdClass();
0cd46577 504 $question->shuffleanswers = $defaultshuffleanswers;
aca318e1 505 $question->defaultgrade = 1;
506 $question->image = "";
507 $question->usecase = 0;
508 $question->multiplier = array();
172f6d95 509 $question->generalfeedback = '';
08892d5b 510 $question->correctfeedback = '';
511 $question->partiallycorrectfeedback = '';
512 $question->incorrectfeedback = '';
5931ea94 513 $question->answernumbering = 'abc';
46013523 514 $question->penalty = 0.1;
3f5633df 515 $question->length = 1;
aca318e1 516
5fd8f999 517 // this option in case the questiontypes class wants
518 // to know where the data came from
519 $question->export_process = true;
093414d2 520 $question->import_process = true;
5fd8f999 521
aca318e1 522 return $question;
523 }
524
f3701561 525 /**
271e6dec 526 * Given the data known to define a question in
527 * this format, this function converts it into a question
f3701561 528 * object suitable for processing and insertion into Moodle.
529 *
530 * If your format does not use blank lines to delimit questions
531 * (e.g. an XML format) you must override 'readquestions' too
532 * @param $lines mixed data that represents question
533 * @return object question object
534 */
aca318e1 535 function readquestion($lines) {
aca318e1 536
1e3d6fd8 537 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
538 echo "<p>$formatnotimplemented</p>";
aca318e1 539
540 return NULL;
541 }
542
f3701561 543 /**
544 * Override if any post-processing is required
545 * @return boolean success
546 */
aca318e1 547 function importpostprocess() {
aca318e1 548 return true;
549 }
550
f3701561 551 /**
552 * Import an image file encoded in base64 format
553 * @param string path path (in course data) to store picture
554 * @param string base64 encoded picture
555 * @return string filename (nb. collisions are handled)
556 */
d08e16b2 557 function importimagefile( $path, $base64 ) {
d08e16b2 558 global $CFG;
559
bec167f3
PS
560 //TODO: MDL-16094
561 throw new coding_exception('importimagefile() was not converted to new file api yet, sorry - see MDL-16094');
562
d08e16b2 563 // all this to get the destination directory
564 // and filename!
565 $fullpath = "{$CFG->dataroot}/{$this->course->id}/$path";
566 $path_parts = pathinfo( $fullpath );
567 $destination = $path_parts['dirname'];
568 $file = clean_filename( $path_parts['basename'] );
569
71735794 570 // check if path exists
571 check_dir_exists($destination, true, true );
572
d08e16b2 573 // detect and fix any filename collision - get unique filename
271e6dec 574 $newfiles = resolve_filename_collisions( $destination, array($file) );
d08e16b2 575 $newfile = $newfiles[0];
576
577 // convert and save file contents
578 if (!$content = base64_decode( $base64 )) {
46013523 579 return '';
d08e16b2 580 }
581 $newfullpath = "$destination/$newfile";
582 if (!$fh = fopen( $newfullpath, 'w' )) {
46013523 583 return '';
d08e16b2 584 }
585 if (!fwrite( $fh, $content )) {
46013523 586 return '';
d08e16b2 587 }
588 fclose( $fh );
589
590 // return the (possibly) new filename
6dbcacee 591 $newfile = preg_replace("~{$CFG->dataroot}/{$this->course->id}/~", '',$newfullpath);
d08e16b2 592 return $newfile;
593 }
594
3f5633df 595
f3701561 596/*******************
597 * EXPORT FUNCTIONS
598 *******************/
aca318e1 599
271e6dec 600 /**
a41e3287 601 * Provide export functionality for plugin questiontypes
602 * Do not override
603 * @param name questiontype name
271e6dec 604 * @param question object data to export
a41e3287 605 * @param extra mixed any addition format specific data needed
606 * @return string the data to append to export or false if error (or unhandled)
607 */
608 function try_exporting_using_qtypes( $name, $question, $extra=null ) {
609 global $QTYPES;
610
611 // work out the name of format in use
612 $formatname = substr( get_class( $this ), strlen( 'qformat_' ));
613 $methodname = "export_to_$formatname";
614
615 if (array_key_exists( $name, $QTYPES )) {
616 $qtype = $QTYPES[ $name ];
617 if (method_exists( $qtype, $methodname )) {
618 if ($data = $qtype->$methodname( $question, $this, $extra )) {
619 return $data;
620 }
621 }
622 }
623 return false;
624 }
625
f3701561 626 /**
627 * Return the files extension appropriate for this type
628 * override if you don't want .txt
629 * @return string file extension
630 */
aca318e1 631 function export_file_extension() {
aca318e1 632 return ".txt";
633 }
634
f3701561 635 /**
636 * Do any pre-processing that may be required
637 * @param boolean success
638 */
08892d5b 639 function exportpreprocess() {
aca318e1 640 return true;
641 }
642
f3701561 643 /**
644 * Enable any processing to be done on the content
645 * just prior to the file being saved
646 * default is to do nothing
647 * @param string output text
648 * @param string processed output text
649 */
aca318e1 650 function presave_process( $content ) {
aca318e1 651 return $content;
652 }
653
f3701561 654 /**
655 * Do the export
656 * For most types this should not need to be overrided
657 * @return boolean success
658 */
08892d5b 659 function exportprocess() {
fef8f84e 660 global $CFG, $OUTPUT;
aca318e1 661
662 // create a directory for the exports (if not already existing)
1367cb8d 663 if (! $export_dir = make_upload_directory($this->question_get_export_dir())) {
5a2a5331 664 print_error('cannotcreatepath', 'quiz', $export_dir);
aca318e1 665 }
1367cb8d 666 $path = $CFG->dataroot.'/'.$this->question_get_export_dir();
aca318e1 667
668 // get the questions (from database) in this category
669 // only get q's with no parents (no cloze subquestions specifically)
2c44a3d3 670 if ($this->category){
671 $questions = get_questions_category( $this->category, true );
672 } else {
673 $questions = $this->questions;
674 }
aca318e1 675
fef8f84e 676 echo $OUTPUT->notification( get_string('exportingquestions','quiz') );
aca318e1 677 $count = 0;
678
679 // results are first written into string (and then to a file)
680 // so create/initialize the string here
681 $expout = "";
271e6dec 682
f1abd39f 683 // track which category questions are in
684 // if it changes we will record the category change in the output
685 // file if selected. 0 means that it will get printed before the 1st question
686 $trackcategory = 0;
aca318e1 687
688 // iterate through questions
689 foreach($questions as $question) {
271e6dec 690
a9b16aff 691 // do not export hidden questions
692 if (!empty($question->hidden)) {
693 continue;
694 }
695
696 // do not export random questions
697 if ($question->qtype==RANDOM) {
698 continue;
699 }
271e6dec 700
f1abd39f 701 // check if we need to record category change
702 if ($this->cattofile) {
703 if ($question->category != $trackcategory) {
271e6dec 704 $trackcategory = $question->category;
728d60a1 705 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
271e6dec 706
f1abd39f 707 // create 'dummy' question for category export
7f389342 708 $dummyquestion = new stdClass();
f1abd39f 709 $dummyquestion->qtype = 'category';
710 $dummyquestion->category = $categoryname;
728d60a1 711 $dummyquestion->name = 'Switch category to ' . $categoryname;
f1abd39f 712 $dummyquestion->id = 0;
713 $dummyquestion->questiontextformat = '';
728d60a1 714 $expout .= $this->writequestion($dummyquestion) . "\n";
271e6dec 715 }
716 }
f1abd39f 717
718 // export the question displaying message
719 $count++;
5b0dc681 720 echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
0647e82b 721 if (question_has_capability_on($question, 'view', $question->category)){
722 $expout .= $this->writequestion( $question ) . "\n";
723 }
a9b16aff 724 }
aca318e1 725
2c6d2c88 726 // continue path for following error checks
727 $course = $this->course;
2c44a3d3 728 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
2c6d2c88 729
730 // did we actually process anything
731 if ($count==0) {
2c44a3d3 732 print_error( 'noquestions','quiz',$continuepath );
2c6d2c88 733 }
734
aca318e1 735 // final pre-process on exported data
736 $expout = $this->presave_process( $expout );
271e6dec 737
aca318e1 738 // write file
08892d5b 739 $filepath = $path."/".$this->filename . $this->export_file_extension();
aca318e1 740 if (!$fh=fopen($filepath,"w")) {
2c6d2c88 741 print_error( 'cannotopen','quiz',$continuepath,$filepath );
aca318e1 742 }
f1abd39f 743 if (!fwrite($fh, $expout, strlen($expout) )) {
2c6d2c88 744 print_error( 'cannotwrite','quiz',$continuepath,$filepath );
aca318e1 745 }
746 fclose($fh);
aca318e1 747 return true;
748 }
3f5633df 749
271e6dec 750 /**
751 * get the category as a path (e.g., tom/dick/harry)
752 * @param int id the id of the most nested catgory
271e6dec 753 * @return string the path
754 */
728d60a1 755 function get_category_path($id, $includecontext = true) {
f34488b2 756 global $DB;
728d60a1
TH
757
758 if (!$category = $DB->get_record('question_categories',array('id' =>$id))) {
1e7386c9 759 print_error('cannotfindcategory', 'error', '', $id);
271e6dec 760 }
271e6dec 761 $contextstring = $this->translator->context_to_string($category->contextid);
728d60a1
TH
762
763 $pathsections = array();
271e6dec 764 do {
728d60a1 765 $pathsections[] = $category->name;
271e6dec 766 $id = $category->parent;
728d60a1 767 } while ($category = $DB->get_record( 'question_categories', array('id' => $id )));
271e6dec 768
769 if ($includecontext){
728d60a1 770 $pathsections[] = '$' . $contextstring . '$';
271e6dec 771 }
728d60a1
TH
772
773 $path = $this->assemble_category_path(array_reverse($pathsections));
774
271e6dec 775 return $path;
776 }
aca318e1 777
728d60a1
TH
778 /**
779 * Convert a list of category names, possibly preceeded by one of the
780 * context tokens like $course$, into a string representation of the
781 * category path.
782 *
783 * Names are separated by / delimiters. And /s in the name are replaced by //.
784 *
785 * To reverse the process and split the paths into names, use
786 * {@link split_category_path()}.
787 *
788 * @param array $names
789 * @return string
790 */
791 protected function assemble_category_path($names) {
792 $escapednames = array();
793 foreach ($names as $name) {
794 $escapedname = str_replace('/', '//', $name);
795 if (substr($escapedname, 0, 1) == '/') {
796 $escapedname = ' ' . $escapedname;
797 }
798 if (substr($escapedname, -1) == '/') {
799 $escapedname = $escapedname . ' ';
800 }
801 $escapednames[] = $escapedname;
802 }
803 return implode('/', $escapednames);
804 }
805
806 /**
807 * Convert a string, as returned by {@link assemble_category_path()},
808 * back into an array of category names.
809 *
810 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
aab03169 811 * which matches the cleaning in question/category_form.php.
728d60a1
TH
812 *
813 * @param string $path
814 * @return array of category names.
815 */
816 protected function split_category_path($path) {
817 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
818 $names = array();
819 foreach ($rawnames as $rawname) {
820 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
821 }
822 return $names;
823 }
824
f3701561 825 /**
826 * Do an post-processing that may be required
827 * @return boolean success
828 */
aca318e1 829 function exportpostprocess() {
aca318e1 830 return true;
831 }
832
f3701561 833 /**
834 * convert a single question object into text output in the given
835 * format.
836 * This must be overriden
837 * @param object question question object
838 * @return mixed question export text or null if not implemented
839 */
aca318e1 840 function writequestion($question) {
1e3d6fd8 841 // if not overidden, then this is an error.
842 $formatnotimplemented = get_string( 'formatnotimplemented','quiz' );
843 echo "<p>$formatnotimplemented</p>";
aca318e1 844 return NULL;
845 }
846
f3701561 847 /**
271e6dec 848 * get directory into which export is going
f3701561 849 * @return string file path
850 */
1367cb8d 851 function question_get_export_dir() {
1b8b535d 852 global $USER;
853 if ($this->canaccessbackupdata) {
854 $dirname = get_string("exportfilename","quiz");
855 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
856 } else {
857 $path = 'temp/questionexport/' . $USER->id;
858 }
1367cb8d 859 return $path;
860 }
861
f3701561 862 /**
863 * where question specifies a moodle (text) format this
864 * performs the conversion.
865 */
5b0dc681 866 function format_question_text($question) {
fe6ce234 867 global $DB;
5b0dc681 868 $formatoptions = new stdClass;
869 $formatoptions->noclean = true;
870 $formatoptions->para = false;
871 if (empty($question->questiontextformat)) {
872 $format = FORMAT_MOODLE;
873 } else {
874 $format = $question->questiontextformat;
875 }
fe6ce234
DC
876 $text = $question->questiontext;
877 return format_text(html_to_text($text), $format, $formatoptions);
5b0dc681 878 }
aca318e1 879}