on-demand release 3.6dev+
[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
4323d029 30/**
31 * Base class for question import and export formats.
32 *
d3603157
TH
33 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4323d029 35 */
f5565b69 36class qformat_default {
aca318e1 37
13bb604e 38 public $displayerrors = true;
e0736817 39 public $category = null;
13bb604e 40 public $questions = array();
e0736817 41 public $course = null;
13bb604e
TH
42 public $filename = '';
43 public $realfilename = '';
44 public $matchgrades = 'error';
45 public $catfromfile = 0;
46 public $contextfromfile = 0;
47 public $cattofile = 0;
48 public $contexttofile = 0;
49 public $questionids = array();
50 public $importerrors = 0;
51 public $stoponerror = true;
52 public $translator = null;
53 public $canaccessbackupdata = true;
cde2709a 54 protected $importcontext = null;
1dab8faa
JB
55 /** @var bool $displayprogress Whether to display progress. */
56 public $displayprogress = true;
aca318e1 57
e198992b
TH
58 // functions to indicate import/export functionality
59 // override to return true if implemented
aca318e1 60
f7970e3c 61 /** @return bool whether this plugin provides import functionality. */
c7df5006 62 public function provide_import() {
46732124 63 return false;
aca318e1 64 }
65
f7970e3c 66 /** @return bool whether this plugin provides export functionality. */
c7df5006 67 public function provide_export() {
46732124
TH
68 return false;
69 }
70
71 /** The string mime-type of the files that this plugin reads or writes. */
c7df5006 72 public function mime_type() {
46732124
TH
73 return mimeinfo('type', $this->export_file_extension());
74 }
75
76 /**
77 * @return string the file extension (including .) that is normally used for
78 * files handled by this plugin.
79 */
c7df5006 80 public function export_file_extension() {
46732124 81 return '.txt';
aca318e1 82 }
a1ef8c6d 83
7da7bfa1
JF
84 /**
85 * Check if the given file is capable of being imported by this plugin.
86 *
87 * Note that expensive or detailed integrity checks on the file should
88 * not be performed by this method. Simple file type or magic-number tests
89 * would be suitable.
90 *
a1ef8c6d 91 * @param stored_file $file the file to check
7da7bfa1
JF
92 * @return bool whether this plugin can import the file
93 */
94 public function can_import_file($file) {
95 return ($file->get_mimetype() == $this->mime_type());
96 }
aca318e1 97
e198992b 98 // Accessor methods
aca318e1 99
08892d5b 100 /**
101 * set the category
102 * @param object category the category object
103 */
c7df5006 104 public function setCategory($category) {
13bb604e 105 if (count($this->questions)) {
88bc20c3 106 debugging('You shouldn\'t call setCategory after setQuestions');
107 }
08892d5b 108 $this->category = $category;
d197ea43 109 $this->importcontext = context::instance_by_id($this->category->contextid);
08892d5b 110 }
aca318e1 111
2c44a3d3 112 /**
113 * Set the specific questions to export. Should not include questions with
114 * parents (sub questions of cloze question type).
115 * Only used for question export.
116 * @param array of question objects
117 */
c7df5006 118 public function setQuestions($questions) {
13bb604e 119 if ($this->category !== null) {
88bc20c3 120 debugging('You shouldn\'t call setQuestions after setCategory');
121 }
2c44a3d3 122 $this->questions = $questions;
123 }
124
08892d5b 125 /**
126 * set the course class variable
127 * @param course object Moodle course variable
128 */
c7df5006 129 public function setCourse($course) {
aca318e1 130 $this->course = $course;
08892d5b 131 }
13bb604e 132
271e6dec 133 /**
134 * set an array of contexts.
135 * @param array $contexts Moodle course variable
136 */
c7df5006 137 public function setContexts($contexts) {
271e6dec 138 $this->contexts = $contexts;
139 $this->translator = new context_to_string_translator($this->contexts);
140 }
aca318e1 141
08892d5b 142 /**
143 * set the filename
144 * @param string filename name of file to import/export
145 */
c7df5006 146 public function setFilename($filename) {
08892d5b 147 $this->filename = $filename;
148 }
88bc20c3 149
150 /**
73b7b195 151 * set the "real" filename
152 * (this is what the user typed, regardless of wha happened next)
153 * @param string realfilename name of file as typed by user
154 */
c7df5006 155 public function setRealfilename($realfilename) {
88bc20c3 156 $this->realfilename = $realfilename;
157 }
08892d5b 158
159 /**
160 * set matchgrades
161 * @param string matchgrades error or nearest for grades
162 */
c7df5006 163 public function setMatchgrades($matchgrades) {
08892d5b 164 $this->matchgrades = $matchgrades;
aca318e1 165 }
166
76f0a334 167 /**
08892d5b 168 * set catfromfile
169 * @param bool catfromfile allow categories embedded in import file
76f0a334 170 */
c7df5006 171 public function setCatfromfile($catfromfile) {
08892d5b 172 $this->catfromfile = $catfromfile;
173 }
271e6dec 174
175 /**
176 * set contextfromfile
177 * @param bool $contextfromfile allow contexts embedded in import file
178 */
c7df5006 179 public function setContextfromfile($contextfromfile) {
271e6dec 180 $this->contextfromfile = $contextfromfile;
181 }
182
f1abd39f 183 /**
184 * set cattofile
185 * @param bool cattofile exports categories within export file
186 */
c7df5006 187 public function setCattofile($cattofile) {
f1abd39f 188 $this->cattofile = $cattofile;
271e6dec 189 }
13bb604e 190
271e6dec 191 /**
192 * set contexttofile
193 * @param bool cattofile exports categories within export file
194 */
c7df5006 195 public function setContexttofile($contexttofile) {
271e6dec 196 $this->contexttofile = $contexttofile;
197 }
aca318e1 198
f3701561 199 /**
200 * set stoponerror
201 * @param bool stoponerror stops database write if any errors reported
202 */
c7df5006 203 public function setStoponerror($stoponerror) {
f3701561 204 $this->stoponerror = $stoponerror;
205 }
206
1b8b535d 207 /**
f7970e3c 208 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
1b8b535d 209 * where export files are saved.
210 */
c7df5006 211 public function set_can_access_backupdata($canaccess) {
1b8b535d 212 $this->canaccessbackupdata = $canaccess;
213 }
214
1dab8faa
JB
215 /**
216 * Change whether to display progress messages.
217 * There is normally no need to use this function as the
218 * default for $displayprogress is true.
219 * Set to false for unit tests.
220 * @param bool $displayprogress
221 */
222 public function set_display_progress($displayprogress) {
223 $this->displayprogress = $displayprogress;
224 }
225
e198992b
TH
226 /***********************
227 * IMPORTING FUNCTIONS
228 ***********************/
f3701561 229
230 /**
231 * Handle parsing error
232 */
c7df5006 233 protected function error($message, $text='', $questionname='') {
5e8a85aa 234 $importerrorquestion = get_string('importerrorquestion', 'question');
cdeabc06 235
f3701561 236 echo "<div class=\"importerror\">\n";
f4fe3968 237 echo "<strong>{$importerrorquestion} {$questionname}</strong>";
f3701561 238 if (!empty($text)) {
239 $text = s($text);
f4fe3968 240 echo "<blockquote>{$text}</blockquote>\n";
f3701561 241 }
f4fe3968 242 echo "<strong>{$message}</strong>\n";
f3701561 243 echo "</div>";
244
57944b7a 245 $this->importerrors++;
f3701561 246 }
08892d5b 247
271e6dec 248 /**
a41e3287 249 * Import for questiontype plugins
250 * Do not override.
251 * @param data mixed The segment of data containing the question
252 * @param question object processed (so far) by standard import code if appropriate
253 * @param extra mixed any additional format specific data that may be passed by the format
88bc20c3 254 * @param qtypehint hint about a question type from format
a41e3287 255 * @return object question object suitable for save_options() or false if cannot handle
256 */
c7df5006 257 public function try_importing_using_qtypes($data, $question = null, $extra = null,
49e2bba7 258 $qtypehint = '') {
a41e3287 259
260 // work out what format we are using
88bc20c3 261 $formatname = substr(get_class($this), strlen('qformat_'));
f4fe3968 262 $methodname = "import_from_{$formatname}";
a41e3287 263
88bc20c3 264 //first try importing using a hint from format
265 if (!empty($qtypehint)) {
49e2bba7 266 $qtype = question_bank::get_qtype($qtypehint, false);
88bc20c3 267 if (is_object($qtype) && method_exists($qtype, $methodname)) {
268 $question = $qtype->$methodname($data, $question, $this, $extra);
269 if ($question) {
270 return $question;
271 }
272 }
273 }
274
a41e3287 275 // loop through installed questiontypes checking for
276 // function to handle this question
49e2bba7 277 foreach (question_bank::get_all_qtypes() as $qtype) {
13bb604e
TH
278 if (method_exists($qtype, $methodname)) {
279 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
a41e3287 280 return $question;
281 }
282 }
271e6dec 283 }
284 return false;
a41e3287 285 }
286
08892d5b 287 /**
288 * Perform any required pre-processing
f7970e3c 289 * @return bool success
08892d5b 290 */
7348402f 291 public function importpreprocess() {
08892d5b 292 return true;
293 }
294
295 /**
296 * Process the file
297 * This method should not normally be overidden
f7970e3c 298 * @return bool success
08892d5b 299 */
d0a60444
JB
300 public function importprocess() {
301 global $USER, $DB, $OUTPUT;
cde2709a 302
cef7621e 303 // Raise time and memory, as importing can be quite intensive.
3ef7279f 304 core_php_time_limit::raise();
cef7621e 305 raise_memory_limit(MEMORY_EXTRA);
67c12527 306
9dd46039 307 // STAGE 1: Parse the file
1dab8faa
JB
308 if ($this->displayprogress) {
309 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
310 }
271e6dec 311
08892d5b 312 if (! $lines = $this->readdata($this->filename)) {
5e8a85aa 313 echo $OUTPUT->notification(get_string('cannotread', 'question'));
aca318e1 314 return false;
315 }
316
4d188926 317 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
5e8a85aa 318 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
aca318e1 319 return false;
320 }
321
f3701561 322 // STAGE 2: Write data to database
1dab8faa
JB
323 if ($this->displayprogress) {
324 echo $OUTPUT->notification(get_string('importingquestions', 'question',
325 $this->count_questions($questions)), 'notifysuccess');
326 }
aca318e1 327
f3701561 328 // check for errors before we continue
329 if ($this->stoponerror and ($this->importerrors>0)) {
5e8a85aa 330 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
10b4a508 331 return true;
f3701561 332 }
333
76f0a334 334 // get list of valid answer grades
92111e8d 335 $gradeoptionsfull = question_bank::fraction_options_full();
76f0a334 336
c1828e0b 337 // check answer grades are valid
338 // (now need to do this here because of 'stop on error': MDL-10689)
339 $gradeerrors = 0;
340 $goodquestions = array();
341 foreach ($questions as $question) {
342 if (!empty($question->fraction) and (is_array($question->fraction))) {
343 $fractions = $question->fraction;
b5d09003 344 $invalidfractions = array();
c1828e0b 345 foreach ($fractions as $key => $fraction) {
e198992b
TH
346 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
347 $this->matchgrades);
348 if ($newfraction === false) {
b5d09003 349 $invalidfractions[] = $fraction;
e198992b 350 } else {
c1828e0b 351 $fractions[$key] = $newfraction;
352 }
353 }
b5d09003
TH
354 if ($invalidfractions) {
355 echo $OUTPUT->notification(get_string('invalidgrade', 'question',
356 implode(', ', $invalidfractions)));
c1828e0b 357 ++$gradeerrors;
358 continue;
e198992b 359 } else {
c1828e0b 360 $question->fraction = $fractions;
361 }
362 }
363 $goodquestions[] = $question;
364 }
365 $questions = $goodquestions;
366
367 // check for errors before we continue
e198992b 368 if ($this->stoponerror && $gradeerrors > 0) {
c1828e0b 369 return false;
370 }
371
372 // count number of questions processed
aca318e1 373 $count = 0;
374
375 foreach ($questions as $question) { // Process and store each question
66de66fe 376 $transaction = $DB->start_delegated_transaction();
08892d5b 377
271e6dec 378 // reset the php timeout
3ef7279f 379 core_php_time_limit::raise();
67c12527 380
08892d5b 381 // check for category modifiers
9dd46039 382 if ($question->qtype == 'category') {
08892d5b 383 if ($this->catfromfile) {
384 // find/create category object
40e71443 385 $catpath = $question->category;
1dab8faa 386 $newcategory = $this->create_category_path($catpath, $question);
08892d5b 387 if (!empty($newcategory)) {
388 $this->category = $newcategory;
389 }
390 }
539a25ff 391 $transaction->allow_commit();
271e6dec 392 continue;
08892d5b 393 }
4d188926 394 $question->context = $this->importcontext;
08892d5b 395
aca318e1 396 $count++;
397
1dab8faa
JB
398 if ($this->displayprogress) {
399 echo "<hr /><p><b>{$count}</b>. " . $this->format_question_text($question) . "</p>";
400 }
aca318e1 401
9dd46039 402 $question->category = $this->category->id;
aca318e1 403 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 404
271e6dec 405 $question->createdby = $USER->id;
406 $question->timecreated = time();
08f53286
TH
407 $question->modifiedby = $USER->id;
408 $question->timemodified = time();
6189fda4
JB
409 if (isset($question->idnumber) && (string) $question->idnumber !== '') {
410 if ($DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $question->category])) {
411 // We cannot have duplicate idnumbers in a category.
412 unset($question->idnumber);
413 }
414 }
415
7ace84e0 416 $fileoptions = array(
624ff5ba 417 'subdirs' => true,
7ace84e0
JMV
418 'maxfiles' => -1,
419 'maxbytes' => 0,
420 );
271e6dec 421
cde2709a 422 $question->id = $DB->insert_record('question', $question);
7ace84e0 423
7980a381
JMV
424 if (isset($question->questiontextitemid)) {
425 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
7ace84e0
JMV
426 $this->importcontext->id, 'question', 'questiontext', $question->id,
427 $fileoptions, $question->questiontext);
428 } else if (isset($question->questiontextfiles)) {
cde2709a 429 foreach ($question->questiontextfiles as $file) {
d649fb02 430 question_bank::get_qtype($question->qtype)->import_file(
4d188926 431 $this->importcontext, 'question', 'questiontext', $question->id, $file);
cde2709a
DC
432 }
433 }
7980a381
JMV
434 if (isset($question->generalfeedbackitemid)) {
435 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
7ace84e0
JMV
436 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
437 $fileoptions, $question->generalfeedback);
438 } else if (isset($question->generalfeedbackfiles)) {
cde2709a 439 foreach ($question->generalfeedbackfiles as $file) {
d649fb02 440 question_bank::get_qtype($question->qtype)->import_file(
4d188926 441 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
cde2709a
DC
442 }
443 }
7ace84e0 444 $DB->update_record('question', $question);
aca318e1 445
446 $this->questionids[] = $question->id;
447
448 // Now to save all the answers and type-specific options
449
d649fb02 450 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
aca318e1 451
bbd655b4
SL
452 if (core_tag_tag::is_enabled('core_question', 'question')) {
453 // Is the current context we're importing in a course context?
454 $importingcontext = $this->importcontext;
455 $importingcoursecontext = $importingcontext->get_course_context(false);
456 $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
457
458 if (!empty($question->coursetags)) {
459 if ($isimportingcontextcourseoractivity) {
460 $mergedtags = array_merge($question->coursetags, $question->tags);
461
462 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
463 $question->context, $mergedtags);
464 } else {
465 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
466 context_course::instance($this->course->id), $question->coursetags);
13596866 467
bbd655b4
SL
468 if (!empty($question->tags)) {
469 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
470 $importingcontext, $question->tags);
471 }
472 }
f6bafa92 473 } else if (!empty($question->tags)) {
bbd655b4
SL
474 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
475 $question->context, $question->tags);
476 }
4f290077
TH
477 }
478
aca318e1 479 if (!empty($result->error)) {
fef8f84e 480 echo $OUTPUT->notification($result->error);
66de66fe
TH
481 // Can't use $transaction->rollback(); since it requires an exception,
482 // and I don't want to rewrite this code to change the error handling now.
483 $DB->force_transaction_rollback();
aca318e1 484 return false;
485 }
486
66de66fe
TH
487 $transaction->allow_commit();
488
aca318e1 489 if (!empty($result->notice)) {
fef8f84e 490 echo $OUTPUT->notification($result->notice);
aca318e1 491 return true;
492 }
cbe20043 493
494 // Give the question a unique version stamp determined by question_hash()
e198992b
TH
495 $DB->set_field('question', 'version', question_hash($question),
496 array('id' => $question->id));
aca318e1 497 }
498 return true;
499 }
13bb604e 500
ce2df288 501 /**
502 * Count all non-category questions in the questions array.
f34488b2 503 *
ce2df288 504 * @param array questions An array of question objects.
505 * @return int The count.
f34488b2 506 *
ce2df288 507 */
c7df5006 508 protected function count_questions($questions) {
ce2df288 509 $count = 0;
510 if (!is_array($questions)) {
511 return $count;
512 }
513 foreach ($questions as $question) {
e198992b
TH
514 if (!is_object($question) || !isset($question->qtype) ||
515 ($question->qtype == 'category')) {
ce2df288 516 continue;
517 }
518 $count++;
519 }
520 return $count;
521 }
522
271e6dec 523 /**
524 * find and/or create the category described by a delimited list
525 * e.g. $course$/tom/dick/harry or tom/dick/harry
526 *
527 * removes any context string no matter whether $getcontext is set
528 * but if $getcontext is set then ignore the context and use selected category context.
529 *
530 * @param string catpath delimited category path
1dab8faa 531 * @param object $lastcategoryinfo Contains category information
271e6dec 532 * @return mixed category object or null if fails
533 */
1dab8faa 534 protected function create_category_path($catpath, $lastcategoryinfo = null) {
f34488b2 535 global $DB;
728d60a1 536 $catnames = $this->split_category_path($catpath);
271e6dec 537 $parent = 0;
538 $category = null;
88bc20c3 539
5ca9e32d 540 // check for context id in path, it might not be there in pre 1.9 exports
541 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
49e2bba7 542 if ($matchcount == 1) {
271e6dec 543 $contextid = $this->translator->string_to_context($matches[1]);
544 array_shift($catnames);
545 } else {
728d60a1 546 $contextid = false;
271e6dec 547 }
728d60a1 548
f86f8c85
SR
549 // Before 3.5, question categories could be created at top level.
550 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
551 if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
552 array_unshift($catnames, 'top');
553 }
554
728d60a1 555 if ($this->contextfromfile && $contextid !== false) {
d197ea43 556 $context = context::instance_by_id($contextid);
271e6dec 557 require_capability('moodle/question:add', $context);
558 } else {
d197ea43 559 $context = context::instance_by_id($this->category->contextid);
271e6dec 560 }
4d188926 561 $this->importcontext = $context;
728d60a1
TH
562
563 // Now create any categories that need to be created.
1dab8faa 564 foreach ($catnames as $key => $catname) {
f86f8c85
SR
565 if ($parent == 0) {
566 $category = question_get_top_category($context->id, true);
567 $parent = $category->id;
568 } else if ($category = $DB->get_record('question_categories',
e198992b 569 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
1dab8faa
JB
570 // Do nothing unless the child category appears before the parent category
571 // in the imported xml file. Because the parent was created without info being available
572 // at that time, this allows the info to be added from the xml data.
573 if ($key == (count($catnames) - 1) && $lastcategoryinfo && $lastcategoryinfo->info !== null &&
574 $lastcategoryinfo->info !== "" && $category->info == "") {
575 $category->info = $lastcategoryinfo->info;
576 if ($lastcategoryinfo->infoformat !== null && $lastcategoryinfo->infoformat !== "") {
577 $category->infoformat = $lastcategoryinfo->infoformat;
578 }
579 $DB->update_record('question_categories', $category);
580 }
271e6dec 581 $parent = $category->id;
582 } else {
d0a60444
JB
583 if ($catname == 'top') {
584 // Should not happen, but if it does just move on.
585 // Occurs when there has been some import/export that has created
586 // multiple nested 'top' categories (due to old bug solved by MDL-63165).
1dab8faa 587 // This basically silently cleans up old errors. Not throwing an exception here.
d0a60444
JB
588 continue;
589 }
271e6dec 590 require_capability('moodle/question:managecategory', $context);
1dab8faa
JB
591 // Create the new category. This will create all the categories in the catpath,
592 // though only the final category will have any info added if available.
7f389342 593 $category = new stdClass();
271e6dec 594 $category->contextid = $context->id;
595 $category->name = $catname;
596 $category->info = '';
1dab8faa
JB
597 // Only add info (category description) for the final category in the catpath.
598 if ($key == (count($catnames) - 1) && $lastcategoryinfo && $lastcategoryinfo->info !== null &&
599 $lastcategoryinfo->info !== "") {
600 $category->info = $lastcategoryinfo->info;
601 if ($lastcategoryinfo->infoformat !== null && $lastcategoryinfo->infoformat !== "") {
602 $category->infoformat = $lastcategoryinfo->infoformat;
603 }
604 }
271e6dec 605 $category->parent = $parent;
606 $category->sortorder = 999;
607 $category->stamp = make_unique_id_code();
d0a60444
JB
608 $category->id = $DB->insert_record('question_categories', $category);
609 $parent = $category->id;
271e6dec 610 }
611 }
612 return $category;
613 }
3f5633df 614
f3701561 615 /**
616 * Return complete file within an array, one item per line
617 * @param string filename name of file
618 * @return mixed contents array or false on failure
619 */
c7df5006 620 protected function readdata($filename) {
aca318e1 621 if (is_readable($filename)) {
622 $filearray = file($filename);
623
77c1f160 624 // If the first line of the file starts with a UTF-8 BOM, remove it.
2f1e464a 625 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
77c1f160
TH
626
627 // Check for Macintosh OS line returns (ie file on one line), and fix.
6dbcacee 628 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
aca318e1 629 return explode("\r", $filearray[0]);
630 } else {
631 return $filearray;
632 }
633 }
634 return false;
635 }
636
f3701561 637 /**
271e6dec 638 * Parses an array of lines into an array of questions,
639 * where each item is a question object as defined by
640 * readquestion(). Questions are defined as anything
f3701561 641 * between blank lines.
642 *
4d188926
TH
643 * NOTE this method used to take $context as a second argument. However, at
644 * the point where this method was called, it was impossible to know what
645 * context the quetsions were going to be saved into, so the value could be
646 * wrong. Also, none of the standard question formats were using this argument,
647 * so it was removed. See MDL-32220.
648 *
f3701561 649 * If your format does not use blank lines as a delimiter
650 * then you will need to override this method. Even then
651 * try to use readquestion for each question
652 * @param array lines array of lines from readdata
653 * @return array array of question objects
654 */
4d188926 655 protected function readquestions($lines) {
271e6dec 656
aca318e1 657 $questions = array();
658 $currentquestion = array();
659
660 foreach ($lines as $line) {
661 $line = trim($line);
662 if (empty($line)) {
663 if (!empty($currentquestion)) {
664 if ($question = $this->readquestion($currentquestion)) {
665 $questions[] = $question;
666 }
667 $currentquestion = array();
668 }
669 } else {
670 $currentquestion[] = $line;
671 }
672 }
673
674 if (!empty($currentquestion)) { // There may be a final question
4d188926 675 if ($question = $this->readquestion($currentquestion)) {
aca318e1 676 $questions[] = $question;
677 }
678 }
679
680 return $questions;
681 }
682
f3701561 683 /**
684 * return an "empty" question
685 * Somewhere to specify question parameters that are not handled
686 * by import but are required db fields.
687 * This should not be overridden.
688 * @return object default question
271e6dec 689 */
c7df5006 690 protected function defaultquestion() {
b0679efa 691 global $CFG;
0cd46577 692 static $defaultshuffleanswers = null;
693 if (is_null($defaultshuffleanswers)) {
694 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
695 }
271e6dec 696
aca318e1 697 $question = new stdClass();
0cd46577 698 $question->shuffleanswers = $defaultshuffleanswers;
49e2bba7 699 $question->defaultmark = 1;
aca318e1 700 $question->image = "";
701 $question->usecase = 0;
702 $question->multiplier = array();
45bdcf11 703 $question->questiontextformat = FORMAT_MOODLE;
172f6d95 704 $question->generalfeedback = '';
45bdcf11 705 $question->generalfeedbackformat = FORMAT_MOODLE;
5931ea94 706 $question->answernumbering = 'abc';
49e2bba7 707 $question->penalty = 0.3333333;
3f5633df 708 $question->length = 1;
aca318e1 709
5fd8f999 710 // this option in case the questiontypes class wants
711 // to know where the data came from
712 $question->export_process = true;
093414d2 713 $question->import_process = true;
5fd8f999 714
d47af580
MG
715 $this->add_blank_combined_feedback($question);
716
aca318e1 717 return $question;
718 }
719
cacb8fa0
TH
720 /**
721 * Construct a reasonable default question name, based on the start of the question text.
722 * @param string $questiontext the question text.
723 * @param string $default default question name to use if the constructed one comes out blank.
724 * @return string a reasonable question name.
725 */
726 public function create_default_question_name($questiontext, $default) {
727 $name = $this->clean_question_name(shorten_text($questiontext, 80));
728 if ($name) {
729 return $name;
730 } else {
731 return $default;
732 }
733 }
734
735 /**
736 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
737 * @param string $name the raw question name.
738 * @return string a safe question name.
739 */
740 public function clean_question_name($name) {
741 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
742 $name = trim($name);
743 $trimlength = 251;
2f1e464a 744 while (core_text::strlen($name) > 255 && $trimlength > 0) {
cacb8fa0
TH
745 $name = shorten_text($name, $trimlength);
746 $trimlength -= 10;
747 }
748 return $name;
749 }
750
7ace84e0
JMV
751 /**
752 * Add a blank combined feedback to a question object.
753 * @param object question
754 * @return object question
755 */
756 protected function add_blank_combined_feedback($question) {
d47af580
MG
757 $question->correctfeedback = [
758 'text' => '',
759 'format' => $question->questiontextformat,
760 'files' => []
761 ];
762 $question->partiallycorrectfeedback = [
763 'text' => '',
764 'format' => $question->questiontextformat,
765 'files' => []
766 ];
767 $question->incorrectfeedback = [
768 'text' => '',
769 'format' => $question->questiontextformat,
770 'files' => []
771 ];
7ace84e0
JMV
772 return $question;
773 }
774
f3701561 775 /**
271e6dec 776 * Given the data known to define a question in
777 * this format, this function converts it into a question
f3701561 778 * object suitable for processing and insertion into Moodle.
779 *
780 * If your format does not use blank lines to delimit questions
781 * (e.g. an XML format) you must override 'readquestions' too
782 * @param $lines mixed data that represents question
783 * @return object question object
784 */
c7df5006 785 protected function readquestion($lines) {
762ee139
JMV
786 // We should never get there unless the qformat plugin is broken.
787 throw new coding_exception('Question format plugin is missing important code: readquestion.');
aca318e1 788
e0736817 789 return null;
aca318e1 790 }
791
f3701561 792 /**
793 * Override if any post-processing is required
f7970e3c 794 * @return bool success
f3701561 795 */
7348402f 796 public function importpostprocess() {
aca318e1 797 return true;
798 }
799
e198992b
TH
800 /*******************
801 * EXPORT FUNCTIONS
802 *******************/
aca318e1 803
271e6dec 804 /**
a41e3287 805 * Provide export functionality for plugin questiontypes
806 * Do not override
807 * @param name questiontype name
271e6dec 808 * @param question object data to export
a41e3287 809 * @param extra mixed any addition format specific data needed
810 * @return string the data to append to export or false if error (or unhandled)
811 */
c7df5006 812 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
a41e3287 813 // work out the name of format in use
13bb604e 814 $formatname = substr(get_class($this), strlen('qformat_'));
f4fe3968 815 $methodname = "export_to_{$formatname}";
a41e3287 816
d649fb02
TH
817 $qtype = question_bank::get_qtype($name, false);
818 if (method_exists($qtype, $methodname)) {
819 return $qtype->$methodname($question, $this, $extra);
a41e3287 820 }
821 return false;
822 }
823
f3701561 824 /**
825 * Do any pre-processing that may be required
f7970e3c 826 * @param bool success
f3701561 827 */
c7df5006 828 public function exportpreprocess() {
aca318e1 829 return true;
830 }
831
f3701561 832 /**
833 * Enable any processing to be done on the content
834 * just prior to the file being saved
835 * default is to do nothing
836 * @param string output text
837 * @param string processed output text
838 */
c7df5006 839 protected function presave_process($content) {
aca318e1 840 return $content;
841 }
842
f3701561 843 /**
cc98914e
AN
844 * Perform the export.
845 * For most types this should not need to be overrided.
846 *
847 * @param bool $checkcapabilities Whether to check capabilities when exporting the questions.
848 * @return string The content of the export.
f3701561 849 */
cc98914e 850 public function exportprocess($checkcapabilities = true) {
d0a60444
JB
851 global $CFG, $DB;
852
853 // Get the parents (from database) for this category.
854 $parents = [];
855 if ($this->category) {
856 $parents = question_categorylist_parents($this->category->id);
857 }
aca318e1 858
859 // get the questions (from database) in this category
860 // only get q's with no parents (no cloze subquestions specifically)
cde2709a 861 if ($this->category) {
13bb604e 862 $questions = get_questions_category($this->category, true);
2c44a3d3 863 } else {
864 $questions = $this->questions;
865 }
aca318e1 866
aca318e1 867 $count = 0;
868
869 // results are first written into string (and then to a file)
870 // so create/initialize the string here
871 $expout = "";
271e6dec 872
f1abd39f 873 // track which category questions are in
874 // if it changes we will record the category change in the output
875 // file if selected. 0 means that it will get printed before the 1st question
876 $trackcategory = 0;
aca318e1 877
d0a60444
JB
878 // Array of categories written to file.
879 $writtencategories = [];
880
e198992b 881 foreach ($questions as $question) {
cde2709a 882 // used by file api
e198992b
TH
883 $contextid = $DB->get_field('question_categories', 'contextid',
884 array('id' => $question->category));
cde2709a 885 $question->contextid = $contextid;
271e6dec 886
a9b16aff 887 // do not export hidden questions
888 if (!empty($question->hidden)) {
889 continue;
890 }
891
892 // do not export random questions
55190d7e 893 if ($question->qtype == 'random') {
a9b16aff 894 continue;
895 }
271e6dec 896
f1abd39f 897 // check if we need to record category change
898 if ($this->cattofile) {
d0a60444 899 $addnewcat = false;
f1abd39f 900 if ($question->category != $trackcategory) {
d0a60444 901 $addnewcat = true;
271e6dec 902 $trackcategory = $question->category;
d0a60444
JB
903 }
904 $trackcategoryparents = question_categorylist_parents($trackcategory);
905 // Check if we need to record empty parents categories.
906 foreach ($trackcategoryparents as $trackcategoryparent) {
907 // If parent wasn't written.
908 if (!in_array($trackcategoryparent, $writtencategories)) {
909 // If parent is empty.
910 if (!count($DB->get_records('question', array('category' => $trackcategoryparent)))) {
911 $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
1dab8faa
JB
912 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
913 'name, info, infoformat', MUST_EXIST);
914 if ($categoryinfo->name != 'top') {
915 // Create 'dummy' question for parent category.
916 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
917 $expout .= $this->writequestion($dummyquestion) . "\n";
918 $writtencategories[] = $trackcategoryparent;
919 }
d0a60444
JB
920 }
921 }
922 }
923 if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
924 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
1dab8faa
JB
925 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
926 'info, infoformat', MUST_EXIST);
d0a60444 927 // Create 'dummy' question for category.
1dab8faa 928 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
728d60a1 929 $expout .= $this->writequestion($dummyquestion) . "\n";
d0a60444 930 $writtencategories[] = $trackcategory;
271e6dec 931 }
932 }
f1abd39f 933
934 // export the question displaying message
935 $count++;
cde2709a 936
cc98914e 937 if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
cde2709a 938 $expout .= $this->writequestion($question, $contextid) . "\n";
0647e82b 939 }
a9b16aff 940 }
aca318e1 941
2c6d2c88 942 // continue path for following error checks
943 $course = $this->course;
f4fe3968 944 $continuepath = "{$CFG->wwwroot}/question/export.php?courseid={$course->id}";
2c6d2c88 945
946 // did we actually process anything
947 if ($count==0) {
5e8a85aa 948 print_error('noquestions', 'question', $continuepath);
2c6d2c88 949 }
950
aca318e1 951 // final pre-process on exported data
cde2709a
DC
952 $expout = $this->presave_process($expout);
953 return $expout;
aca318e1 954 }
3f5633df 955
d0a60444
JB
956 /**
957 * Create 'dummy' question for category export.
958 * @param string $categoryname the name of the category
1dab8faa 959 * @param object $categoryinfo description of the category
d0a60444
JB
960 * @return stdClass 'dummy' question for category
961 */
1dab8faa 962 protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
d0a60444
JB
963 $dummyquestion = new stdClass();
964 $dummyquestion->qtype = 'category';
965 $dummyquestion->category = $categoryname;
966 $dummyquestion->id = 0;
967 $dummyquestion->questiontextformat = '';
968 $dummyquestion->contextid = 0;
1dab8faa
JB
969 $dummyquestion->info = $categoryinfo->info;
970 $dummyquestion->infoformat = $categoryinfo->infoformat;
d0a60444
JB
971 $dummyquestion->name = 'Switch category to ' . $categoryname;
972 return $dummyquestion;
973 }
974
271e6dec 975 /**
976 * get the category as a path (e.g., tom/dick/harry)
977 * @param int id the id of the most nested catgory
271e6dec 978 * @return string the path
979 */
c7df5006 980 protected function get_category_path($id, $includecontext = true) {
f34488b2 981 global $DB;
728d60a1 982
e198992b 983 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1e7386c9 984 print_error('cannotfindcategory', 'error', '', $id);
271e6dec 985 }
271e6dec 986 $contextstring = $this->translator->context_to_string($category->contextid);
728d60a1
TH
987
988 $pathsections = array();
271e6dec 989 do {
728d60a1 990 $pathsections[] = $category->name;
271e6dec 991 $id = $category->parent;
13bb604e 992 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
271e6dec 993
13bb604e 994 if ($includecontext) {
728d60a1 995 $pathsections[] = '$' . $contextstring . '$';
271e6dec 996 }
728d60a1
TH
997
998 $path = $this->assemble_category_path(array_reverse($pathsections));
999
271e6dec 1000 return $path;
1001 }
aca318e1 1002
728d60a1
TH
1003 /**
1004 * Convert a list of category names, possibly preceeded by one of the
1005 * context tokens like $course$, into a string representation of the
1006 * category path.
1007 *
1008 * Names are separated by / delimiters. And /s in the name are replaced by //.
1009 *
1010 * To reverse the process and split the paths into names, use
1011 * {@link split_category_path()}.
1012 *
1013 * @param array $names
1014 * @return string
1015 */
1016 protected function assemble_category_path($names) {
1017 $escapednames = array();
1018 foreach ($names as $name) {
1019 $escapedname = str_replace('/', '//', $name);
1020 if (substr($escapedname, 0, 1) == '/') {
1021 $escapedname = ' ' . $escapedname;
1022 }
1023 if (substr($escapedname, -1) == '/') {
1024 $escapedname = $escapedname . ' ';
1025 }
1026 $escapednames[] = $escapedname;
1027 }
1028 return implode('/', $escapednames);
1029 }
1030
1031 /**
1032 * Convert a string, as returned by {@link assemble_category_path()},
1033 * back into an array of category names.
1034 *
071e68f9 1035 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
aab03169 1036 * which matches the cleaning in question/category_form.php.
728d60a1
TH
1037 *
1038 * @param string $path
1039 * @return array of category names.
1040 */
1041 protected function split_category_path($path) {
1042 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1043 $names = array();
1044 foreach ($rawnames as $rawname) {
071e68f9 1045 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
728d60a1
TH
1046 }
1047 return $names;
1048 }
1049
f3701561 1050 /**
1051 * Do an post-processing that may be required
f7970e3c 1052 * @return bool success
f3701561 1053 */
c7df5006 1054 protected function exportpostprocess() {
aca318e1 1055 return true;
1056 }
1057
f3701561 1058 /**
1059 * convert a single question object into text output in the given
1060 * format.
1061 * This must be overriden
1062 * @param object question question object
1063 * @return mixed question export text or null if not implemented
1064 */
c7df5006 1065 protected function writequestion($question) {
1e3d6fd8 1066 // if not overidden, then this is an error.
762ee139 1067 throw new coding_exception('Question format plugin is missing important code: writequestion.');
e0736817 1068 return null;
aca318e1 1069 }
1070
f3701561 1071 /**
13bb604e
TH
1072 * Convert the question text to plain text, so it can safely be displayed
1073 * during import to let the user see roughly what is going on.
f3701561 1074 */
c7df5006 1075 protected function format_question_text($question) {
0b18d0c9
TH
1076 return s(question_utils::to_plain_text($question->questiontext,
1077 $question->questiontextformat));
5b0dc681 1078 }
aca318e1 1079}
17ab0e74
JMV
1080
1081class qformat_based_on_xml extends qformat_default {
1082
7ace84e0
JMV
1083 /**
1084 * A lot of imported files contain unwanted entities.
1085 * This method tries to clean up all known problems.
1086 * @param string str string to correct
1087 * @return string the corrected string
1088 */
1089 public function cleaninput($str) {
1090
1091 $html_code_list = array(
1092 "&#039;" => "'",
1093 "&#8217;" => "'",
1094 "&#8220;" => "\"",
1095 "&#8221;" => "\"",
1096 "&#8211;" => "-",
1097 "&#8212;" => "-",
1098 );
1099 $str = strtr($str, $html_code_list);
2f1e464a
PS
1100 // Use core_text entities_to_utf8 function to convert only numerical entities.
1101 $str = core_text::entities_to_utf8($str, false);
7ace84e0
JMV
1102 return $str;
1103 }
1104
17ab0e74
JMV
1105 /**
1106 * Return the array moodle is expecting
1107 * for an HTML text. No processing is done on $text.
1108 * qformat classes that want to process $text
1109 * for instance to import external images files
1110 * and recode urls in $text must overwrite this method.
1111 * @param array $text some HTML text string
1112 * @return array with keys text, format and files.
1113 */
1114 public function text_field($text) {
1115 return array(
1116 'text' => trim($text),
1117 'format' => FORMAT_HTML,
1118 'files' => array(),
1119 );
1120 }
1121
1122 /**
1123 * Return the value of a node, given a path to the node
1124 * if it doesn't exist return the default value.
1125 * @param array xml data to read
1126 * @param array path path to node expressed as array
1127 * @param mixed default
1128 * @param bool istext process as text
1129 * @param string error if set value must exist, return false and issue message if not
1130 * @return mixed value
1131 */
1132 public function getpath($xml, $path, $default, $istext=false, $error='') {
1133 foreach ($path as $index) {
1134 if (!isset($xml[$index])) {
1135 if (!empty($error)) {
1136 $this->error($error);
1137 return false;
1138 } else {
1139 return $default;
1140 }
1141 }
1142
1143 $xml = $xml[$index];
1144 }
1145
1146 if ($istext) {
1147 if (!is_string($xml)) {
1148 $this->error(get_string('invalidxml', 'qformat_xml'));
1149 }
1150 $xml = trim($xml);
1151 }
1152
1153 return $xml;
1154 }
1155}