MDL-20636 Finish off converting question import.
[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 */
49e2bba7
TH
205 function try_importing_using_qtypes($data, $question = null, $extra = null,
206 $qtypehint = '') {
a41e3287 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)) {
49e2bba7 214 $qtype = question_bank::get_qtype($qtypehint, false);
88bc20c3 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
49e2bba7 225 foreach (question_bank::get_all_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
49e2bba7 246 * @param object $category
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 258 // STAGE 1: Parse the file
f7c1dfaf 259 echo $OUTPUT->notification(get_string('parsingquestions','quiz'), 'notifysuccess');
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
f7c1dfaf
TH
272 echo $OUTPUT->notification(get_string('importingquestions', 'quiz',
273 $this->count_questions($questions)), 'notifysuccess');
aca318e1 274
f3701561 275 // check for errors before we continue
276 if ($this->stoponerror and ($this->importerrors>0)) {
13bb604e 277 echo $OUTPUT->notification(get_string('importparseerror','quiz'));
10b4a508 278 return true;
f3701561 279 }
280
76f0a334 281 // get list of valid answer grades
282 $grades = get_grade_options();
283 $gradeoptionsfull = $grades->gradeoptionsfull;
284
c1828e0b 285 // check answer grades are valid
286 // (now need to do this here because of 'stop on error': MDL-10689)
287 $gradeerrors = 0;
288 $goodquestions = array();
289 foreach ($questions as $question) {
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
49e2bba7 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);
49e2bba7 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;
49e2bba7 543 $question->defaultmark = 1;
aca318e1 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';
49e2bba7 552 $question->penalty = 0.3333333;
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
aca318e1 655 $count = 0;
656
657 // results are first written into string (and then to a file)
658 // so create/initialize the string here
659 $expout = "";
271e6dec 660
f1abd39f 661 // track which category questions are in
662 // if it changes we will record the category change in the output
663 // file if selected. 0 means that it will get printed before the 1st question
664 $trackcategory = 0;
aca318e1 665
666 // iterate through questions
667 foreach($questions as $question) {
cde2709a
DC
668 // used by file api
669 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$question->category));
670 $question->contextid = $contextid;
271e6dec 671
a9b16aff 672 // do not export hidden questions
673 if (!empty($question->hidden)) {
674 continue;
675 }
676
677 // do not export random questions
678 if ($question->qtype==RANDOM) {
679 continue;
680 }
271e6dec 681
f1abd39f 682 // check if we need to record category change
683 if ($this->cattofile) {
684 if ($question->category != $trackcategory) {
271e6dec 685 $trackcategory = $question->category;
728d60a1 686 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
271e6dec 687
f1abd39f 688 // create 'dummy' question for category export
7f389342 689 $dummyquestion = new stdClass();
f1abd39f 690 $dummyquestion->qtype = 'category';
691 $dummyquestion->category = $categoryname;
728d60a1 692 $dummyquestion->name = 'Switch category to ' . $categoryname;
f1abd39f 693 $dummyquestion->id = 0;
694 $dummyquestion->questiontextformat = '';
cde2709a 695 $dummyquestion->contextid = 0;
728d60a1 696 $expout .= $this->writequestion($dummyquestion) . "\n";
271e6dec 697 }
698 }
f1abd39f 699
700 // export the question displaying message
701 $count++;
cde2709a 702
cde2709a 703 if (question_has_capability_on($question, 'view', $question->category)) {
cde2709a 704 $expout .= $this->writequestion($question, $contextid) . "\n";
0647e82b 705 }
a9b16aff 706 }
aca318e1 707
2c6d2c88 708 // continue path for following error checks
709 $course = $this->course;
2c44a3d3 710 $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
2c6d2c88 711
712 // did we actually process anything
713 if ($count==0) {
49e2bba7 714 print_error('noquestions', 'quiz', $continuepath);
2c6d2c88 715 }
716
aca318e1 717 // final pre-process on exported data
cde2709a
DC
718 $expout = $this->presave_process($expout);
719 return $expout;
aca318e1 720 }
3f5633df 721
271e6dec 722 /**
723 * get the category as a path (e.g., tom/dick/harry)
724 * @param int id the id of the most nested catgory
271e6dec 725 * @return string the path
726 */
728d60a1 727 function get_category_path($id, $includecontext = true) {
f34488b2 728 global $DB;
728d60a1
TH
729
730 if (!$category = $DB->get_record('question_categories',array('id' =>$id))) {
1e7386c9 731 print_error('cannotfindcategory', 'error', '', $id);
271e6dec 732 }
271e6dec 733 $contextstring = $this->translator->context_to_string($category->contextid);
728d60a1
TH
734
735 $pathsections = array();
271e6dec 736 do {
728d60a1 737 $pathsections[] = $category->name;
271e6dec 738 $id = $category->parent;
13bb604e 739 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
271e6dec 740
13bb604e 741 if ($includecontext) {
728d60a1 742 $pathsections[] = '$' . $contextstring . '$';
271e6dec 743 }
728d60a1
TH
744
745 $path = $this->assemble_category_path(array_reverse($pathsections));
746
271e6dec 747 return $path;
748 }
aca318e1 749
728d60a1
TH
750 /**
751 * Convert a list of category names, possibly preceeded by one of the
752 * context tokens like $course$, into a string representation of the
753 * category path.
754 *
755 * Names are separated by / delimiters. And /s in the name are replaced by //.
756 *
757 * To reverse the process and split the paths into names, use
758 * {@link split_category_path()}.
759 *
760 * @param array $names
761 * @return string
762 */
763 protected function assemble_category_path($names) {
764 $escapednames = array();
765 foreach ($names as $name) {
766 $escapedname = str_replace('/', '//', $name);
767 if (substr($escapedname, 0, 1) == '/') {
768 $escapedname = ' ' . $escapedname;
769 }
770 if (substr($escapedname, -1) == '/') {
771 $escapedname = $escapedname . ' ';
772 }
773 $escapednames[] = $escapedname;
774 }
775 return implode('/', $escapednames);
776 }
777
778 /**
779 * Convert a string, as returned by {@link assemble_category_path()},
780 * back into an array of category names.
781 *
782 * Each category name is cleaned by a call to clean_param(, PARAM_MULTILANG),
aab03169 783 * which matches the cleaning in question/category_form.php.
728d60a1
TH
784 *
785 * @param string $path
786 * @return array of category names.
787 */
788 protected function split_category_path($path) {
789 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
790 $names = array();
791 foreach ($rawnames as $rawname) {
792 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_MULTILANG);
793 }
794 return $names;
795 }
796
f3701561 797 /**
798 * Do an post-processing that may be required
799 * @return boolean success
800 */
aca318e1 801 function exportpostprocess() {
aca318e1 802 return true;
803 }
804
f3701561 805 /**
806 * convert a single question object into text output in the given
807 * format.
808 * This must be overriden
809 * @param object question question object
810 * @return mixed question export text or null if not implemented
811 */
aca318e1 812 function writequestion($question) {
1e3d6fd8 813 // if not overidden, then this is an error.
13bb604e 814 $formatnotimplemented = get_string('formatnotimplemented','quiz');
1e3d6fd8 815 echo "<p>$formatnotimplemented</p>";
aca318e1 816 return NULL;
817 }
818
f3701561 819 /**
271e6dec 820 * get directory into which export is going
f3701561 821 * @return string file path
822 */
1367cb8d 823 function question_get_export_dir() {
1b8b535d 824 global $USER;
825 if ($this->canaccessbackupdata) {
826 $dirname = get_string("exportfilename","quiz");
827 $path = $this->course->id.'/backupdata/'.$dirname; // backupdata is protected directory
828 } else {
829 $path = 'temp/questionexport/' . $USER->id;
830 }
1367cb8d 831 return $path;
832 }
833
f3701561 834 /**
13bb604e
TH
835 * Convert the question text to plain text, so it can safely be displayed
836 * during import to let the user see roughly what is going on.
f3701561 837 */
5b0dc681 838 function format_question_text($question) {
fe6ce234 839 global $DB;
5b0dc681 840 $formatoptions = new stdClass;
841 $formatoptions->noclean = true;
842 $formatoptions->para = false;
843 if (empty($question->questiontextformat)) {
844 $format = FORMAT_MOODLE;
845 } else {
846 $format = $question->questiontextformat;
847 }
fe6ce234 848 $text = $question->questiontext;
13bb604e 849 return format_text(html_to_text($text, 0, false), $format, $formatoptions);
5b0dc681 850 }
cde2709a
DC
851
852 /**
853 * convert files into text output in the given format.
854 * @param array
855 * @param string encoding method
856 * @return string $string
857 */
858 function writefiles($files, $encoding='base64') {
859 if (empty($files)) {
860 return '';
861 }
862 $string = '';
863 foreach ($files as $file) {
864 if ($file->is_directory()) {
865 continue;
866 }
06f1bd03 867 $string .= '<file name="' . $file->get_filename() . '" encoding="' . $encoding . '">';
cde2709a 868 $string .= base64_encode($file->get_content());
cde2709a
DC
869 $string .= '</file>';
870 }
871 return $string;
872 }
aca318e1 873}