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