PageRenderTime 51ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/question/format.php

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