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