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