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
49e2bba7 285 * @param object $category
f7970e3c 286 * @return bool success
08892d5b 287 */
7348402f 288 public function importprocess($category) {
d649fb02 289 global $USER, $CFG, $DB, $OUTPUT;
cde2709a 290
cef7621e 291 // Raise time and memory, as importing can be quite intensive.
3ef7279f 292 core_php_time_limit::raise();
cef7621e 293 raise_memory_limit(MEMORY_EXTRA);
67c12527 294
9dd46039 295 // STAGE 1: Parse the file
5e8a85aa 296 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
271e6dec 297
08892d5b 298 if (! $lines = $this->readdata($this->filename)) {
5e8a85aa 299 echo $OUTPUT->notification(get_string('cannotread', 'question'));
aca318e1 300 return false;
301 }
302
4d188926 303 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
5e8a85aa 304 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
aca318e1 305 return false;
306 }
307
f3701561 308 // STAGE 2: Write data to database
5e8a85aa 309 echo $OUTPUT->notification(get_string('importingquestions', 'question',
f7c1dfaf 310 $this->count_questions($questions)), 'notifysuccess');
aca318e1 311
f3701561 312 // check for errors before we continue
313 if ($this->stoponerror and ($this->importerrors>0)) {
5e8a85aa 314 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
10b4a508 315 return true;
f3701561 316 }
317
76f0a334 318 // get list of valid answer grades
92111e8d 319 $gradeoptionsfull = question_bank::fraction_options_full();
76f0a334 320
c1828e0b 321 // check answer grades are valid
322 // (now need to do this here because of 'stop on error': MDL-10689)
323 $gradeerrors = 0;
324 $goodquestions = array();
325 foreach ($questions as $question) {
326 if (!empty($question->fraction) and (is_array($question->fraction))) {
327 $fractions = $question->fraction;
b5d09003 328 $invalidfractions = array();
c1828e0b 329 foreach ($fractions as $key => $fraction) {
e198992b
TH
330 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
331 $this->matchgrades);
332 if ($newfraction === false) {
b5d09003 333 $invalidfractions[] = $fraction;
e198992b 334 } else {
c1828e0b 335 $fractions[$key] = $newfraction;
336 }
337 }
b5d09003
TH
338 if ($invalidfractions) {
339 echo $OUTPUT->notification(get_string('invalidgrade', 'question',
340 implode(', ', $invalidfractions)));
c1828e0b 341 ++$gradeerrors;
342 continue;
e198992b 343 } else {
c1828e0b 344 $question->fraction = $fractions;
345 }
346 }
347 $goodquestions[] = $question;
348 }
349 $questions = $goodquestions;
350
351 // check for errors before we continue
e198992b 352 if ($this->stoponerror && $gradeerrors > 0) {
c1828e0b 353 return false;
354 }
355
356 // count number of questions processed
aca318e1 357 $count = 0;
358
359 foreach ($questions as $question) { // Process and store each question
66de66fe 360 $transaction = $DB->start_delegated_transaction();
08892d5b 361
271e6dec 362 // reset the php timeout
3ef7279f 363 core_php_time_limit::raise();
67c12527 364
08892d5b 365 // check for category modifiers
9dd46039 366 if ($question->qtype == 'category') {
08892d5b 367 if ($this->catfromfile) {
368 // find/create category object
40e71443 369 $catpath = $question->category;
728d60a1 370 $newcategory = $this->create_category_path($catpath);
08892d5b 371 if (!empty($newcategory)) {
372 $this->category = $newcategory;
373 }
374 }
539a25ff 375 $transaction->allow_commit();
271e6dec 376 continue;
08892d5b 377 }
4d188926 378 $question->context = $this->importcontext;
08892d5b 379
aca318e1 380 $count++;
381
f4fe3968 382 echo "<hr /><p><b>{$count}</b>. ".$this->format_question_text($question)."</p>";
aca318e1 383
9dd46039 384 $question->category = $this->category->id;
aca318e1 385 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
aca318e1 386
271e6dec 387 $question->createdby = $USER->id;
388 $question->timecreated = time();
08f53286
TH
389 $question->modifiedby = $USER->id;
390 $question->timemodified = time();
7ace84e0 391 $fileoptions = array(
624ff5ba 392 'subdirs' => true,
7ace84e0
JMV
393 'maxfiles' => -1,
394 'maxbytes' => 0,
395 );
271e6dec 396
cde2709a 397 $question->id = $DB->insert_record('question', $question);
7ace84e0 398
7980a381
JMV
399 if (isset($question->questiontextitemid)) {
400 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
7ace84e0
JMV
401 $this->importcontext->id, 'question', 'questiontext', $question->id,
402 $fileoptions, $question->questiontext);
403 } else if (isset($question->questiontextfiles)) {
cde2709a 404 foreach ($question->questiontextfiles as $file) {
d649fb02 405 question_bank::get_qtype($question->qtype)->import_file(
4d188926 406 $this->importcontext, 'question', 'questiontext', $question->id, $file);
cde2709a
DC
407 }
408 }
7980a381
JMV
409 if (isset($question->generalfeedbackitemid)) {
410 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
7ace84e0
JMV
411 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
412 $fileoptions, $question->generalfeedback);
413 } else if (isset($question->generalfeedbackfiles)) {
cde2709a 414 foreach ($question->generalfeedbackfiles as $file) {
d649fb02 415 question_bank::get_qtype($question->qtype)->import_file(
4d188926 416 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
cde2709a
DC
417 }
418 }
7ace84e0 419 $DB->update_record('question', $question);
aca318e1 420
421 $this->questionids[] = $question->id;
422
423 // Now to save all the answers and type-specific options
424
d649fb02 425 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
aca318e1 426
bbd655b4
SL
427 if (core_tag_tag::is_enabled('core_question', 'question')) {
428 // Is the current context we're importing in a course context?
429 $importingcontext = $this->importcontext;
430 $importingcoursecontext = $importingcontext->get_course_context(false);
431 $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
432
433 if (!empty($question->coursetags)) {
434 if ($isimportingcontextcourseoractivity) {
435 $mergedtags = array_merge($question->coursetags, $question->tags);
436
437 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
438 $question->context, $mergedtags);
439 } else {
440 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
441 context_course::instance($this->course->id), $question->coursetags);
13596866 442
bbd655b4
SL
443 if (!empty($question->tags)) {
444 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
445 $importingcontext, $question->tags);
446 }
447 }
f6bafa92 448 } else if (!empty($question->tags)) {
bbd655b4
SL
449 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
450 $question->context, $question->tags);
451 }
4f290077
TH
452 }
453
aca318e1 454 if (!empty($result->error)) {
fef8f84e 455 echo $OUTPUT->notification($result->error);
66de66fe
TH
456 // Can't use $transaction->rollback(); since it requires an exception,
457 // and I don't want to rewrite this code to change the error handling now.
458 $DB->force_transaction_rollback();
aca318e1 459 return false;
460 }
461
66de66fe
TH
462 $transaction->allow_commit();
463
aca318e1 464 if (!empty($result->notice)) {
fef8f84e 465 echo $OUTPUT->notification($result->notice);
aca318e1 466 return true;
467 }
cbe20043 468
469 // Give the question a unique version stamp determined by question_hash()
e198992b
TH
470 $DB->set_field('question', 'version', question_hash($question),
471 array('id' => $question->id));
aca318e1 472 }
473 return true;
474 }
13bb604e 475
ce2df288 476 /**
477 * Count all non-category questions in the questions array.
f34488b2 478 *
ce2df288 479 * @param array questions An array of question objects.
480 * @return int The count.
f34488b2 481 *
ce2df288 482 */
c7df5006 483 protected function count_questions($questions) {
ce2df288 484 $count = 0;
485 if (!is_array($questions)) {
486 return $count;
487 }
488 foreach ($questions as $question) {
e198992b
TH
489 if (!is_object($question) || !isset($question->qtype) ||
490 ($question->qtype == 'category')) {
ce2df288 491 continue;
492 }
493 $count++;
494 }
495 return $count;
496 }
497
271e6dec 498 /**
499 * find and/or create the category described by a delimited list
500 * e.g. $course$/tom/dick/harry or tom/dick/harry
501 *
502 * removes any context string no matter whether $getcontext is set
503 * but if $getcontext is set then ignore the context and use selected category context.
504 *
505 * @param string catpath delimited category path
271e6dec 506 * @param int courseid course to search for categories
507 * @return mixed category object or null if fails
508 */
c7df5006 509 protected function create_category_path($catpath) {
f34488b2 510 global $DB;
728d60a1 511 $catnames = $this->split_category_path($catpath);
271e6dec 512 $parent = 0;
513 $category = null;
88bc20c3 514
5ca9e32d 515 // check for context id in path, it might not be there in pre 1.9 exports
516 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
49e2bba7 517 if ($matchcount == 1) {
271e6dec 518 $contextid = $this->translator->string_to_context($matches[1]);
519 array_shift($catnames);
520 } else {
728d60a1 521 $contextid = false;
271e6dec 522 }
728d60a1 523
f86f8c85
SR
524 // Before 3.5, question categories could be created at top level.
525 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
526 if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
527 array_unshift($catnames, 'top');
528 }
529
728d60a1 530 if ($this->contextfromfile && $contextid !== false) {
d197ea43 531 $context = context::instance_by_id($contextid);
271e6dec 532 require_capability('moodle/question:add', $context);
533 } else {
d197ea43 534 $context = context::instance_by_id($this->category->contextid);
271e6dec 535 }
4d188926 536 $this->importcontext = $context;
728d60a1
TH
537
538 // Now create any categories that need to be created.
271e6dec 539 foreach ($catnames as $catname) {
f86f8c85
SR
540 if ($parent == 0) {
541 $category = question_get_top_category($context->id, true);
542 $parent = $category->id;
543 } else if ($category = $DB->get_record('question_categories',
e198992b 544 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
271e6dec 545 $parent = $category->id;
f86f8c85
SR
546 } else if ($parent == 0) {
547 $category = question_get_top_category($context->id, true);
548 $parent = $category->id;
271e6dec 549 } else {
550 require_capability('moodle/question:managecategory', $context);
551 // create the new category
7f389342 552 $category = new stdClass();
271e6dec 553 $category->contextid = $context->id;
554 $category->name = $catname;
555 $category->info = '';
556 $category->parent = $parent;
557 $category->sortorder = 999;
558 $category->stamp = make_unique_id_code();
bf8e93d7 559 $id = $DB->insert_record('question_categories', $category);
271e6dec 560 $category->id = $id;
561 $parent = $id;
562 }
563 }
564 return $category;
565 }
3f5633df 566
f3701561 567 /**
568 * Return complete file within an array, one item per line
569 * @param string filename name of file
570 * @return mixed contents array or false on failure
571 */
c7df5006 572 protected function readdata($filename) {
aca318e1 573 if (is_readable($filename)) {
574 $filearray = file($filename);
575
77c1f160 576 // If the first line of the file starts with a UTF-8 BOM, remove it.
2f1e464a 577 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
77c1f160
TH
578
579 // Check for Macintosh OS line returns (ie file on one line), and fix.
6dbcacee 580 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
aca318e1 581 return explode("\r", $filearray[0]);
582 } else {
583 return $filearray;
584 }
585 }
586 return false;
587 }
588
f3701561 589 /**
271e6dec 590 * Parses an array of lines into an array of questions,
591 * where each item is a question object as defined by
592 * readquestion(). Questions are defined as anything
f3701561 593 * between blank lines.
594 *
4d188926
TH
595 * NOTE this method used to take $context as a second argument. However, at
596 * the point where this method was called, it was impossible to know what
597 * context the quetsions were going to be saved into, so the value could be
598 * wrong. Also, none of the standard question formats were using this argument,
599 * so it was removed. See MDL-32220.
600 *
f3701561 601 * If your format does not use blank lines as a delimiter
602 * then you will need to override this method. Even then
603 * try to use readquestion for each question
604 * @param array lines array of lines from readdata
605 * @return array array of question objects
606 */
4d188926 607 protected function readquestions($lines) {
271e6dec 608
aca318e1 609 $questions = array();
610 $currentquestion = array();
611
612 foreach ($lines as $line) {
613 $line = trim($line);
614 if (empty($line)) {
615 if (!empty($currentquestion)) {
616 if ($question = $this->readquestion($currentquestion)) {
617 $questions[] = $question;
618 }
619 $currentquestion = array();
620 }
621 } else {
622 $currentquestion[] = $line;
623 }
624 }
625
626 if (!empty($currentquestion)) { // There may be a final question
4d188926 627 if ($question = $this->readquestion($currentquestion)) {
aca318e1 628 $questions[] = $question;
629 }
630 }
631
632 return $questions;
633 }
634
f3701561 635 /**
636 * return an "empty" question
637 * Somewhere to specify question parameters that are not handled
638 * by import but are required db fields.
639 * This should not be overridden.
640 * @return object default question
271e6dec 641 */
c7df5006 642 protected function defaultquestion() {
b0679efa 643 global $CFG;
0cd46577 644 static $defaultshuffleanswers = null;
645 if (is_null($defaultshuffleanswers)) {
646 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
647 }
271e6dec 648
aca318e1 649 $question = new stdClass();
0cd46577 650 $question->shuffleanswers = $defaultshuffleanswers;
49e2bba7 651 $question->defaultmark = 1;
aca318e1 652 $question->image = "";
653 $question->usecase = 0;
654 $question->multiplier = array();
45bdcf11 655 $question->questiontextformat = FORMAT_MOODLE;
172f6d95 656 $question->generalfeedback = '';
45bdcf11 657 $question->generalfeedbackformat = FORMAT_MOODLE;
5931ea94 658 $question->answernumbering = 'abc';
49e2bba7 659 $question->penalty = 0.3333333;
3f5633df 660 $question->length = 1;
aca318e1 661
5fd8f999 662 // this option in case the questiontypes class wants
663 // to know where the data came from
664 $question->export_process = true;
093414d2 665 $question->import_process = true;
5fd8f999 666
d47af580
MG
667 $this->add_blank_combined_feedback($question);
668
aca318e1 669 return $question;
670 }
671
cacb8fa0
TH
672 /**
673 * Construct a reasonable default question name, based on the start of the question text.
674 * @param string $questiontext the question text.
675 * @param string $default default question name to use if the constructed one comes out blank.
676 * @return string a reasonable question name.
677 */
678 public function create_default_question_name($questiontext, $default) {
679 $name = $this->clean_question_name(shorten_text($questiontext, 80));
680 if ($name) {
681 return $name;
682 } else {
683 return $default;
684 }
685 }
686
687 /**
688 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
689 * @param string $name the raw question name.
690 * @return string a safe question name.
691 */
692 public function clean_question_name($name) {
693 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
694 $name = trim($name);
695 $trimlength = 251;
2f1e464a 696 while (core_text::strlen($name) > 255 && $trimlength > 0) {
cacb8fa0
TH
697 $name = shorten_text($name, $trimlength);
698 $trimlength -= 10;
699 }
700 return $name;
701 }
702
7ace84e0
JMV
703 /**
704 * Add a blank combined feedback to a question object.
705 * @param object question
706 * @return object question
707 */
708 protected function add_blank_combined_feedback($question) {
d47af580
MG
709 $question->correctfeedback = [
710 'text' => '',
711 'format' => $question->questiontextformat,
712 'files' => []
713 ];
714 $question->partiallycorrectfeedback = [
715 'text' => '',
716 'format' => $question->questiontextformat,
717 'files' => []
718 ];
719 $question->incorrectfeedback = [
720 'text' => '',
721 'format' => $question->questiontextformat,
722 'files' => []
723 ];
7ace84e0
JMV
724 return $question;
725 }
726
f3701561 727 /**
271e6dec 728 * Given the data known to define a question in
729 * this format, this function converts it into a question
f3701561 730 * object suitable for processing and insertion into Moodle.
731 *
732 * If your format does not use blank lines to delimit questions
733 * (e.g. an XML format) you must override 'readquestions' too
734 * @param $lines mixed data that represents question
735 * @return object question object
736 */
c7df5006 737 protected function readquestion($lines) {
762ee139
JMV
738 // We should never get there unless the qformat plugin is broken.
739 throw new coding_exception('Question format plugin is missing important code: readquestion.');
aca318e1 740
e0736817 741 return null;
aca318e1 742 }
743
f3701561 744 /**
745 * Override if any post-processing is required
f7970e3c 746 * @return bool success
f3701561 747 */
7348402f 748 public function importpostprocess() {
aca318e1 749 return true;
750 }
751
e198992b
TH
752 /*******************
753 * EXPORT FUNCTIONS
754 *******************/
aca318e1 755
271e6dec 756 /**
a41e3287 757 * Provide export functionality for plugin questiontypes
758 * Do not override
759 * @param name questiontype name
271e6dec 760 * @param question object data to export
a41e3287 761 * @param extra mixed any addition format specific data needed
762 * @return string the data to append to export or false if error (or unhandled)
763 */
c7df5006 764 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
a41e3287 765 // work out the name of format in use
13bb604e 766 $formatname = substr(get_class($this), strlen('qformat_'));
f4fe3968 767 $methodname = "export_to_{$formatname}";
a41e3287 768
d649fb02
TH
769 $qtype = question_bank::get_qtype($name, false);
770 if (method_exists($qtype, $methodname)) {
771 return $qtype->$methodname($question, $this, $extra);
a41e3287 772 }
773 return false;
774 }
775
f3701561 776 /**
777 * Do any pre-processing that may be required
f7970e3c 778 * @param bool success
f3701561 779 */
c7df5006 780 public function exportpreprocess() {
aca318e1 781 return true;
782 }
783
f3701561 784 /**
785 * Enable any processing to be done on the content
786 * just prior to the file being saved
787 * default is to do nothing
788 * @param string output text
789 * @param string processed output text
790 */
c7df5006 791 protected function presave_process($content) {
aca318e1 792 return $content;
793 }
794
f3701561 795 /**
cc98914e
AN
796 * Perform the export.
797 * For most types this should not need to be overrided.
798 *
799 * @param bool $checkcapabilities Whether to check capabilities when exporting the questions.
800 * @return string The content of the export.
f3701561 801 */
cc98914e 802 public function exportprocess($checkcapabilities = true) {
cde2709a 803 global $CFG, $OUTPUT, $DB, $USER;
aca318e1 804
805 // get the questions (from database) in this category
806 // only get q's with no parents (no cloze subquestions specifically)
cde2709a 807 if ($this->category) {
13bb604e 808 $questions = get_questions_category($this->category, true);
2c44a3d3 809 } else {
810 $questions = $this->questions;
811 }
aca318e1 812
aca318e1 813 $count = 0;
814
815 // results are first written into string (and then to a file)
816 // so create/initialize the string here
817 $expout = "";
271e6dec 818
f1abd39f 819 // track which category questions are in
820 // if it changes we will record the category change in the output
821 // file if selected. 0 means that it will get printed before the 1st question
822 $trackcategory = 0;
aca318e1 823
824 // iterate through questions
e198992b 825 foreach ($questions as $question) {
cde2709a 826 // used by file api
e198992b
TH
827 $contextid = $DB->get_field('question_categories', 'contextid',
828 array('id' => $question->category));
cde2709a 829 $question->contextid = $contextid;
271e6dec 830
a9b16aff 831 // do not export hidden questions
832 if (!empty($question->hidden)) {
833 continue;
834 }
835
836 // do not export random questions
55190d7e 837 if ($question->qtype == 'random') {
a9b16aff 838 continue;
839 }
271e6dec 840
f1abd39f 841 // check if we need to record category change
842 if ($this->cattofile) {
843 if ($question->category != $trackcategory) {
271e6dec 844 $trackcategory = $question->category;
728d60a1 845 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
271e6dec 846
f1abd39f 847 // create 'dummy' question for category export
7f389342 848 $dummyquestion = new stdClass();
f1abd39f 849 $dummyquestion->qtype = 'category';
850 $dummyquestion->category = $categoryname;
728d60a1 851 $dummyquestion->name = 'Switch category to ' . $categoryname;
f1abd39f 852 $dummyquestion->id = 0;
853 $dummyquestion->questiontextformat = '';
cde2709a 854 $dummyquestion->contextid = 0;
728d60a1 855 $expout .= $this->writequestion($dummyquestion) . "\n";
271e6dec 856 }
857 }
f1abd39f 858
859 // export the question displaying message
860 $count++;
cde2709a 861
cc98914e 862 if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
cde2709a 863 $expout .= $this->writequestion($question, $contextid) . "\n";
0647e82b 864 }
a9b16aff 865 }
aca318e1 866
2c6d2c88 867 // continue path for following error checks
868 $course = $this->course;
f4fe3968 869 $continuepath = "{$CFG->wwwroot}/question/export.php?courseid={$course->id}";
2c6d2c88 870
871 // did we actually process anything
872 if ($count==0) {
5e8a85aa 873 print_error('noquestions', 'question', $continuepath);
2c6d2c88 874 }
875
aca318e1 876 // final pre-process on exported data
cde2709a
DC
877 $expout = $this->presave_process($expout);
878 return $expout;
aca318e1 879 }
3f5633df 880
271e6dec 881 /**
882 * get the category as a path (e.g., tom/dick/harry)
883 * @param int id the id of the most nested catgory
271e6dec 884 * @return string the path
885 */
c7df5006 886 protected function get_category_path($id, $includecontext = true) {
f34488b2 887 global $DB;
728d60a1 888
e198992b 889 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1e7386c9 890 print_error('cannotfindcategory', 'error', '', $id);
271e6dec 891 }
271e6dec 892 $contextstring = $this->translator->context_to_string($category->contextid);
728d60a1
TH
893
894 $pathsections = array();
271e6dec 895 do {
728d60a1 896 $pathsections[] = $category->name;
271e6dec 897 $id = $category->parent;
13bb604e 898 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
271e6dec 899
13bb604e 900 if ($includecontext) {
728d60a1 901 $pathsections[] = '$' . $contextstring . '$';
271e6dec 902 }
728d60a1
TH
903
904 $path = $this->assemble_category_path(array_reverse($pathsections));
905
271e6dec 906 return $path;
907 }
aca318e1 908
728d60a1
TH
909 /**
910 * Convert a list of category names, possibly preceeded by one of the
911 * context tokens like $course$, into a string representation of the
912 * category path.
913 *
914 * Names are separated by / delimiters. And /s in the name are replaced by //.
915 *
916 * To reverse the process and split the paths into names, use
917 * {@link split_category_path()}.
918 *
919 * @param array $names
920 * @return string
921 */
922 protected function assemble_category_path($names) {
923 $escapednames = array();
924 foreach ($names as $name) {
925 $escapedname = str_replace('/', '//', $name);
926 if (substr($escapedname, 0, 1) == '/') {
927 $escapedname = ' ' . $escapedname;
928 }
929 if (substr($escapedname, -1) == '/') {
930 $escapedname = $escapedname . ' ';
931 }
932 $escapednames[] = $escapedname;
933 }
934 return implode('/', $escapednames);
935 }
936
937 /**
938 * Convert a string, as returned by {@link assemble_category_path()},
939 * back into an array of category names.
940 *
071e68f9 941 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
aab03169 942 * which matches the cleaning in question/category_form.php.
728d60a1
TH
943 *
944 * @param string $path
945 * @return array of category names.
946 */
947 protected function split_category_path($path) {
948 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
949 $names = array();
950 foreach ($rawnames as $rawname) {
071e68f9 951 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
728d60a1
TH
952 }
953 return $names;
954 }
955
f3701561 956 /**
957 * Do an post-processing that may be required
f7970e3c 958 * @return bool success
f3701561 959 */
c7df5006 960 protected function exportpostprocess() {
aca318e1 961 return true;
962 }
963
f3701561 964 /**
965 * convert a single question object into text output in the given
966 * format.
967 * This must be overriden
968 * @param object question question object
969 * @return mixed question export text or null if not implemented
970 */
c7df5006 971 protected function writequestion($question) {
1e3d6fd8 972 // if not overidden, then this is an error.
762ee139 973 throw new coding_exception('Question format plugin is missing important code: writequestion.');
e0736817 974 return null;
aca318e1 975 }
976
f3701561 977 /**
13bb604e
TH
978 * Convert the question text to plain text, so it can safely be displayed
979 * during import to let the user see roughly what is going on.
f3701561 980 */
c7df5006 981 protected function format_question_text($question) {
0b18d0c9
TH
982 return s(question_utils::to_plain_text($question->questiontext,
983 $question->questiontextformat));
5b0dc681 984 }
aca318e1 985}
17ab0e74
JMV
986
987class qformat_based_on_xml extends qformat_default {
988
7ace84e0
JMV
989 /**
990 * A lot of imported files contain unwanted entities.
991 * This method tries to clean up all known problems.
992 * @param string str string to correct
993 * @return string the corrected string
994 */
995 public function cleaninput($str) {
996
997 $html_code_list = array(
998 "&#039;" => "'",
999 "&#8217;" => "'",
1000 "&#8220;" => "\"",
1001 "&#8221;" => "\"",
1002 "&#8211;" => "-",
1003 "&#8212;" => "-",
1004 );
1005 $str = strtr($str, $html_code_list);
2f1e464a
PS
1006 // Use core_text entities_to_utf8 function to convert only numerical entities.
1007 $str = core_text::entities_to_utf8($str, false);
7ace84e0
JMV
1008 return $str;
1009 }
1010
17ab0e74
JMV
1011 /**
1012 * Return the array moodle is expecting
1013 * for an HTML text. No processing is done on $text.
1014 * qformat classes that want to process $text
1015 * for instance to import external images files
1016 * and recode urls in $text must overwrite this method.
1017 * @param array $text some HTML text string
1018 * @return array with keys text, format and files.
1019 */
1020 public function text_field($text) {
1021 return array(
1022 'text' => trim($text),
1023 'format' => FORMAT_HTML,
1024 'files' => array(),
1025 );
1026 }
1027
1028 /**
1029 * Return the value of a node, given a path to the node
1030 * if it doesn't exist return the default value.
1031 * @param array xml data to read
1032 * @param array path path to node expressed as array
1033 * @param mixed default
1034 * @param bool istext process as text
1035 * @param string error if set value must exist, return false and issue message if not
1036 * @return mixed value
1037 */
1038 public function getpath($xml, $path, $default, $istext=false, $error='') {
1039 foreach ($path as $index) {
1040 if (!isset($xml[$index])) {
1041 if (!empty($error)) {
1042 $this->error($error);
1043 return false;
1044 } else {
1045 return $default;
1046 }
1047 }
1048
1049 $xml = $xml[$index];
1050 }
1051
1052 if ($istext) {
1053 if (!is_string($xml)) {
1054 $this->error(get_string('invalidxml', 'qformat_xml'));
1055 }
1056 $xml = trim($xml);
1057 }
1058
1059 return $xml;
1060 }
1061}