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