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