Merge branch 'MDL-64173-master' of git://github.com/bmbrands/moodle
[moodle.git] / question / format.php
blob2db3d24cb59d53f85b2cd6686d17b01317e79b36
1 <?php
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.
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/>.
17 /**
18 * Defines the base class for question import and export formats.
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
27 defined('MOODLE_INTERNAL') || die();
30 /**
31 * Base class for question import and export formats.
33 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class qformat_default {
38 public $displayerrors = true;
39 public $category = null;
40 public $questions = array();
41 public $course = null;
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;
54 protected $importcontext = null;
55 /** @var bool $displayprogress Whether to display progress. */
56 public $displayprogress = true;
58 // functions to indicate import/export functionality
59 // override to return true if implemented
61 /** @return bool whether this plugin provides import functionality. */
62 public function provide_import() {
63 return false;
66 /** @return bool whether this plugin provides export functionality. */
67 public function provide_export() {
68 return false;
71 /** The string mime-type of the files that this plugin reads or writes. */
72 public function mime_type() {
73 return mimeinfo('type', $this->export_file_extension());
76 /**
77 * @return string the file extension (including .) that is normally used for
78 * files handled by this plugin.
80 public function export_file_extension() {
81 return '.txt';
84 /**
85 * Check if the given file is capable of being imported by this plugin.
87 * Note that expensive or detailed integrity checks on the file should
88 * not be performed by this method. Simple file type or magic-number tests
89 * would be suitable.
91 * @param stored_file $file the file to check
92 * @return bool whether this plugin can import the file
94 public function can_import_file($file) {
95 return ($file->get_mimetype() == $this->mime_type());
98 // Accessor methods
101 * set the category
102 * @param object category the category object
104 public function setCategory($category) {
105 if (count($this->questions)) {
106 debugging('You shouldn\'t call setCategory after setQuestions');
108 $this->category = $category;
109 $this->importcontext = context::instance_by_id($this->category->contextid);
113 * Set the specific questions to export. Should not include questions with
114 * parents (sub questions of cloze question type).
115 * Only used for question export.
116 * @param array of question objects
118 public function setQuestions($questions) {
119 if ($this->category !== null) {
120 debugging('You shouldn\'t call setQuestions after setCategory');
122 $this->questions = $questions;
126 * set the course class variable
127 * @param course object Moodle course variable
129 public function setCourse($course) {
130 $this->course = $course;
134 * set an array of contexts.
135 * @param array $contexts Moodle course variable
137 public function setContexts($contexts) {
138 $this->contexts = $contexts;
139 $this->translator = new context_to_string_translator($this->contexts);
143 * set the filename
144 * @param string filename name of file to import/export
146 public function setFilename($filename) {
147 $this->filename = $filename;
151 * set the "real" filename
152 * (this is what the user typed, regardless of wha happened next)
153 * @param string realfilename name of file as typed by user
155 public function setRealfilename($realfilename) {
156 $this->realfilename = $realfilename;
160 * set matchgrades
161 * @param string matchgrades error or nearest for grades
163 public function setMatchgrades($matchgrades) {
164 $this->matchgrades = $matchgrades;
168 * set catfromfile
169 * @param bool catfromfile allow categories embedded in import file
171 public function setCatfromfile($catfromfile) {
172 $this->catfromfile = $catfromfile;
176 * set contextfromfile
177 * @param bool $contextfromfile allow contexts embedded in import file
179 public function setContextfromfile($contextfromfile) {
180 $this->contextfromfile = $contextfromfile;
184 * set cattofile
185 * @param bool cattofile exports categories within export file
187 public function setCattofile($cattofile) {
188 $this->cattofile = $cattofile;
192 * set contexttofile
193 * @param bool cattofile exports categories within export file
195 public function setContexttofile($contexttofile) {
196 $this->contexttofile = $contexttofile;
200 * set stoponerror
201 * @param bool stoponerror stops database write if any errors reported
203 public function setStoponerror($stoponerror) {
204 $this->stoponerror = $stoponerror;
208 * @param bool $canaccess Whether the current use can access the backup data folder. Determines
209 * where export files are saved.
211 public function set_can_access_backupdata($canaccess) {
212 $this->canaccessbackupdata = $canaccess;
216 * Change whether to display progress messages.
217 * There is normally no need to use this function as the
218 * default for $displayprogress is true.
219 * Set to false for unit tests.
220 * @param bool $displayprogress
222 public function set_display_progress($displayprogress) {
223 $this->displayprogress = $displayprogress;
226 /***********************
227 * IMPORTING FUNCTIONS
228 ***********************/
231 * Handle parsing error
233 protected function error($message, $text='', $questionname='') {
234 $importerrorquestion = get_string('importerrorquestion', 'question');
236 echo "<div class=\"importerror\">\n";
237 echo "<strong>{$importerrorquestion} {$questionname}</strong>";
238 if (!empty($text)) {
239 $text = s($text);
240 echo "<blockquote>{$text}</blockquote>\n";
242 echo "<strong>{$message}</strong>\n";
243 echo "</div>";
245 $this->importerrors++;
249 * Import for questiontype plugins
250 * Do not override.
251 * @param data mixed The segment of data containing the question
252 * @param question object processed (so far) by standard import code if appropriate
253 * @param extra mixed any additional format specific data that may be passed by the format
254 * @param qtypehint hint about a question type from format
255 * @return object question object suitable for save_options() or false if cannot handle
257 public function try_importing_using_qtypes($data, $question = null, $extra = null,
258 $qtypehint = '') {
260 // work out what format we are using
261 $formatname = substr(get_class($this), strlen('qformat_'));
262 $methodname = "import_from_{$formatname}";
264 //first try importing using a hint from format
265 if (!empty($qtypehint)) {
266 $qtype = question_bank::get_qtype($qtypehint, false);
267 if (is_object($qtype) && method_exists($qtype, $methodname)) {
268 $question = $qtype->$methodname($data, $question, $this, $extra);
269 if ($question) {
270 return $question;
275 // loop through installed questiontypes checking for
276 // function to handle this question
277 foreach (question_bank::get_all_qtypes() as $qtype) {
278 if (method_exists($qtype, $methodname)) {
279 if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
280 return $question;
284 return false;
288 * Perform any required pre-processing
289 * @return bool success
291 public function importpreprocess() {
292 return true;
296 * Process the file
297 * This method should not normally be overidden
298 * @return bool success
300 public function importprocess() {
301 global $USER, $DB, $OUTPUT;
303 // Raise time and memory, as importing can be quite intensive.
304 core_php_time_limit::raise();
305 raise_memory_limit(MEMORY_EXTRA);
307 // STAGE 1: Parse the file
308 if ($this->displayprogress) {
309 echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
312 if (! $lines = $this->readdata($this->filename)) {
313 echo $OUTPUT->notification(get_string('cannotread', 'question'));
314 return false;
317 if (!$questions = $this->readquestions($lines)) { // Extract all the questions
318 echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
319 return false;
322 // STAGE 2: Write data to database
323 if ($this->displayprogress) {
324 echo $OUTPUT->notification(get_string('importingquestions', 'question',
325 $this->count_questions($questions)), 'notifysuccess');
328 // check for errors before we continue
329 if ($this->stoponerror and ($this->importerrors>0)) {
330 echo $OUTPUT->notification(get_string('importparseerror', 'question'));
331 return true;
334 // get list of valid answer grades
335 $gradeoptionsfull = question_bank::fraction_options_full();
337 // check answer grades are valid
338 // (now need to do this here because of 'stop on error': MDL-10689)
339 $gradeerrors = 0;
340 $goodquestions = array();
341 foreach ($questions as $question) {
342 if (!empty($question->fraction) and (is_array($question->fraction))) {
343 $fractions = $question->fraction;
344 $invalidfractions = array();
345 foreach ($fractions as $key => $fraction) {
346 $newfraction = match_grade_options($gradeoptionsfull, $fraction,
347 $this->matchgrades);
348 if ($newfraction === false) {
349 $invalidfractions[] = $fraction;
350 } else {
351 $fractions[$key] = $newfraction;
354 if ($invalidfractions) {
355 echo $OUTPUT->notification(get_string('invalidgrade', 'question',
356 implode(', ', $invalidfractions)));
357 ++$gradeerrors;
358 continue;
359 } else {
360 $question->fraction = $fractions;
363 $goodquestions[] = $question;
365 $questions = $goodquestions;
367 // check for errors before we continue
368 if ($this->stoponerror && $gradeerrors > 0) {
369 return false;
372 // count number of questions processed
373 $count = 0;
375 foreach ($questions as $question) { // Process and store each question
376 $transaction = $DB->start_delegated_transaction();
378 // reset the php timeout
379 core_php_time_limit::raise();
381 // check for category modifiers
382 if ($question->qtype == 'category') {
383 if ($this->catfromfile) {
384 // find/create category object
385 $catpath = $question->category;
386 $newcategory = $this->create_category_path($catpath, $question);
387 if (!empty($newcategory)) {
388 $this->category = $newcategory;
391 $transaction->allow_commit();
392 continue;
394 $question->context = $this->importcontext;
396 $count++;
398 if ($this->displayprogress) {
399 echo "<hr /><p><b>{$count}</b>. " . $this->format_question_text($question) . "</p>";
402 $question->category = $this->category->id;
403 $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
405 $question->createdby = $USER->id;
406 $question->timecreated = time();
407 $question->modifiedby = $USER->id;
408 $question->timemodified = time();
409 if (isset($question->idnumber)) {
410 if ((string) $question->idnumber === '') {
411 // Id number not really set. Get rid of it.
412 unset($question->idnumber);
413 } else {
414 if ($DB->record_exists('question',
415 ['idnumber' => $question->idnumber, 'category' => $question->category])) {
416 // We cannot have duplicate idnumbers in a category. Just remove it.
417 unset($question->idnumber);
422 $fileoptions = array(
423 'subdirs' => true,
424 'maxfiles' => -1,
425 'maxbytes' => 0,
428 $question->id = $DB->insert_record('question', $question);
430 if (isset($question->questiontextitemid)) {
431 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
432 $this->importcontext->id, 'question', 'questiontext', $question->id,
433 $fileoptions, $question->questiontext);
434 } else if (isset($question->questiontextfiles)) {
435 foreach ($question->questiontextfiles as $file) {
436 question_bank::get_qtype($question->qtype)->import_file(
437 $this->importcontext, 'question', 'questiontext', $question->id, $file);
440 if (isset($question->generalfeedbackitemid)) {
441 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
442 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
443 $fileoptions, $question->generalfeedback);
444 } else if (isset($question->generalfeedbackfiles)) {
445 foreach ($question->generalfeedbackfiles as $file) {
446 question_bank::get_qtype($question->qtype)->import_file(
447 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
450 $DB->update_record('question', $question);
452 $this->questionids[] = $question->id;
454 // Now to save all the answers and type-specific options
456 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
458 if (core_tag_tag::is_enabled('core_question', 'question')) {
459 // Is the current context we're importing in a course context?
460 $importingcontext = $this->importcontext;
461 $importingcoursecontext = $importingcontext->get_course_context(false);
462 $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
464 if (!empty($question->coursetags)) {
465 if ($isimportingcontextcourseoractivity) {
466 $mergedtags = array_merge($question->coursetags, $question->tags);
468 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
469 $question->context, $mergedtags);
470 } else {
471 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
472 context_course::instance($this->course->id), $question->coursetags);
474 if (!empty($question->tags)) {
475 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
476 $importingcontext, $question->tags);
479 } else if (!empty($question->tags)) {
480 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
481 $question->context, $question->tags);
485 if (!empty($result->error)) {
486 echo $OUTPUT->notification($result->error);
487 // Can't use $transaction->rollback(); since it requires an exception,
488 // and I don't want to rewrite this code to change the error handling now.
489 $DB->force_transaction_rollback();
490 return false;
493 $transaction->allow_commit();
495 if (!empty($result->notice)) {
496 echo $OUTPUT->notification($result->notice);
497 return true;
500 // Give the question a unique version stamp determined by question_hash()
501 $DB->set_field('question', 'version', question_hash($question),
502 array('id' => $question->id));
504 return true;
508 * Count all non-category questions in the questions array.
510 * @param array questions An array of question objects.
511 * @return int The count.
514 protected function count_questions($questions) {
515 $count = 0;
516 if (!is_array($questions)) {
517 return $count;
519 foreach ($questions as $question) {
520 if (!is_object($question) || !isset($question->qtype) ||
521 ($question->qtype == 'category')) {
522 continue;
524 $count++;
526 return $count;
530 * find and/or create the category described by a delimited list
531 * e.g. $course$/tom/dick/harry or tom/dick/harry
533 * removes any context string no matter whether $getcontext is set
534 * but if $getcontext is set then ignore the context and use selected category context.
536 * @param string catpath delimited category path
537 * @param object $lastcategoryinfo Contains category information
538 * @return mixed category object or null if fails
540 protected function create_category_path($catpath, $lastcategoryinfo = null) {
541 global $DB;
542 $catnames = $this->split_category_path($catpath);
543 $parent = 0;
544 $category = null;
546 // check for context id in path, it might not be there in pre 1.9 exports
547 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
548 if ($matchcount == 1) {
549 $contextid = $this->translator->string_to_context($matches[1]);
550 array_shift($catnames);
551 } else {
552 $contextid = false;
555 // Before 3.5, question categories could be created at top level.
556 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
557 if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
558 array_unshift($catnames, 'top');
561 if ($this->contextfromfile && $contextid !== false) {
562 $context = context::instance_by_id($contextid);
563 require_capability('moodle/question:add', $context);
564 } else {
565 $context = context::instance_by_id($this->category->contextid);
567 $this->importcontext = $context;
569 // Now create any categories that need to be created.
570 foreach ($catnames as $key => $catname) {
571 if ($parent == 0) {
572 $category = question_get_top_category($context->id, true);
573 $parent = $category->id;
574 } else if ($category = $DB->get_record('question_categories',
575 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
576 // Do nothing unless the child category appears before the parent category
577 // in the imported xml file. Because the parent was created without info being available
578 // at that time, this allows the info to be added from the xml data.
579 if ($key == (count($catnames) - 1) && $lastcategoryinfo && isset($lastcategoryinfo->info) &&
580 $lastcategoryinfo->info !== '' && $category->info === '') {
581 $category->info = $lastcategoryinfo->info;
582 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
583 $category->infoformat = $lastcategoryinfo->infoformat;
585 $DB->update_record('question_categories', $category);
587 $parent = $category->id;
588 } else {
589 if ($catname == 'top') {
590 // Should not happen, but if it does just move on.
591 // Occurs when there has been some import/export that has created
592 // multiple nested 'top' categories (due to old bug solved by MDL-63165).
593 // This basically silently cleans up old errors. Not throwing an exception here.
594 continue;
596 require_capability('moodle/question:managecategory', $context);
597 // Create the new category. This will create all the categories in the catpath,
598 // though only the final category will have any info added if available.
599 $category = new stdClass();
600 $category->contextid = $context->id;
601 $category->name = $catname;
602 $category->info = '';
603 // Only add info (category description) for the final category in the catpath.
604 if ($key == (count($catnames) - 1) && $lastcategoryinfo && isset($lastcategoryinfo->info) &&
605 $lastcategoryinfo->info !== '') {
606 $category->info = $lastcategoryinfo->info;
607 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
608 $category->infoformat = $lastcategoryinfo->infoformat;
611 $category->parent = $parent;
612 $category->sortorder = 999;
613 $category->stamp = make_unique_id_code();
614 $category->id = $DB->insert_record('question_categories', $category);
615 $parent = $category->id;
618 return $category;
622 * Return complete file within an array, one item per line
623 * @param string filename name of file
624 * @return mixed contents array or false on failure
626 protected function readdata($filename) {
627 if (is_readable($filename)) {
628 $filearray = file($filename);
630 // If the first line of the file starts with a UTF-8 BOM, remove it.
631 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
633 // Check for Macintosh OS line returns (ie file on one line), and fix.
634 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
635 return explode("\r", $filearray[0]);
636 } else {
637 return $filearray;
640 return false;
644 * Parses an array of lines into an array of questions,
645 * where each item is a question object as defined by
646 * readquestion(). Questions are defined as anything
647 * between blank lines.
649 * NOTE this method used to take $context as a second argument. However, at
650 * the point where this method was called, it was impossible to know what
651 * context the quetsions were going to be saved into, so the value could be
652 * wrong. Also, none of the standard question formats were using this argument,
653 * so it was removed. See MDL-32220.
655 * If your format does not use blank lines as a delimiter
656 * then you will need to override this method. Even then
657 * try to use readquestion for each question
658 * @param array lines array of lines from readdata
659 * @return array array of question objects
661 protected function readquestions($lines) {
663 $questions = array();
664 $currentquestion = array();
666 foreach ($lines as $line) {
667 $line = trim($line);
668 if (empty($line)) {
669 if (!empty($currentquestion)) {
670 if ($question = $this->readquestion($currentquestion)) {
671 $questions[] = $question;
673 $currentquestion = array();
675 } else {
676 $currentquestion[] = $line;
680 if (!empty($currentquestion)) { // There may be a final question
681 if ($question = $this->readquestion($currentquestion)) {
682 $questions[] = $question;
686 return $questions;
690 * return an "empty" question
691 * Somewhere to specify question parameters that are not handled
692 * by import but are required db fields.
693 * This should not be overridden.
694 * @return object default question
696 protected function defaultquestion() {
697 global $CFG;
698 static $defaultshuffleanswers = null;
699 if (is_null($defaultshuffleanswers)) {
700 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
703 $question = new stdClass();
704 $question->shuffleanswers = $defaultshuffleanswers;
705 $question->defaultmark = 1;
706 $question->image = '';
707 $question->usecase = 0;
708 $question->multiplier = array();
709 $question->questiontextformat = FORMAT_MOODLE;
710 $question->generalfeedback = '';
711 $question->generalfeedbackformat = FORMAT_MOODLE;
712 $question->answernumbering = 'abc';
713 $question->penalty = 0.3333333;
714 $question->length = 1;
716 // this option in case the questiontypes class wants
717 // to know where the data came from
718 $question->export_process = true;
719 $question->import_process = true;
721 $this->add_blank_combined_feedback($question);
723 return $question;
727 * Construct a reasonable default question name, based on the start of the question text.
728 * @param string $questiontext the question text.
729 * @param string $default default question name to use if the constructed one comes out blank.
730 * @return string a reasonable question name.
732 public function create_default_question_name($questiontext, $default) {
733 $name = $this->clean_question_name(shorten_text($questiontext, 80));
734 if ($name) {
735 return $name;
736 } else {
737 return $default;
742 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
743 * @param string $name the raw question name.
744 * @return string a safe question name.
746 public function clean_question_name($name) {
747 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
748 $name = trim($name);
749 $trimlength = 251;
750 while (core_text::strlen($name) > 255 && $trimlength > 0) {
751 $name = shorten_text($name, $trimlength);
752 $trimlength -= 10;
754 return $name;
758 * Add a blank combined feedback to a question object.
759 * @param object question
760 * @return object question
762 protected function add_blank_combined_feedback($question) {
763 $question->correctfeedback = [
764 'text' => '',
765 'format' => $question->questiontextformat,
766 'files' => []
768 $question->partiallycorrectfeedback = [
769 'text' => '',
770 'format' => $question->questiontextformat,
771 'files' => []
773 $question->incorrectfeedback = [
774 'text' => '',
775 'format' => $question->questiontextformat,
776 'files' => []
778 return $question;
782 * Given the data known to define a question in
783 * this format, this function converts it into a question
784 * object suitable for processing and insertion into Moodle.
786 * If your format does not use blank lines to delimit questions
787 * (e.g. an XML format) you must override 'readquestions' too
788 * @param $lines mixed data that represents question
789 * @return object question object
791 protected function readquestion($lines) {
792 // We should never get there unless the qformat plugin is broken.
793 throw new coding_exception('Question format plugin is missing important code: readquestion.');
795 return null;
799 * Override if any post-processing is required
800 * @return bool success
802 public function importpostprocess() {
803 return true;
806 /*******************
807 * EXPORT FUNCTIONS
808 *******************/
811 * Provide export functionality for plugin questiontypes
812 * Do not override
813 * @param name questiontype name
814 * @param question object data to export
815 * @param extra mixed any addition format specific data needed
816 * @return string the data to append to export or false if error (or unhandled)
818 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
819 // work out the name of format in use
820 $formatname = substr(get_class($this), strlen('qformat_'));
821 $methodname = "export_to_{$formatname}";
823 $qtype = question_bank::get_qtype($name, false);
824 if (method_exists($qtype, $methodname)) {
825 return $qtype->$methodname($question, $this, $extra);
827 return false;
831 * Do any pre-processing that may be required
832 * @param bool success
834 public function exportpreprocess() {
835 return true;
839 * Enable any processing to be done on the content
840 * just prior to the file being saved
841 * default is to do nothing
842 * @param string output text
843 * @param string processed output text
845 protected function presave_process($content) {
846 return $content;
850 * Perform the export.
851 * For most types this should not need to be overrided.
853 * @param bool $checkcapabilities Whether to check capabilities when exporting the questions.
854 * @return string The content of the export.
856 public function exportprocess($checkcapabilities = true) {
857 global $CFG, $DB;
859 // Get the parents (from database) for this category.
860 $parents = [];
861 if ($this->category) {
862 $parents = question_categorylist_parents($this->category->id);
865 // get the questions (from database) in this category
866 // only get q's with no parents (no cloze subquestions specifically)
867 if ($this->category) {
868 $questions = get_questions_category($this->category, true);
869 } else {
870 $questions = $this->questions;
873 $count = 0;
875 // results are first written into string (and then to a file)
876 // so create/initialize the string here
877 $expout = '';
879 // track which category questions are in
880 // if it changes we will record the category change in the output
881 // file if selected. 0 means that it will get printed before the 1st question
882 $trackcategory = 0;
884 // Array of categories written to file.
885 $writtencategories = [];
887 foreach ($questions as $question) {
888 // used by file api
889 $contextid = $DB->get_field('question_categories', 'contextid',
890 array('id' => $question->category));
891 $question->contextid = $contextid;
893 // do not export hidden questions
894 if (!empty($question->hidden)) {
895 continue;
898 // do not export random questions
899 if ($question->qtype == 'random') {
900 continue;
903 // check if we need to record category change
904 if ($this->cattofile) {
905 $addnewcat = false;
906 if ($question->category != $trackcategory) {
907 $addnewcat = true;
908 $trackcategory = $question->category;
910 $trackcategoryparents = question_categorylist_parents($trackcategory);
911 // Check if we need to record empty parents categories.
912 foreach ($trackcategoryparents as $trackcategoryparent) {
913 // If parent wasn't written.
914 if (!in_array($trackcategoryparent, $writtencategories)) {
915 // If parent is empty.
916 if (!count($DB->get_records('question', array('category' => $trackcategoryparent)))) {
917 $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
918 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
919 'name, info, infoformat', MUST_EXIST);
920 if ($categoryinfo->name != 'top') {
921 // Create 'dummy' question for parent category.
922 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
923 $expout .= $this->writequestion($dummyquestion) . "\n";
924 $writtencategories[] = $trackcategoryparent;
929 if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
930 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
931 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
932 'info, infoformat', MUST_EXIST);
933 // Create 'dummy' question for category.
934 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
935 $expout .= $this->writequestion($dummyquestion) . "\n";
936 $writtencategories[] = $trackcategory;
940 // export the question displaying message
941 $count++;
943 if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
944 $expout .= $this->writequestion($question, $contextid) . "\n";
948 // continue path for following error checks
949 $course = $this->course;
950 $continuepath = "{$CFG->wwwroot}/question/export.php?courseid={$course->id}";
952 // did we actually process anything
953 if ($count==0) {
954 print_error('noquestions', 'question', $continuepath);
957 // final pre-process on exported data
958 $expout = $this->presave_process($expout);
959 return $expout;
963 * Create 'dummy' question for category export.
964 * @param string $categoryname the name of the category
965 * @param object $categoryinfo description of the category
966 * @return stdClass 'dummy' question for category
968 protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
969 $dummyquestion = new stdClass();
970 $dummyquestion->qtype = 'category';
971 $dummyquestion->category = $categoryname;
972 $dummyquestion->id = 0;
973 $dummyquestion->questiontextformat = '';
974 $dummyquestion->contextid = 0;
975 $dummyquestion->info = $categoryinfo->info;
976 $dummyquestion->infoformat = $categoryinfo->infoformat;
977 $dummyquestion->name = 'Switch category to ' . $categoryname;
978 return $dummyquestion;
982 * get the category as a path (e.g., tom/dick/harry)
983 * @param int id the id of the most nested catgory
984 * @return string the path
986 protected function get_category_path($id, $includecontext = true) {
987 global $DB;
989 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
990 print_error('cannotfindcategory', 'error', '', $id);
992 $contextstring = $this->translator->context_to_string($category->contextid);
994 $pathsections = array();
995 do {
996 $pathsections[] = $category->name;
997 $id = $category->parent;
998 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
1000 if ($includecontext) {
1001 $pathsections[] = '$' . $contextstring . '$';
1004 $path = $this->assemble_category_path(array_reverse($pathsections));
1006 return $path;
1010 * Convert a list of category names, possibly preceeded by one of the
1011 * context tokens like $course$, into a string representation of the
1012 * category path.
1014 * Names are separated by / delimiters. And /s in the name are replaced by //.
1016 * To reverse the process and split the paths into names, use
1017 * {@link split_category_path()}.
1019 * @param array $names
1020 * @return string
1022 protected function assemble_category_path($names) {
1023 $escapednames = array();
1024 foreach ($names as $name) {
1025 $escapedname = str_replace('/', '//', $name);
1026 if (substr($escapedname, 0, 1) == '/') {
1027 $escapedname = ' ' . $escapedname;
1029 if (substr($escapedname, -1) == '/') {
1030 $escapedname = $escapedname . ' ';
1032 $escapednames[] = $escapedname;
1034 return implode('/', $escapednames);
1038 * Convert a string, as returned by {@link assemble_category_path()},
1039 * back into an array of category names.
1041 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
1042 * which matches the cleaning in question/category_form.php.
1044 * @param string $path
1045 * @return array of category names.
1047 protected function split_category_path($path) {
1048 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1049 $names = array();
1050 foreach ($rawnames as $rawname) {
1051 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
1053 return $names;
1057 * Do an post-processing that may be required
1058 * @return bool success
1060 protected function exportpostprocess() {
1061 return true;
1065 * convert a single question object into text output in the given
1066 * format.
1067 * This must be overriden
1068 * @param object question question object
1069 * @return mixed question export text or null if not implemented
1071 protected function writequestion($question) {
1072 // if not overidden, then this is an error.
1073 throw new coding_exception('Question format plugin is missing important code: writequestion.');
1074 return null;
1078 * Convert the question text to plain text, so it can safely be displayed
1079 * during import to let the user see roughly what is going on.
1081 protected function format_question_text($question) {
1082 return s(question_utils::to_plain_text($question->questiontext,
1083 $question->questiontextformat));
1087 class qformat_based_on_xml extends qformat_default {
1090 * A lot of imported files contain unwanted entities.
1091 * This method tries to clean up all known problems.
1092 * @param string str string to correct
1093 * @return string the corrected string
1095 public function cleaninput($str) {
1097 $html_code_list = array(
1098 "&#039;" => "'",
1099 "&#8217;" => "'",
1100 "&#8220;" => "\"",
1101 "&#8221;" => "\"",
1102 "&#8211;" => "-",
1103 "&#8212;" => "-",
1105 $str = strtr($str, $html_code_list);
1106 // Use core_text entities_to_utf8 function to convert only numerical entities.
1107 $str = core_text::entities_to_utf8($str, false);
1108 return $str;
1112 * Return the array moodle is expecting
1113 * for an HTML text. No processing is done on $text.
1114 * qformat classes that want to process $text
1115 * for instance to import external images files
1116 * and recode urls in $text must overwrite this method.
1117 * @param array $text some HTML text string
1118 * @return array with keys text, format and files.
1120 public function text_field($text) {
1121 return array(
1122 'text' => trim($text),
1123 'format' => FORMAT_HTML,
1124 'files' => array(),
1129 * Return the value of a node, given a path to the node
1130 * if it doesn't exist return the default value.
1131 * @param array xml data to read
1132 * @param array path path to node expressed as array
1133 * @param mixed default
1134 * @param bool istext process as text
1135 * @param string error if set value must exist, return false and issue message if not
1136 * @return mixed value
1138 public function getpath($xml, $path, $default, $istext=false, $error='') {
1139 foreach ($path as $index) {
1140 if (!isset($xml[$index])) {
1141 if (!empty($error)) {
1142 $this->error($error);
1143 return false;
1144 } else {
1145 return $default;
1149 $xml = $xml[$index];
1152 if ($istext) {
1153 if (!is_string($xml)) {
1154 $this->error(get_string('invalidxml', 'qformat_xml'));
1156 $xml = trim($xml);
1159 return $xml;