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