weekly release 3.7dev
[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();
2d696f8f
TH
409 if (isset($question->idnumber)) {
410 if ((string) $question->idnumber === '') {
411 // Id number not really set. Get rid of it.
6189fda4 412 unset($question->idnumber);
2d696f8f
TH
413 } else {
414 if ($DB->record_exists('question',
415 ['idnumber' => $question->idnumber, 'category' => $question->category])) {
416 // We cannot have duplicate idnumbers in a category. Just remove it.
417 unset($question->idnumber);
418 }
6189fda4
JB
419 }
420 }
421
7ace84e0 422 $fileoptions = array(
624ff5ba 423 'subdirs' => true,
7ace84e0
JMV
424 'maxfiles' => -1,
425 'maxbytes' => 0,
426 );
271e6dec 427
cde2709a 428 $question->id = $DB->insert_record('question', $question);
7ace84e0 429
7980a381
JMV
430 if (isset($question->questiontextitemid)) {
431 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
7ace84e0
JMV
432 $this->importcontext->id, 'question', 'questiontext', $question->id,
433 $fileoptions, $question->questiontext);
434 } else if (isset($question->questiontextfiles)) {
cde2709a 435 foreach ($question->questiontextfiles as $file) {
d649fb02 436 question_bank::get_qtype($question->qtype)->import_file(
4d188926 437 $this->importcontext, 'question', 'questiontext', $question->id, $file);
cde2709a
DC
438 }
439 }
7980a381
JMV
440 if (isset($question->generalfeedbackitemid)) {
441 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
7ace84e0
JMV
442 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
443 $fileoptions, $question->generalfeedback);
444 } else if (isset($question->generalfeedbackfiles)) {
cde2709a 445 foreach ($question->generalfeedbackfiles as $file) {
d649fb02 446 question_bank::get_qtype($question->qtype)->import_file(
4d188926 447 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
cde2709a
DC
448 }
449 }
7ace84e0 450 $DB->update_record('question', $question);
aca318e1 451
452 $this->questionids[] = $question->id;
453
454 // Now to save all the answers and type-specific options
455
d649fb02 456 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
aca318e1 457
bbd655b4
SL
458 if (core_tag_tag::is_enabled('core_question', 'question')) {
459 // Is the current context we're importing in a course context?
460 $importingcontext = $this->importcontext;
461 $importingcoursecontext = $importingcontext->get_course_context(false);
462 $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
463
464 if (!empty($question->coursetags)) {
465 if ($isimportingcontextcourseoractivity) {
466 $mergedtags = array_merge($question->coursetags, $question->tags);
467
468 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
469 $question->context, $mergedtags);
470 } else {
471 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
472 context_course::instance($this->course->id), $question->coursetags);
13596866 473
bbd655b4
SL
474 if (!empty($question->tags)) {
475 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
476 $importingcontext, $question->tags);
477 }
478 }
f6bafa92 479 } else if (!empty($question->tags)) {
bbd655b4
SL
480 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
481 $question->context, $question->tags);
482 }
4f290077
TH
483 }
484
aca318e1 485 if (!empty($result->error)) {
fef8f84e 486 echo $OUTPUT->notification($result->error);
66de66fe
TH
487 // Can't use $transaction->rollback(); since it requires an exception,
488 // and I don't want to rewrite this code to change the error handling now.
489 $DB->force_transaction_rollback();
aca318e1 490 return false;
491 }
492
66de66fe
TH
493 $transaction->allow_commit();
494
aca318e1 495 if (!empty($result->notice)) {
fef8f84e 496 echo $OUTPUT->notification($result->notice);
aca318e1 497 return true;
498 }
cbe20043 499
500 // Give the question a unique version stamp determined by question_hash()
e198992b
TH
501 $DB->set_field('question', 'version', question_hash($question),
502 array('id' => $question->id));
aca318e1 503 }
504 return true;
505 }
13bb604e 506
ce2df288 507 /**
508 * Count all non-category questions in the questions array.
f34488b2 509 *
ce2df288 510 * @param array questions An array of question objects.
511 * @return int The count.
f34488b2 512 *
ce2df288 513 */
c7df5006 514 protected function count_questions($questions) {
ce2df288 515 $count = 0;
516 if (!is_array($questions)) {
517 return $count;
518 }
519 foreach ($questions as $question) {
e198992b
TH
520 if (!is_object($question) || !isset($question->qtype) ||
521 ($question->qtype == 'category')) {
ce2df288 522 continue;
523 }
524 $count++;
525 }
526 return $count;
527 }
528
271e6dec 529 /**
530 * find and/or create the category described by a delimited list
531 * e.g. $course$/tom/dick/harry or tom/dick/harry
532 *
533 * removes any context string no matter whether $getcontext is set
534 * but if $getcontext is set then ignore the context and use selected category context.
535 *
536 * @param string catpath delimited category path
1dab8faa 537 * @param object $lastcategoryinfo Contains category information
271e6dec 538 * @return mixed category object or null if fails
539 */
1dab8faa 540 protected function create_category_path($catpath, $lastcategoryinfo = null) {
f34488b2 541 global $DB;
728d60a1 542 $catnames = $this->split_category_path($catpath);
271e6dec 543 $parent = 0;
544 $category = null;
88bc20c3 545
5ca9e32d 546 // check for context id in path, it might not be there in pre 1.9 exports
547 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
49e2bba7 548 if ($matchcount == 1) {
271e6dec 549 $contextid = $this->translator->string_to_context($matches[1]);
550 array_shift($catnames);
551 } else {
728d60a1 552 $contextid = false;
271e6dec 553 }
728d60a1 554
f86f8c85
SR
555 // Before 3.5, question categories could be created at top level.
556 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
557 if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
558 array_unshift($catnames, 'top');
559 }
560
728d60a1 561 if ($this->contextfromfile && $contextid !== false) {
d197ea43 562 $context = context::instance_by_id($contextid);
271e6dec 563 require_capability('moodle/question:add', $context);
564 } else {
d197ea43 565 $context = context::instance_by_id($this->category->contextid);
271e6dec 566 }
4d188926 567 $this->importcontext = $context;
728d60a1
TH
568
569 // Now create any categories that need to be created.
1dab8faa 570 foreach ($catnames as $key => $catname) {
f86f8c85
SR
571 if ($parent == 0) {
572 $category = question_get_top_category($context->id, true);
573 $parent = $category->id;
574 } else if ($category = $DB->get_record('question_categories',
e198992b 575 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
1dab8faa
JB
576 // Do nothing unless the child category appears before the parent category
577 // in the imported xml file. Because the parent was created without info being available
578 // at that time, this allows the info to be added from the xml data.
3a8cde29
TH
579 if ($key == (count($catnames) - 1) && $lastcategoryinfo && isset($lastcategoryinfo->info) &&
580 $lastcategoryinfo->info !== '' && $category->info === '') {
1dab8faa 581 $category->info = $lastcategoryinfo->info;
3a8cde29 582 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
1dab8faa
JB
583 $category->infoformat = $lastcategoryinfo->infoformat;
584 }
585 $DB->update_record('question_categories', $category);
586 }
271e6dec 587 $parent = $category->id;
588 } else {
d0a60444
JB
589 if ($catname == 'top') {
590 // Should not happen, but if it does just move on.
591 // Occurs when there has been some import/export that has created
592 // multiple nested 'top' categories (due to old bug solved by MDL-63165).
1dab8faa 593 // This basically silently cleans up old errors. Not throwing an exception here.
d0a60444
JB
594 continue;
595 }
271e6dec 596 require_capability('moodle/question:managecategory', $context);
1dab8faa
JB
597 // Create the new category. This will create all the categories in the catpath,
598 // though only the final category will have any info added if available.
7f389342 599 $category = new stdClass();
271e6dec 600 $category->contextid = $context->id;
601 $category->name = $catname;
602 $category->info = '';
1dab8faa 603 // Only add info (category description) for the final category in the catpath.
3a8cde29
TH
604 if ($key == (count($catnames) - 1) && $lastcategoryinfo && isset($lastcategoryinfo->info) &&
605 $lastcategoryinfo->info !== '') {
1dab8faa 606 $category->info = $lastcategoryinfo->info;
3a8cde29 607 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
1dab8faa
JB
608 $category->infoformat = $lastcategoryinfo->infoformat;
609 }
610 }
271e6dec 611 $category->parent = $parent;
612 $category->sortorder = 999;
613 $category->stamp = make_unique_id_code();
d0a60444
JB
614 $category->id = $DB->insert_record('question_categories', $category);
615 $parent = $category->id;
271e6dec 616 }
617 }
618 return $category;
619 }
3f5633df 620
f3701561 621 /**
622 * Return complete file within an array, one item per line
623 * @param string filename name of file
624 * @return mixed contents array or false on failure
625 */
c7df5006 626 protected function readdata($filename) {
aca318e1 627 if (is_readable($filename)) {
628 $filearray = file($filename);
629
77c1f160 630 // If the first line of the file starts with a UTF-8 BOM, remove it.
2f1e464a 631 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
77c1f160
TH
632
633 // Check for Macintosh OS line returns (ie file on one line), and fix.
6dbcacee 634 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
aca318e1 635 return explode("\r", $filearray[0]);
636 } else {
637 return $filearray;
638 }
639 }
640 return false;
641 }
642
f3701561 643 /**
271e6dec 644 * Parses an array of lines into an array of questions,
645 * where each item is a question object as defined by
646 * readquestion(). Questions are defined as anything
f3701561 647 * between blank lines.
648 *
4d188926
TH
649 * NOTE this method used to take $context as a second argument. However, at
650 * the point where this method was called, it was impossible to know what
651 * context the quetsions were going to be saved into, so the value could be
652 * wrong. Also, none of the standard question formats were using this argument,
653 * so it was removed. See MDL-32220.
654 *
f3701561 655 * If your format does not use blank lines as a delimiter
656 * then you will need to override this method. Even then
657 * try to use readquestion for each question
658 * @param array lines array of lines from readdata
659 * @return array array of question objects
660 */
4d188926 661 protected function readquestions($lines) {
271e6dec 662
aca318e1 663 $questions = array();
664 $currentquestion = array();
665
666 foreach ($lines as $line) {
667 $line = trim($line);
668 if (empty($line)) {
669 if (!empty($currentquestion)) {
670 if ($question = $this->readquestion($currentquestion)) {
671 $questions[] = $question;
672 }
673 $currentquestion = array();
674 }
675 } else {
676 $currentquestion[] = $line;
677 }
678 }
679
680 if (!empty($currentquestion)) { // There may be a final question
4d188926 681 if ($question = $this->readquestion($currentquestion)) {
aca318e1 682 $questions[] = $question;
683 }
684 }
685
686 return $questions;
687 }
688
f3701561 689 /**
690 * return an "empty" question
691 * Somewhere to specify question parameters that are not handled
692 * by import but are required db fields.
693 * This should not be overridden.
694 * @return object default question
271e6dec 695 */
c7df5006 696 protected function defaultquestion() {
b0679efa 697 global $CFG;
0cd46577 698 static $defaultshuffleanswers = null;
699 if (is_null($defaultshuffleanswers)) {
700 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
701 }
271e6dec 702
aca318e1 703 $question = new stdClass();
0cd46577 704 $question->shuffleanswers = $defaultshuffleanswers;
49e2bba7 705 $question->defaultmark = 1;
3a8cde29 706 $question->image = '';
aca318e1 707 $question->usecase = 0;
708 $question->multiplier = array();
45bdcf11 709 $question->questiontextformat = FORMAT_MOODLE;
172f6d95 710 $question->generalfeedback = '';
45bdcf11 711 $question->generalfeedbackformat = FORMAT_MOODLE;
5931ea94 712 $question->answernumbering = 'abc';
49e2bba7 713 $question->penalty = 0.3333333;
3f5633df 714 $question->length = 1;
aca318e1 715
5fd8f999 716 // this option in case the questiontypes class wants
717 // to know where the data came from
718 $question->export_process = true;
093414d2 719 $question->import_process = true;
5fd8f999 720
d47af580
MG
721 $this->add_blank_combined_feedback($question);
722
aca318e1 723 return $question;
724 }
725
cacb8fa0
TH
726 /**
727 * Construct a reasonable default question name, based on the start of the question text.
728 * @param string $questiontext the question text.
729 * @param string $default default question name to use if the constructed one comes out blank.
730 * @return string a reasonable question name.
731 */
732 public function create_default_question_name($questiontext, $default) {
733 $name = $this->clean_question_name(shorten_text($questiontext, 80));
734 if ($name) {
735 return $name;
736 } else {
737 return $default;
738 }
739 }
740
741 /**
742 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
743 * @param string $name the raw question name.
744 * @return string a safe question name.
745 */
746 public function clean_question_name($name) {
747 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
748 $name = trim($name);
749 $trimlength = 251;
2f1e464a 750 while (core_text::strlen($name) > 255 && $trimlength > 0) {
cacb8fa0
TH
751 $name = shorten_text($name, $trimlength);
752 $trimlength -= 10;
753 }
754 return $name;
755 }
756
7ace84e0
JMV
757 /**
758 * Add a blank combined feedback to a question object.
759 * @param object question
760 * @return object question
761 */
762 protected function add_blank_combined_feedback($question) {
d47af580
MG
763 $question->correctfeedback = [
764 'text' => '',
765 'format' => $question->questiontextformat,
766 'files' => []
767 ];
768 $question->partiallycorrectfeedback = [
769 'text' => '',
770 'format' => $question->questiontextformat,
771 'files' => []
772 ];
773 $question->incorrectfeedback = [
774 'text' => '',
775 'format' => $question->questiontextformat,
776 'files' => []
777 ];
7ace84e0
JMV
778 return $question;
779 }
780
f3701561 781 /**
271e6dec 782 * Given the data known to define a question in
783 * this format, this function converts it into a question
f3701561 784 * object suitable for processing and insertion into Moodle.
785 *
786 * If your format does not use blank lines to delimit questions
787 * (e.g. an XML format) you must override 'readquestions' too
788 * @param $lines mixed data that represents question
789 * @return object question object
790 */
c7df5006 791 protected function readquestion($lines) {
762ee139
JMV
792 // We should never get there unless the qformat plugin is broken.
793 throw new coding_exception('Question format plugin is missing important code: readquestion.');
aca318e1 794
e0736817 795 return null;
aca318e1 796 }
797
f3701561 798 /**
799 * Override if any post-processing is required
f7970e3c 800 * @return bool success
f3701561 801 */
7348402f 802 public function importpostprocess() {
aca318e1 803 return true;
804 }
805
e198992b
TH
806 /*******************
807 * EXPORT FUNCTIONS
808 *******************/
aca318e1 809
271e6dec 810 /**
a41e3287 811 * Provide export functionality for plugin questiontypes
812 * Do not override
813 * @param name questiontype name
271e6dec 814 * @param question object data to export
a41e3287 815 * @param extra mixed any addition format specific data needed
816 * @return string the data to append to export or false if error (or unhandled)
817 */
c7df5006 818 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
a41e3287 819 // work out the name of format in use
13bb604e 820 $formatname = substr(get_class($this), strlen('qformat_'));
f4fe3968 821 $methodname = "export_to_{$formatname}";
a41e3287 822
d649fb02
TH
823 $qtype = question_bank::get_qtype($name, false);
824 if (method_exists($qtype, $methodname)) {
825 return $qtype->$methodname($question, $this, $extra);
a41e3287 826 }
827 return false;
828 }
829
f3701561 830 /**
831 * Do any pre-processing that may be required
f7970e3c 832 * @param bool success
f3701561 833 */
c7df5006 834 public function exportpreprocess() {
aca318e1 835 return true;
836 }
837
f3701561 838 /**
839 * Enable any processing to be done on the content
840 * just prior to the file being saved
841 * default is to do nothing
842 * @param string output text
843 * @param string processed output text
844 */
c7df5006 845 protected function presave_process($content) {
aca318e1 846 return $content;
847 }
848
f3701561 849 /**
cc98914e
AN
850 * Perform the export.
851 * For most types this should not need to be overrided.
852 *
853 * @param bool $checkcapabilities Whether to check capabilities when exporting the questions.
854 * @return string The content of the export.
f3701561 855 */
cc98914e 856 public function exportprocess($checkcapabilities = true) {
d0a60444
JB
857 global $CFG, $DB;
858
859 // Get the parents (from database) for this category.
860 $parents = [];
861 if ($this->category) {
862 $parents = question_categorylist_parents($this->category->id);
863 }
aca318e1 864
865 // get the questions (from database) in this category
866 // only get q's with no parents (no cloze subquestions specifically)
cde2709a 867 if ($this->category) {
13bb604e 868 $questions = get_questions_category($this->category, true);
2c44a3d3 869 } else {
870 $questions = $this->questions;
871 }
aca318e1 872
aca318e1 873 $count = 0;
874
875 // results are first written into string (and then to a file)
876 // so create/initialize the string here
3a8cde29 877 $expout = '';
271e6dec 878
f1abd39f 879 // track which category questions are in
880 // if it changes we will record the category change in the output
881 // file if selected. 0 means that it will get printed before the 1st question
882 $trackcategory = 0;
aca318e1 883
d0a60444
JB
884 // Array of categories written to file.
885 $writtencategories = [];
886
e198992b 887 foreach ($questions as $question) {
cde2709a 888 // used by file api
e198992b
TH
889 $contextid = $DB->get_field('question_categories', 'contextid',
890 array('id' => $question->category));
cde2709a 891 $question->contextid = $contextid;
271e6dec 892
a9b16aff 893 // do not export hidden questions
894 if (!empty($question->hidden)) {
895 continue;
896 }
897
898 // do not export random questions
55190d7e 899 if ($question->qtype == 'random') {
a9b16aff 900 continue;
901 }
271e6dec 902
f1abd39f 903 // check if we need to record category change
904 if ($this->cattofile) {
d0a60444 905 $addnewcat = false;
f1abd39f 906 if ($question->category != $trackcategory) {
d0a60444 907 $addnewcat = true;
271e6dec 908 $trackcategory = $question->category;
d0a60444
JB
909 }
910 $trackcategoryparents = question_categorylist_parents($trackcategory);
911 // Check if we need to record empty parents categories.
912 foreach ($trackcategoryparents as $trackcategoryparent) {
913 // If parent wasn't written.
914 if (!in_array($trackcategoryparent, $writtencategories)) {
915 // If parent is empty.
916 if (!count($DB->get_records('question', array('category' => $trackcategoryparent)))) {
917 $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
1dab8faa
JB
918 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
919 'name, info, infoformat', MUST_EXIST);
920 if ($categoryinfo->name != 'top') {
921 // Create 'dummy' question for parent category.
922 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
923 $expout .= $this->writequestion($dummyquestion) . "\n";
924 $writtencategories[] = $trackcategoryparent;
925 }
d0a60444
JB
926 }
927 }
928 }
929 if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
930 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
1dab8faa
JB
931 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
932 'info, infoformat', MUST_EXIST);
d0a60444 933 // Create 'dummy' question for category.
1dab8faa 934 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
728d60a1 935 $expout .= $this->writequestion($dummyquestion) . "\n";
d0a60444 936 $writtencategories[] = $trackcategory;
271e6dec 937 }
938 }
f1abd39f 939
940 // export the question displaying message
941 $count++;
cde2709a 942
cc98914e 943 if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
cde2709a 944 $expout .= $this->writequestion($question, $contextid) . "\n";
0647e82b 945 }
a9b16aff 946 }
aca318e1 947
2c6d2c88 948 // continue path for following error checks
949 $course = $this->course;
f4fe3968 950 $continuepath = "{$CFG->wwwroot}/question/export.php?courseid={$course->id}";
2c6d2c88 951
952 // did we actually process anything
953 if ($count==0) {
5e8a85aa 954 print_error('noquestions', 'question', $continuepath);
2c6d2c88 955 }
956
aca318e1 957 // final pre-process on exported data
cde2709a
DC
958 $expout = $this->presave_process($expout);
959 return $expout;
aca318e1 960 }
3f5633df 961
d0a60444
JB
962 /**
963 * Create 'dummy' question for category export.
964 * @param string $categoryname the name of the category
1dab8faa 965 * @param object $categoryinfo description of the category
d0a60444
JB
966 * @return stdClass 'dummy' question for category
967 */
1dab8faa 968 protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
d0a60444
JB
969 $dummyquestion = new stdClass();
970 $dummyquestion->qtype = 'category';
971 $dummyquestion->category = $categoryname;
972 $dummyquestion->id = 0;
973 $dummyquestion->questiontextformat = '';
974 $dummyquestion->contextid = 0;
1dab8faa
JB
975 $dummyquestion->info = $categoryinfo->info;
976 $dummyquestion->infoformat = $categoryinfo->infoformat;
d0a60444
JB
977 $dummyquestion->name = 'Switch category to ' . $categoryname;
978 return $dummyquestion;
979 }
980
271e6dec 981 /**
982 * get the category as a path (e.g., tom/dick/harry)
983 * @param int id the id of the most nested catgory
271e6dec 984 * @return string the path
985 */
c7df5006 986 protected function get_category_path($id, $includecontext = true) {
f34488b2 987 global $DB;
728d60a1 988
e198992b 989 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1e7386c9 990 print_error('cannotfindcategory', 'error', '', $id);
271e6dec 991 }
271e6dec 992 $contextstring = $this->translator->context_to_string($category->contextid);
728d60a1
TH
993
994 $pathsections = array();
271e6dec 995 do {
728d60a1 996 $pathsections[] = $category->name;
271e6dec 997 $id = $category->parent;
13bb604e 998 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
271e6dec 999
13bb604e 1000 if ($includecontext) {
728d60a1 1001 $pathsections[] = '$' . $contextstring . '$';
271e6dec 1002 }
728d60a1
TH
1003
1004 $path = $this->assemble_category_path(array_reverse($pathsections));
1005
271e6dec 1006 return $path;
1007 }
aca318e1 1008
728d60a1
TH
1009 /**
1010 * Convert a list of category names, possibly preceeded by one of the
1011 * context tokens like $course$, into a string representation of the
1012 * category path.
1013 *
1014 * Names are separated by / delimiters. And /s in the name are replaced by //.
1015 *
1016 * To reverse the process and split the paths into names, use
1017 * {@link split_category_path()}.
1018 *
1019 * @param array $names
1020 * @return string
1021 */
1022 protected function assemble_category_path($names) {
1023 $escapednames = array();
1024 foreach ($names as $name) {
1025 $escapedname = str_replace('/', '//', $name);
1026 if (substr($escapedname, 0, 1) == '/') {
1027 $escapedname = ' ' . $escapedname;
1028 }
1029 if (substr($escapedname, -1) == '/') {
1030 $escapedname = $escapedname . ' ';
1031 }
1032 $escapednames[] = $escapedname;
1033 }
1034 return implode('/', $escapednames);
1035 }
1036
1037 /**
1038 * Convert a string, as returned by {@link assemble_category_path()},
1039 * back into an array of category names.
1040 *
071e68f9 1041 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
aab03169 1042 * which matches the cleaning in question/category_form.php.
728d60a1
TH
1043 *
1044 * @param string $path
1045 * @return array of category names.
1046 */
1047 protected function split_category_path($path) {
1048 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1049 $names = array();
1050 foreach ($rawnames as $rawname) {
071e68f9 1051 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
728d60a1
TH
1052 }
1053 return $names;
1054 }
1055
f3701561 1056 /**
1057 * Do an post-processing that may be required
f7970e3c 1058 * @return bool success
f3701561 1059 */
c7df5006 1060 protected function exportpostprocess() {
aca318e1 1061 return true;
1062 }
1063
f3701561 1064 /**
1065 * convert a single question object into text output in the given
1066 * format.
1067 * This must be overriden
1068 * @param object question question object
1069 * @return mixed question export text or null if not implemented
1070 */
c7df5006 1071 protected function writequestion($question) {
1e3d6fd8 1072 // if not overidden, then this is an error.
762ee139 1073 throw new coding_exception('Question format plugin is missing important code: writequestion.');
e0736817 1074 return null;
aca318e1 1075 }
1076
f3701561 1077 /**
13bb604e
TH
1078 * Convert the question text to plain text, so it can safely be displayed
1079 * during import to let the user see roughly what is going on.
f3701561 1080 */
c7df5006 1081 protected function format_question_text($question) {
0b18d0c9
TH
1082 return s(question_utils::to_plain_text($question->questiontext,
1083 $question->questiontextformat));
5b0dc681 1084 }
aca318e1 1085}
17ab0e74
JMV
1086
1087class qformat_based_on_xml extends qformat_default {
1088
7ace84e0
JMV
1089 /**
1090 * A lot of imported files contain unwanted entities.
1091 * This method tries to clean up all known problems.
1092 * @param string str string to correct
1093 * @return string the corrected string
1094 */
1095 public function cleaninput($str) {
1096
1097 $html_code_list = array(
1098 "&#039;" => "'",
1099 "&#8217;" => "'",
1100 "&#8220;" => "\"",
1101 "&#8221;" => "\"",
1102 "&#8211;" => "-",
1103 "&#8212;" => "-",
1104 );
1105 $str = strtr($str, $html_code_list);
2f1e464a
PS
1106 // Use core_text entities_to_utf8 function to convert only numerical entities.
1107 $str = core_text::entities_to_utf8($str, false);
7ace84e0
JMV
1108 return $str;
1109 }
1110
17ab0e74
JMV
1111 /**
1112 * Return the array moodle is expecting
1113 * for an HTML text. No processing is done on $text.
1114 * qformat classes that want to process $text
1115 * for instance to import external images files
1116 * and recode urls in $text must overwrite this method.
1117 * @param array $text some HTML text string
1118 * @return array with keys text, format and files.
1119 */
1120 public function text_field($text) {
1121 return array(
1122 'text' => trim($text),
1123 'format' => FORMAT_HTML,
1124 'files' => array(),
1125 );
1126 }
1127
1128 /**
1129 * Return the value of a node, given a path to the node
1130 * if it doesn't exist return the default value.
1131 * @param array xml data to read
1132 * @param array path path to node expressed as array
1133 * @param mixed default
1134 * @param bool istext process as text
1135 * @param string error if set value must exist, return false and issue message if not
1136 * @return mixed value
1137 */
1138 public function getpath($xml, $path, $default, $istext=false, $error='') {
1139 foreach ($path as $index) {
1140 if (!isset($xml[$index])) {
1141 if (!empty($error)) {
1142 $this->error($error);
1143 return false;
1144 } else {
1145 return $default;
1146 }
1147 }
1148
1149 $xml = $xml[$index];
1150 }
1151
1152 if ($istext) {
1153 if (!is_string($xml)) {
1154 $this->error(get_string('invalidxml', 'qformat_xml'));
1155 }
1156 $xml = trim($xml);
1157 }
1158
1159 return $xml;
1160 }
1161}