Merge branch 'MDL-73457-master-2' of https://github.com/HuongNV13/moodle
[moodle.git] / question / format.php
blobf3819694ecb3fc05353d3b15c4bad6c33f8a4009
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 core_question\local\bank\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_bank_entries',
415 ['idnumber' => $question->idnumber, 'questioncategoryid' => $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);
429 // Create a bank entry for each question imported.
430 $questionbankentry = new \stdClass();
431 $questionbankentry->questioncategoryid = $question->category;
432 $questionbankentry->idnumber = $question->idnumber ?? null;
433 $questionbankentry->ownerid = $question->createdby;
434 $questionbankentry->id = $DB->insert_record('question_bank_entries', $questionbankentry);
435 // Create a version for each question imported.
436 $questionversion = new \stdClass();
437 $questionversion->questionbankentryid = $questionbankentry->id;
438 $questionversion->questionid = $question->id;
439 $questionversion->version = 1;
440 $questionversion->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
441 $questionversion->id = $DB->insert_record('question_versions', $questionversion);
443 $event = \core\event\question_created::create_from_question_instance($question, $this->importcontext);
444 $event->trigger();
446 if (isset($question->questiontextitemid)) {
447 $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
448 $this->importcontext->id, 'question', 'questiontext', $question->id,
449 $fileoptions, $question->questiontext);
450 } else if (isset($question->questiontextfiles)) {
451 foreach ($question->questiontextfiles as $file) {
452 question_bank::get_qtype($question->qtype)->import_file(
453 $this->importcontext, 'question', 'questiontext', $question->id, $file);
456 if (isset($question->generalfeedbackitemid)) {
457 $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
458 $this->importcontext->id, 'question', 'generalfeedback', $question->id,
459 $fileoptions, $question->generalfeedback);
460 } else if (isset($question->generalfeedbackfiles)) {
461 foreach ($question->generalfeedbackfiles as $file) {
462 question_bank::get_qtype($question->qtype)->import_file(
463 $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
466 $DB->update_record('question', $question);
468 $this->questionids[] = $question->id;
470 // Now to save all the answers and type-specific options
472 $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
474 if (core_tag_tag::is_enabled('core_question', 'question')) {
475 // Is the current context we're importing in a course context?
476 $importingcontext = $this->importcontext;
477 $importingcoursecontext = $importingcontext->get_course_context(false);
478 $isimportingcontextcourseoractivity = !empty($importingcoursecontext);
480 if (!empty($question->coursetags)) {
481 if ($isimportingcontextcourseoractivity) {
482 $mergedtags = array_merge($question->coursetags, $question->tags);
484 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
485 $question->context, $mergedtags);
486 } else {
487 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
488 context_course::instance($this->course->id), $question->coursetags);
490 if (!empty($question->tags)) {
491 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
492 $importingcontext, $question->tags);
495 } else if (!empty($question->tags)) {
496 core_tag_tag::set_item_tags('core_question', 'question', $question->id,
497 $question->context, $question->tags);
501 if (!empty($result->error)) {
502 echo $OUTPUT->notification($result->error);
503 // Can't use $transaction->rollback(); since it requires an exception,
504 // and I don't want to rewrite this code to change the error handling now.
505 $DB->force_transaction_rollback();
506 return false;
509 $transaction->allow_commit();
511 if (!empty($result->notice)) {
512 echo $OUTPUT->notification($result->notice);
513 return true;
517 return true;
521 * Count all non-category questions in the questions array.
523 * @param array questions An array of question objects.
524 * @return int The count.
527 protected function count_questions($questions) {
528 $count = 0;
529 if (!is_array($questions)) {
530 return $count;
532 foreach ($questions as $question) {
533 if (!is_object($question) || !isset($question->qtype) ||
534 ($question->qtype == 'category')) {
535 continue;
537 $count++;
539 return $count;
543 * find and/or create the category described by a delimited list
544 * e.g. $course$/tom/dick/harry or tom/dick/harry
546 * removes any context string no matter whether $getcontext is set
547 * but if $getcontext is set then ignore the context and use selected category context.
549 * @param string catpath delimited category path
550 * @param object $lastcategoryinfo Contains category information
551 * @return mixed category object or null if fails
553 protected function create_category_path($catpath, $lastcategoryinfo = null) {
554 global $DB;
555 $catnames = $this->split_category_path($catpath);
556 $parent = 0;
557 $category = null;
559 // check for context id in path, it might not be there in pre 1.9 exports
560 $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
561 if ($matchcount == 1) {
562 $contextid = $this->translator->string_to_context($matches[1]);
563 array_shift($catnames);
564 } else {
565 $contextid = false;
568 // Before 3.5, question categories could be created at top level.
569 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
570 if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
571 array_unshift($catnames, 'top');
574 if ($this->contextfromfile && $contextid !== false) {
575 $context = context::instance_by_id($contextid);
576 require_capability('moodle/question:add', $context);
577 } else {
578 $context = context::instance_by_id($this->category->contextid);
580 $this->importcontext = $context;
582 // Now create any categories that need to be created.
583 foreach ($catnames as $key => $catname) {
584 if ($parent == 0) {
585 $category = question_get_top_category($context->id, true);
586 $parent = $category->id;
587 } else if ($category = $DB->get_record('question_categories',
588 array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
589 // If this category is now the last one in the path we are processing ...
590 if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
591 // Do nothing unless the child category appears before the parent category
592 // in the imported xml file. Because the parent was created without info being available
593 // at that time, this allows the info to be added from the xml data.
594 if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== ''
595 && $category->info === '') {
596 $category->info = $lastcategoryinfo->info;
597 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
598 $category->infoformat = $lastcategoryinfo->infoformat;
601 // Same for idnumber.
602 if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== ''
603 && $category->idnumber === '') {
604 $category->idnumber = $lastcategoryinfo->idnumber;
606 $DB->update_record('question_categories', $category);
608 $parent = $category->id;
609 } else {
610 if ($catname == 'top') {
611 // Should not happen, but if it does just move on.
612 // Occurs when there has been some import/export that has created
613 // multiple nested 'top' categories (due to old bug solved by MDL-63165).
614 // This basically silently cleans up old errors. Not throwing an exception here.
615 continue;
617 require_capability('moodle/question:managecategory', $context);
618 // Create the new category. This will create all the categories in the catpath,
619 // though only the final category will have any info added if available.
620 $category = new stdClass();
621 $category->contextid = $context->id;
622 $category->name = $catname;
623 $category->info = '';
624 // Only add info (category description) for the final category in the catpath.
625 if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
626 if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== '') {
627 $category->info = $lastcategoryinfo->info;
628 if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
629 $category->infoformat = $lastcategoryinfo->infoformat;
632 // Same for idnumber.
633 if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== '') {
634 $category->idnumber = $lastcategoryinfo->idnumber;
637 $category->parent = $parent;
638 $category->sortorder = 999;
639 $category->stamp = make_unique_id_code();
640 $category->id = $DB->insert_record('question_categories', $category);
641 $parent = $category->id;
642 $event = \core\event\question_category_created::create_from_question_category_instance($category, $context);
643 $event->trigger();
646 return $category;
650 * Return complete file within an array, one item per line
651 * @param string filename name of file
652 * @return mixed contents array or false on failure
654 protected function readdata($filename) {
655 if (is_readable($filename)) {
656 $filearray = file($filename);
658 // If the first line of the file starts with a UTF-8 BOM, remove it.
659 $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
661 // Check for Macintosh OS line returns (ie file on one line), and fix.
662 if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
663 return explode("\r", $filearray[0]);
664 } else {
665 return $filearray;
668 return false;
672 * Parses an array of lines into an array of questions,
673 * where each item is a question object as defined by
674 * readquestion(). Questions are defined as anything
675 * between blank lines.
677 * NOTE this method used to take $context as a second argument. However, at
678 * the point where this method was called, it was impossible to know what
679 * context the quetsions were going to be saved into, so the value could be
680 * wrong. Also, none of the standard question formats were using this argument,
681 * so it was removed. See MDL-32220.
683 * If your format does not use blank lines as a delimiter
684 * then you will need to override this method. Even then
685 * try to use readquestion for each question
686 * @param array lines array of lines from readdata
687 * @return array array of question objects
689 protected function readquestions($lines) {
691 $questions = array();
692 $currentquestion = array();
694 foreach ($lines as $line) {
695 $line = trim($line);
696 if (empty($line)) {
697 if (!empty($currentquestion)) {
698 if ($question = $this->readquestion($currentquestion)) {
699 $questions[] = $question;
701 $currentquestion = array();
703 } else {
704 $currentquestion[] = $line;
708 if (!empty($currentquestion)) { // There may be a final question
709 if ($question = $this->readquestion($currentquestion)) {
710 $questions[] = $question;
714 return $questions;
718 * return an "empty" question
719 * Somewhere to specify question parameters that are not handled
720 * by import but are required db fields.
721 * This should not be overridden.
722 * @return object default question
724 protected function defaultquestion() {
725 global $CFG;
726 static $defaultshuffleanswers = null;
727 if (is_null($defaultshuffleanswers)) {
728 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
731 $question = new stdClass();
732 $question->shuffleanswers = $defaultshuffleanswers;
733 $question->defaultmark = 1;
734 $question->image = '';
735 $question->usecase = 0;
736 $question->multiplier = array();
737 $question->questiontextformat = FORMAT_MOODLE;
738 $question->generalfeedback = '';
739 $question->generalfeedbackformat = FORMAT_MOODLE;
740 $question->answernumbering = 'abc';
741 $question->penalty = 0.3333333;
742 $question->length = 1;
744 // this option in case the questiontypes class wants
745 // to know where the data came from
746 $question->export_process = true;
747 $question->import_process = true;
749 $this->add_blank_combined_feedback($question);
751 return $question;
755 * Construct a reasonable default question name, based on the start of the question text.
756 * @param string $questiontext the question text.
757 * @param string $default default question name to use if the constructed one comes out blank.
758 * @return string a reasonable question name.
760 public function create_default_question_name($questiontext, $default) {
761 $name = $this->clean_question_name(shorten_text($questiontext, 80));
762 if ($name) {
763 return $name;
764 } else {
765 return $default;
770 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
771 * @param string $name the raw question name.
772 * @return string a safe question name.
774 public function clean_question_name($name) {
775 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
776 $name = trim($name);
777 $trimlength = 251;
778 while (core_text::strlen($name) > 255 && $trimlength > 0) {
779 $name = shorten_text($name, $trimlength);
780 $trimlength -= 10;
782 return $name;
786 * Add a blank combined feedback to a question object.
787 * @param object question
788 * @return object question
790 protected function add_blank_combined_feedback($question) {
791 $question->correctfeedback = [
792 'text' => '',
793 'format' => $question->questiontextformat,
794 'files' => []
796 $question->partiallycorrectfeedback = [
797 'text' => '',
798 'format' => $question->questiontextformat,
799 'files' => []
801 $question->incorrectfeedback = [
802 'text' => '',
803 'format' => $question->questiontextformat,
804 'files' => []
806 return $question;
810 * Given the data known to define a question in
811 * this format, this function converts it into a question
812 * object suitable for processing and insertion into Moodle.
814 * If your format does not use blank lines to delimit questions
815 * (e.g. an XML format) you must override 'readquestions' too
816 * @param $lines mixed data that represents question
817 * @return object question object
819 protected function readquestion($lines) {
820 // We should never get there unless the qformat plugin is broken.
821 throw new coding_exception('Question format plugin is missing important code: readquestion.');
823 return null;
827 * Override if any post-processing is required
828 * @return bool success
830 public function importpostprocess() {
831 return true;
834 /*******************
835 * EXPORT FUNCTIONS
836 *******************/
839 * Provide export functionality for plugin questiontypes
840 * Do not override
841 * @param name questiontype name
842 * @param question object data to export
843 * @param extra mixed any addition format specific data needed
844 * @return string the data to append to export or false if error (or unhandled)
846 protected function try_exporting_using_qtypes($name, $question, $extra=null) {
847 // work out the name of format in use
848 $formatname = substr(get_class($this), strlen('qformat_'));
849 $methodname = "export_to_{$formatname}";
851 $qtype = question_bank::get_qtype($name, false);
852 if (method_exists($qtype, $methodname)) {
853 return $qtype->$methodname($question, $this, $extra);
855 return false;
859 * Do any pre-processing that may be required
860 * @param bool success
862 public function exportpreprocess() {
863 return true;
867 * Enable any processing to be done on the content
868 * just prior to the file being saved
869 * default is to do nothing
870 * @param string output text
871 * @param string processed output text
873 protected function presave_process($content) {
874 return $content;
878 * Perform the export.
879 * For most types this should not need to be overrided.
881 * @param bool $checkcapabilities Whether to check capabilities when exporting the questions.
882 * @return string The content of the export.
884 public function exportprocess($checkcapabilities = true) {
885 global $CFG, $DB;
887 // Raise time and memory, as exporting can be quite intensive.
888 core_php_time_limit::raise();
889 raise_memory_limit(MEMORY_EXTRA);
891 // Get the parents (from database) for this category.
892 $parents = [];
893 if ($this->category) {
894 $parents = question_categorylist_parents($this->category->id);
897 // get the questions (from database) in this category
898 // only get q's with no parents (no cloze subquestions specifically)
899 if ($this->category) {
900 // Export only the latest version of a question.
901 $questions = get_questions_category($this->category, true, true, true, true);
902 } else {
903 $questions = $this->questions;
906 $count = 0;
908 // results are first written into string (and then to a file)
909 // so create/initialize the string here
910 $expout = '';
912 // track which category questions are in
913 // if it changes we will record the category change in the output
914 // file if selected. 0 means that it will get printed before the 1st question
915 $trackcategory = 0;
917 // Array of categories written to file.
918 $writtencategories = [];
920 foreach ($questions as $question) {
921 // used by file api
922 $questionbankentry = question_bank::load_question($question->id);
923 $qcategory = $questionbankentry->category;
924 $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $qcategory]);
925 $question->contextid = $contextid;
926 $question->idnumber = $questionbankentry->idnumber;
927 if ($question->status === \core_question\local\bank\question_version_status::QUESTION_STATUS_READY) {
928 $question->status = 0;
929 } else {
930 $question->status = 1;
933 // do not export hidden questions
934 if (!empty($question->hidden)) {
935 continue;
938 // do not export random questions
939 if ($question->qtype == 'random') {
940 continue;
943 // check if we need to record category change
944 if ($this->cattofile) {
945 $addnewcat = false;
946 if ($question->category != $trackcategory) {
947 $addnewcat = true;
948 $trackcategory = $question->category;
950 $trackcategoryparents = question_categorylist_parents($trackcategory);
951 // Check if we need to record empty parents categories.
952 foreach ($trackcategoryparents as $trackcategoryparent) {
953 // If parent wasn't written.
954 if (!in_array($trackcategoryparent, $writtencategories)) {
955 // If parent is empty.
956 if (!count($DB->get_records('question_bank_entries', ['questioncategoryid' => $trackcategoryparent]))) {
957 $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
958 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
959 'name, info, infoformat, idnumber', MUST_EXIST);
960 if ($categoryinfo->name != 'top') {
961 // Create 'dummy' question for parent category.
962 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
963 $expout .= $this->writequestion($dummyquestion) . "\n";
964 $writtencategories[] = $trackcategoryparent;
969 if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
970 $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
971 $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
972 'info, infoformat, idnumber', MUST_EXIST);
973 // Create 'dummy' question for category.
974 $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
975 $expout .= $this->writequestion($dummyquestion) . "\n";
976 $writtencategories[] = $trackcategory;
980 // Add the question to result.
981 if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
982 $expquestion = $this->writequestion($question, $contextid);
983 // Don't add anything if witequestion returned nothing.
984 // This will permit qformat plugins to exclude some questions.
985 if ($expquestion !== null) {
986 $expout .= $expquestion . "\n";
987 $count++;
992 // continue path for following error checks
993 $course = $this->course;
994 $continuepath = "{$CFG->wwwroot}/question/bank/exportquestions/export.php?courseid={$course->id}";
996 // did we actually process anything
997 if ($count==0) {
998 print_error('noquestions', 'question', $continuepath);
1001 // final pre-process on exported data
1002 $expout = $this->presave_process($expout);
1003 return $expout;
1007 * Create 'dummy' question for category export.
1008 * @param string $categoryname the name of the category
1009 * @param object $categoryinfo description of the category
1010 * @return stdClass 'dummy' question for category
1012 protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
1013 $dummyquestion = new stdClass();
1014 $dummyquestion->qtype = 'category';
1015 $dummyquestion->category = $categoryname;
1016 $dummyquestion->id = 0;
1017 $dummyquestion->questiontextformat = '';
1018 $dummyquestion->contextid = 0;
1019 $dummyquestion->info = $categoryinfo->info;
1020 $dummyquestion->infoformat = $categoryinfo->infoformat;
1021 $dummyquestion->idnumber = $categoryinfo->idnumber;
1022 $dummyquestion->name = 'Switch category to ' . $categoryname;
1023 return $dummyquestion;
1027 * get the category as a path (e.g., tom/dick/harry)
1028 * @param int id the id of the most nested catgory
1029 * @return string the path
1031 protected function get_category_path($id, $includecontext = true) {
1032 global $DB;
1034 if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1035 print_error('cannotfindcategory', 'error', '', $id);
1037 $contextstring = $this->translator->context_to_string($category->contextid);
1039 $pathsections = array();
1040 do {
1041 $pathsections[] = $category->name;
1042 $id = $category->parent;
1043 } while ($category = $DB->get_record('question_categories', array('id' => $id)));
1045 if ($includecontext) {
1046 $pathsections[] = '$' . $contextstring . '$';
1049 $path = $this->assemble_category_path(array_reverse($pathsections));
1051 return $path;
1055 * Convert a list of category names, possibly preceeded by one of the
1056 * context tokens like $course$, into a string representation of the
1057 * category path.
1059 * Names are separated by / delimiters. And /s in the name are replaced by //.
1061 * To reverse the process and split the paths into names, use
1062 * {@link split_category_path()}.
1064 * @param array $names
1065 * @return string
1067 protected function assemble_category_path($names) {
1068 $escapednames = array();
1069 foreach ($names as $name) {
1070 $escapedname = str_replace('/', '//', $name);
1071 if (substr($escapedname, 0, 1) == '/') {
1072 $escapedname = ' ' . $escapedname;
1074 if (substr($escapedname, -1) == '/') {
1075 $escapedname = $escapedname . ' ';
1077 $escapednames[] = $escapedname;
1079 return implode('/', $escapednames);
1083 * Convert a string, as returned by {@link assemble_category_path()},
1084 * back into an array of category names.
1086 * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
1087 * which matches the cleaning in question/bank/managecategories/category_form.php.
1089 * @param string $path
1090 * @return array of category names.
1092 protected function split_category_path($path) {
1093 $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1094 $names = array();
1095 foreach ($rawnames as $rawname) {
1096 $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
1098 return $names;
1102 * Do an post-processing that may be required
1103 * @return bool success
1105 protected function exportpostprocess() {
1106 return true;
1110 * convert a single question object into text output in the given
1111 * format.
1112 * This must be overriden
1113 * @param object question question object
1114 * @return mixed question export text or null if not implemented
1116 protected function writequestion($question) {
1117 // if not overidden, then this is an error.
1118 throw new coding_exception('Question format plugin is missing important code: writequestion.');
1119 return null;
1123 * Convert the question text to plain text, so it can safely be displayed
1124 * during import to let the user see roughly what is going on.
1126 protected function format_question_text($question) {
1127 return s(question_utils::to_plain_text($question->questiontext,
1128 $question->questiontextformat));
1132 class qformat_based_on_xml extends qformat_default {
1135 * A lot of imported files contain unwanted entities.
1136 * This method tries to clean up all known problems.
1137 * @param string str string to correct
1138 * @return string the corrected string
1140 public function cleaninput($str) {
1142 $html_code_list = array(
1143 "&#039;" => "'",
1144 "&#8217;" => "'",
1145 "&#8220;" => "\"",
1146 "&#8221;" => "\"",
1147 "&#8211;" => "-",
1148 "&#8212;" => "-",
1150 $str = strtr($str, $html_code_list);
1151 // Use core_text entities_to_utf8 function to convert only numerical entities.
1152 $str = core_text::entities_to_utf8($str, false);
1153 return $str;
1157 * Return the array moodle is expecting
1158 * for an HTML text. No processing is done on $text.
1159 * qformat classes that want to process $text
1160 * for instance to import external images files
1161 * and recode urls in $text must overwrite this method.
1162 * @param array $text some HTML text string
1163 * @return array with keys text, format and files.
1165 public function text_field($text) {
1166 return array(
1167 'text' => trim($text),
1168 'format' => FORMAT_HTML,
1169 'files' => array(),
1174 * Return the value of a node, given a path to the node
1175 * if it doesn't exist return the default value.
1176 * @param array xml data to read
1177 * @param array path path to node expressed as array
1178 * @param mixed default
1179 * @param bool istext process as text
1180 * @param string error if set value must exist, return false and issue message if not
1181 * @return mixed value
1183 public function getpath($xml, $path, $default, $istext=false, $error='') {
1184 foreach ($path as $index) {
1185 if (!isset($xml[$index])) {
1186 if (!empty($error)) {
1187 $this->error($error);
1188 return false;
1189 } else {
1190 return $default;
1194 $xml = $xml[$index];
1197 if ($istext) {
1198 if (!is_string($xml)) {
1199 $this->error(get_string('invalidxml', 'qformat_xml'));
1201 $xml = trim($xml);
1204 return $xml;