weekly release 2.7dev
[moodle.git] / mod / lesson / format.php
CommitLineData
472e5662 1<?php
0a4abb73
SH
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
5491947a 18/**
86342d63 19 * format.php - Default format class for file imports/exports. Doesn't do
5491947a 20 * everything on it's own -- it needs to be extended.
21 *
0a4abb73
SH
22 * Included by import.ph
23 *
9b24f68b 24 * @package mod_lesson
cc3dbaaa
PS
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0a4abb73
SH
27 **/
28
1e7f8ea2
PS
29defined('MOODLE_INTERNAL') || die();
30
0a4abb73
SH
31/**
32 * Given some question info and some data about the the answers
33 * this function parses, organises and saves the question
34 *
35 * This is only used when IMPORTING questions and is only called
36 * from format.php
37 * Lifted from mod/quiz/lib.php -
38 * 1. all reference to oldanswers removed
39 * 2. all reference to quiz_multichoice table removed
e231a3ff
TH
40 * 3. In shortanswer questions usecase is store in the qoption field
41 * 4. In numeric questions store the range as two answers
42 * 5. truefalse options are ignored
43 * 6. For multichoice questions with more than one answer the qoption field is true
0a4abb73
SH
44 *
45 * @param opject $question Contains question data like question, type and answers.
46 * @return object Returns $result->error or $result->notice.
5491947a 47 **/
0a4abb73
SH
48function lesson_save_question_options($question, $lesson) {
49 global $DB;
50
51 // These lines are required to ensure that all page types have
52 // been loaded for the following switch
53 if (!($lesson instanceof lesson)) {
54 $lesson = new lesson($lesson);
55 }
56 $manager = lesson_page_type_manager::get($lesson);
2f67a9b3 57
0a4abb73 58 $timenow = time();
39790bd8 59 $result = new stdClass();
0a4abb73
SH
60 switch ($question->qtype) {
61 case LESSON_PAGE_SHORTANSWER:
62
63 $answers = array();
64 $maxfraction = -1;
65
66 // Insert all the new answers
67 foreach ($question->answer as $key => $dataanswer) {
68 if ($dataanswer != "") {
69 $answer = new stdClass;
70 $answer->lessonid = $question->lessonid;
71 $answer->pageid = $question->id;
72 if ($question->fraction[$key] >=0.5) {
73 $answer->jumpto = LESSON_NEXTPAGE;
74 }
75 $answer->timecreated = $timenow;
76 $answer->grade = $question->fraction[$key] * 100;
77 $answer->answer = $dataanswer;
912ea4bc
RT
78 $answer->response = $question->feedback[$key]['text'];
79 $answer->responseformat = $question->feedback[$key]['format'];
0a4abb73
SH
80 $answer->id = $DB->insert_record("lesson_answers", $answer);
81 $answers[] = $answer->id;
82 if ($question->fraction[$key] > $maxfraction) {
83 $maxfraction = $question->fraction[$key];
84 }
85 }
86 }
87
88
89 /// Perform sanity checks on fractional grades
90 if ($maxfraction != 1) {
91 $maxfraction = $maxfraction * 100;
92 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
93 return $result;
94 }
95 break;
96
e231a3ff 97 case LESSON_PAGE_NUMERICAL: // Note similarities to shortanswer.
0a4abb73
SH
98
99 $answers = array();
100 $maxfraction = -1;
101
102
103 // for each answer store the pair of min and max values even if they are the same
104 foreach ($question->answer as $key => $dataanswer) {
105 if ($dataanswer != "") {
106 $answer = new stdClass;
107 $answer->lessonid = $question->lessonid;
108 $answer->pageid = $question->id;
109 $answer->jumpto = LESSON_NEXTPAGE;
110 $answer->timecreated = $timenow;
111 $answer->grade = $question->fraction[$key] * 100;
112 $min = $question->answer[$key] - $question->tolerance[$key];
113 $max = $question->answer[$key] + $question->tolerance[$key];
114 $answer->answer = $min.":".$max;
115 // $answer->answer = $question->min[$key].":".$question->max[$key]; original line for min/max
912ea4bc
RT
116 $answer->response = $question->feedback[$key]['text'];
117 $answer->responseformat = $question->feedback[$key]['format'];
0a4abb73
SH
118 $answer->id = $DB->insert_record("lesson_answers", $answer);
119
120 $answers[] = $answer->id;
121 if ($question->fraction[$key] > $maxfraction) {
122 $maxfraction = $question->fraction[$key];
123 }
124 }
125 }
126
127 /// Perform sanity checks on fractional grades
128 if ($maxfraction != 1) {
129 $maxfraction = $maxfraction * 100;
130 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
131 return $result;
132 }
133 break;
134
135
136 case LESSON_PAGE_TRUEFALSE:
137
138 // the truth
92701024 139 $answer = new stdClass();
0a4abb73
SH
140 $answer->lessonid = $question->lessonid;
141 $answer->pageid = $question->id;
142 $answer->timecreated = $timenow;
143 $answer->answer = get_string("true", "quiz");
912ea4bc 144 $answer->grade = $question->correctanswer * 100;
0a4abb73
SH
145 if ($answer->grade > 50 ) {
146 $answer->jumpto = LESSON_NEXTPAGE;
147 }
148 if (isset($question->feedbacktrue)) {
912ea4bc
RT
149 $answer->response = $question->feedbacktrue['text'];
150 $answer->responseformat = $question->feedbacktrue['format'];
0a4abb73 151 }
64a3ce8c 152 $DB->insert_record("lesson_answers", $answer);
0a4abb73
SH
153
154 // the lie
155 $answer = new stdClass;
156 $answer->lessonid = $question->lessonid;
157 $answer->pageid = $question->id;
158 $answer->timecreated = $timenow;
159 $answer->answer = get_string("false", "quiz");
912ea4bc 160 $answer->grade = (1 - (int)$question->correctanswer) * 100;
0a4abb73
SH
161 if ($answer->grade > 50 ) {
162 $answer->jumpto = LESSON_NEXTPAGE;
163 }
164 if (isset($question->feedbackfalse)) {
912ea4bc
RT
165 $answer->response = $question->feedbackfalse['text'];
166 $answer->responseformat = $question->feedbackfalse['format'];
0a4abb73 167 }
64a3ce8c 168 $DB->insert_record("lesson_answers", $answer);
0a4abb73
SH
169
170 break;
171
172 case LESSON_PAGE_MULTICHOICE:
173
174 $totalfraction = 0;
175 $maxfraction = -1;
176
177 $answers = array();
178
179 // Insert all the new answers
180 foreach ($question->answer as $key => $dataanswer) {
181 if ($dataanswer != "") {
182 $answer = new stdClass;
183 $answer->lessonid = $question->lessonid;
184 $answer->pageid = $question->id;
185 $answer->timecreated = $timenow;
186 $answer->grade = $question->fraction[$key] * 100;
187 // changed some defaults
188 /* Original Code
189 if ($answer->grade > 50 ) {
190 $answer->jumpto = LESSON_NEXTPAGE;
191 }
192 Replaced with: */
193 if ($answer->grade > 50 ) {
194 $answer->jumpto = LESSON_NEXTPAGE;
195 $answer->score = 1;
196 }
197 // end Replace
912ea4bc
RT
198 $answer->answer = $dataanswer['text'];
199 $answer->answerformat = $dataanswer['format'];
200 $answer->response = $question->feedback[$key]['text'];
201 $answer->responseformat = $question->feedback[$key]['format'];
0a4abb73
SH
202 $answer->id = $DB->insert_record("lesson_answers", $answer);
203 // for Sanity checks
204 if ($question->fraction[$key] > 0) {
205 $totalfraction += $question->fraction[$key];
206 }
207 if ($question->fraction[$key] > $maxfraction) {
208 $maxfraction = $question->fraction[$key];
209 }
210 }
211 }
212
213 /// Perform sanity checks on fractional grades
214 if ($question->single) {
215 if ($maxfraction != 1) {
216 $maxfraction = $maxfraction * 100;
217 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
218 return $result;
219 }
220 } else {
221 $totalfraction = round($totalfraction,2);
222 if ($totalfraction != 1) {
223 $totalfraction = $totalfraction * 100;
224 $result->notice = get_string("fractionsaddwrong", "quiz", $totalfraction);
225 return $result;
226 }
227 }
228 break;
229
230 case LESSON_PAGE_MATCHING:
231
232 $subquestions = array();
233
234 $defaultanswer = new stdClass;
235 $defaultanswer->lessonid = $question->lessonid;
236 $defaultanswer->pageid = $question->id;
237 $defaultanswer->timecreated = $timenow;
238 $defaultanswer->grade = 0;
239
240 // The first answer should always be the correct answer
241 $correctanswer = clone($defaultanswer);
242 $correctanswer->answer = get_string('thatsthecorrectanswer', 'lesson');
b09ac20b 243 $correctanswer->jumpto = LESSON_NEXTPAGE;
0a4abb73
SH
244 $DB->insert_record("lesson_answers", $correctanswer);
245
246 // The second answer should always be the wrong answer
247 $wronganswer = clone($defaultanswer);
248 $wronganswer->answer = get_string('thatsthewronganswer', 'lesson');
249 $DB->insert_record("lesson_answers", $wronganswer);
250
251 $i = 0;
252 // Insert all the new question+answer pairs
253 foreach ($question->subquestions as $key => $questiontext) {
254 $answertext = $question->subanswers[$key];
255 if (!empty($questiontext) and !empty($answertext)) {
256 $answer = clone($defaultanswer);
912ea4bc
RT
257 $answer->answer = $questiontext['text'];
258 $answer->answerformat = $questiontext['format'];
0a4abb73
SH
259 $answer->response = $answertext;
260 if ($i == 0) {
261 // first answer contains the correct answer jump
262 $answer->jumpto = LESSON_NEXTPAGE;
263 }
64a3ce8c 264 $subquestions[] = $DB->insert_record("lesson_answers", $answer);
0a4abb73
SH
265 $i++;
266 }
267 }
268
269 if (count($subquestions) < 3) {
270 $result->notice = get_string("notenoughsubquestions", "quiz");
271 return $result;
272 }
273 break;
274 default:
275 $result->error = "Unsupported question type ($question->qtype)!";
276 return $result;
277 }
278 return true;
279}
394c97c8 280
394c97c8 281
90455bb3 282class qformat_default {
394c97c8 283
284 var $displayerrors = true;
ecea65ca 285 var $category = null;
394c97c8 286 var $questionids = array();
efbe07b0 287 protected $importcontext = null;
e231a3ff
TH
288 var $qtypeconvert = array('numerical' => LESSON_PAGE_NUMERICAL,
289 'multichoice' => LESSON_PAGE_MULTICHOICE,
290 'truefalse' => LESSON_PAGE_TRUEFALSE,
291 'shortanswer' => LESSON_PAGE_SHORTANSWER,
292 'match' => LESSON_PAGE_MATCHING
90455bb3 293 );
394c97c8 294
0a4abb73
SH
295 // Importing functions
296 function provide_import() {
297 return false;
298 }
394c97c8 299
efbe07b0
JMV
300 function set_importcontext($context) {
301 $this->importcontext = $context;
302 }
303
394c97c8 304 function importpreprocess() {
0a4abb73 305 // Does any pre-processing that may be desired
394c97c8 306 return true;
307 }
308
309 function importprocess($filename, $lesson, $pageid) {
d68ccdba 310 global $DB, $OUTPUT;
86342d63 311
394c97c8 312 /// Processes a given file. There's probably little need to change this
313 $timenow = time();
314
315 if (! $lines = $this->readdata($filename)) {
d68ccdba 316 echo $OUTPUT->notification("File could not be read, or was empty");
394c97c8 317 return false;
318 }
319
320 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
d68ccdba 321 echo $OUTPUT->notification("There are no questions in this file!");
394c97c8 322 return false;
323 }
86342d63 324
912ea4bc
RT
325 //Avoid category as question type
326 echo $OUTPUT->notification(get_string('importcount', 'lesson',
327 $this->count_questions($questions)), 'notifysuccess');
394c97c8 328
329 $count = 0;
eebc821c
RW
330 $addquestionontop = false;
331 if ($pageid == 0) {
332 $addquestionontop = true;
333 $updatelessonpage = $DB->get_record('lesson_pages', array('lessonid' => $lesson->id, 'prevpageid' => 0));
334 } else {
84c5f641 335 $updatelessonpage = $DB->get_record('lesson_pages', array('lessonid' => $lesson->id, 'id' => $pageid));
eebc821c 336 }
394c97c8 337
0a4abb73
SH
338 $unsupportedquestions = 0;
339
394c97c8 340 foreach ($questions as $question) { // Process and store each question
341 switch ($question->qtype) {
912ea4bc
RT
342 //TODO: Bad way to bypass category in data... Quickfix for MDL-27964
343 case 'category':
344 break;
394c97c8 345 // the good ones
e231a3ff
TH
346 case 'shortanswer' :
347 case 'numerical' :
348 case 'truefalse' :
349 case 'multichoice' :
350 case 'match' :
394c97c8 351 $count++;
352
912ea4bc
RT
353 //Show nice formated question in one line.
354 echo "<hr><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
355
f7ffb898 356 $newpage = new stdClass;
394c97c8 357 $newpage->lessonid = $lesson->id;
90455bb3 358 $newpage->qtype = $this->qtypeconvert[$question->qtype];
394c97c8 359 switch ($question->qtype) {
e231a3ff 360 case 'shortanswer' :
90455bb3 361 if (isset($question->usecase)) {
362 $newpage->qoption = $question->usecase;
363 }
394c97c8 364 break;
e231a3ff 365 case 'multichoice' :
394c97c8 366 if (isset($question->single)) {
367 $newpage->qoption = !$question->single;
368 }
369 break;
370 }
371 $newpage->timecreated = $timenow;
372 if ($question->name != $question->questiontext) {
373 $newpage->title = $question->name;
374 } else {
375 $newpage->title = "Page $count";
376 }
377 $newpage->contents = $question->questiontext;
1c3b1f7a
EL
378 $newpage->contentsformat = isset($question->questionformat) ? $question->questionformat : FORMAT_HTML;
379
394c97c8 380 // set up page links
381 if ($pageid) {
382 // the new page follows on from this page
646fc290 383 if (!$page = $DB->get_record("lesson_pages", array("id" => $pageid))) {
771dc7b2 384 print_error('invalidpageid', 'lesson');
394c97c8 385 }
386 $newpage->prevpageid = $pageid;
387 $newpage->nextpageid = $page->nextpageid;
388 // insert the page and reset $pageid
6d40f12e 389 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 390 // update the linked list
6d40f12e 391 $DB->set_field("lesson_pages", "nextpageid", $newpageid, array("id" => $pageid));
394c97c8 392 } else {
393 // new page is the first page
394 // get the existing (first) page (if any)
646fc290 395 $params = array ("lessonid" => $lesson->id, "prevpageid" => 0);
396 if (!$page = $DB->get_record_select("lesson_pages", "lessonid = :lessonid AND prevpageid = :prevpageid", $params)) {
394c97c8 397 // there are no existing pages
398 $newpage->prevpageid = 0; // this is a first page
399 $newpage->nextpageid = 0; // this is the only page
646fc290 400 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 401 } else {
402 // there are existing pages put this at the start
403 $newpage->prevpageid = 0; // this is a first page
404 $newpage->nextpageid = $page->id;
646fc290 405 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 406 // update the linked list
6d40f12e 407 $DB->set_field("lesson_pages", "prevpageid", $newpageid, array("id" => $page->id));
394c97c8 408 }
409 }
eebc821c 410
394c97c8 411 // reset $pageid and put the page ID in $question, used in save_question_option()
412 $pageid = $newpageid;
413 $question->id = $newpageid;
86342d63 414
394c97c8 415 $this->questionids[] = $question->id;
416
efbe07b0
JMV
417 // Import images in question text.
418 if (isset($question->questiontextitemid)) {
419 $questiontext = file_save_draft_area_files($question->questiontextitemid,
420 $this->importcontext->id, 'mod_lesson', 'page_contents', $newpageid,
421 null , $question->questiontext);
422 // Update content with recoded urls.
423 $DB->set_field("lesson_pages", "contents", $questiontext, array("id" => $newpageid));
424 }
425
394c97c8 426 // Now to save all the answers and type-specific options
427
428 $question->lessonid = $lesson->id; // needed for foreign key
90455bb3 429 $question->qtype = $this->qtypeconvert[$question->qtype];
0a4abb73 430 $result = lesson_save_question_options($question, $lesson);
394c97c8 431
432 if (!empty($result->error)) {
d68ccdba 433 echo $OUTPUT->notification($result->error);
394c97c8 434 return false;
435 }
436
437 if (!empty($result->notice)) {
d68ccdba 438 echo $OUTPUT->notification($result->notice);
394c97c8 439 return true;
440 }
441 break;
442 // the Bad ones
443 default :
0a4abb73
SH
444 $unsupportedquestions++;
445 break;
394c97c8 446 }
eebc821c 447 }
84c5f641
DW
448 // Update the prev links if there were existing pages.
449 if (!empty($updatelessonpage)) {
450 if ($addquestionontop) {
451 $DB->set_field("lesson_pages", "prevpageid", $pageid, array("id" => $updatelessonpage->id));
452 } else {
453 $DB->set_field("lesson_pages", "prevpageid", $pageid, array("id" => $updatelessonpage->nextpageid));
454 }
394c97c8 455 }
0a4abb73
SH
456 if ($unsupportedquestions) {
457 echo $OUTPUT->notification(get_string('unknownqtypesnotimported', 'lesson', $unsupportedquestions));
458 }
394c97c8 459 return true;
460 }
461
912ea4bc
RT
462 /**
463 * Count all non-category questions in the questions array.
464 *
465 * @param array questions An array of question objects.
466 * @return int The count.
467 *
468 */
469 protected function count_questions($questions) {
470 $count = 0;
471 if (!is_array($questions)) {
472 return $count;
473 }
474 foreach ($questions as $question) {
475 if (!is_object($question) || !isset($question->qtype) ||
476 ($question->qtype == 'category')) {
477 continue;
478 }
479 $count++;
480 }
481 return $count;
482 }
394c97c8 483
484 function readdata($filename) {
485 /// Returns complete file with an array, one item per line
486
487 if (is_readable($filename)) {
488 $filearray = file($filename);
489
490 /// Check for Macintosh OS line returns (ie file on one line), and fix
6dbcacee 491 if (preg_match("/\r/", $filearray[0]) AND !preg_match("/\n/", $filearray[0])) {
394c97c8 492 return explode("\r", $filearray[0]);
493 } else {
494 return $filearray;
495 }
496 }
497 return false;
498 }
499
ba15c346 500 protected function readquestions($lines) {
86342d63
PS
501 /// Parses an array of lines into an array of questions,
502 /// where each item is a question object as defined by
503 /// readquestion(). Questions are defined as anything
394c97c8 504 /// between blank lines.
86342d63 505
394c97c8 506 $questions = array();
507 $currentquestion = array();
508
509 foreach ($lines as $line) {
510 $line = trim($line);
511 if (empty($line)) {
512 if (!empty($currentquestion)) {
513 if ($question = $this->readquestion($currentquestion)) {
514 $questions[] = $question;
515 }
516 $currentquestion = array();
517 }
518 } else {
519 $currentquestion[] = $line;
520 }
521 }
522
523 if (!empty($currentquestion)) { // There may be a final question
524 if ($question = $this->readquestion($currentquestion)) {
525 $questions[] = $question;
526 }
527 }
528
529 return $questions;
530 }
531
532
e8eb2b00 533 protected function readquestion($lines) {
86342d63
PS
534 /// Given an array of lines known to define a question in
535 /// this format, this function converts it into a question
394c97c8 536 /// object suitable for processing and insertion into Moodle.
537
538 echo "<p>This flash question format has not yet been completed!</p>";
539
ecea65ca 540 return null;
394c97c8 541 }
542
cacb8fa0
TH
543 /**
544 * Construct a reasonable default question name, based on the start of the question text.
545 * @param string $questiontext the question text.
546 * @param string $default default question name to use if the constructed one comes out blank.
547 * @return string a reasonable question name.
548 */
549 public function create_default_question_name($questiontext, $default) {
550 $name = $this->clean_question_name(shorten_text($questiontext, 80));
551 if ($name) {
552 return $name;
553 } else {
554 return $default;
555 }
556 }
557
558 /**
559 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
560 * @param string $name the raw question name.
561 * @return string a safe question name.
562 */
563 public function clean_question_name($name) {
564 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
565 $name = trim($name);
566 $trimlength = 251;
2f1e464a 567 while (core_text::strlen($name) > 255 && $trimlength > 0) {
cacb8fa0
TH
568 $name = shorten_text($name, $trimlength);
569 $trimlength -= 10;
570 }
571 return $name;
572 }
573
90455bb3 574 function defaultquestion() {
575 // returns an "empty" question
576 // Somewhere to specify question parameters that are not handled
577 // by import but are required db fields.
86342d63 578 // This should not be overridden.
508fe4d8 579 global $CFG;
580
90455bb3 581 $question = new stdClass();
0a4abb73 582 $question->shuffleanswers = get_config('quiz', 'shuffleanswers');
912ea4bc 583 $question->defaultmark = 1;
508fe4d8 584 $question->image = "";
585 $question->usecase = 0;
586 $question->multiplier = array();
587 $question->generalfeedback = '';
588 $question->correctfeedback = '';
589 $question->partiallycorrectfeedback = '';
590 $question->incorrectfeedback = '';
591 $question->answernumbering = 'abc';
592 $question->penalty = 0.1;
593 $question->length = 1;
90455bb3 594 $question->qoption = 0;
595 $question->layout = 1;
86342d63 596
912ea4bc
RT
597 // this option in case the questiontypes class wants
598 // to know where the data came from
599 $question->export_process = true;
600 $question->import_process = true;
601
90455bb3 602 return $question;
603 }
394c97c8 604
605 function importpostprocess() {
0a4abb73
SH
606 /// Does any post-processing that may be desired
607 /// Argument is a simple array of question ids that
608 /// have just been added.
394c97c8 609 return true;
610 }
611
912ea4bc
RT
612 /**
613 * Convert the question text to plain text, so it can safely be displayed
614 * during import to let the user see roughly what is going on.
615 */
616 protected function format_question_text($question) {
617 $formatoptions = new stdClass();
618 $formatoptions->noclean = true;
efbe07b0
JMV
619 // The html_to_text call strips out all URLs, but format_text complains
620 // if it finds @@PLUGINFILE@@ tokens. So, we need to replace
621 // @@PLUGINFILE@@ with a real URL, but it doesn't matter what.
622 // We use http://example.com/.
623 $text = str_replace('@@PLUGINFILE@@/', 'http://example.com/', $question->questiontext);
624 return html_to_text(format_text($text,
912ea4bc
RT
625 $question->questiontextformat, $formatoptions), 0, false);
626 }
bba5e716
TH
627
628 /**
629 * Since the lesson module tries to re-use the question bank import classes in
630 * a crazy way, this is necessary to stop things breaking.
631 */
632 protected function add_blank_combined_feedback($question) {
633 return $question;
634 }
394c97c8 635}
636
86342d63 637
bba5e716
TH
638/**
639 * Since the lesson module tries to re-use the question bank import classes in
640 * a crazy way, this is necessary to stop things breaking. This should be exactly
641 * the same as the class defined in question/format.php.
642 */
643class qformat_based_on_xml extends qformat_default {
644 /**
645 * A lot of imported files contain unwanted entities.
646 * This method tries to clean up all known problems.
647 * @param string str string to correct
648 * @return string the corrected string
649 */
650 public function cleaninput($str) {
651
652 $html_code_list = array(
653 "&#039;" => "'",
654 "&#8217;" => "'",
655 "&#8220;" => "\"",
656 "&#8221;" => "\"",
657 "&#8211;" => "-",
658 "&#8212;" => "-",
659 );
660 $str = strtr($str, $html_code_list);
2f1e464a
PS
661 // Use core_text entities_to_utf8 function to convert only numerical entities.
662 $str = core_text::entities_to_utf8($str, false);
bba5e716
TH
663 return $str;
664 }
665
666 /**
667 * Return the array moodle is expecting
668 * for an HTML text. No processing is done on $text.
669 * qformat classes that want to process $text
670 * for instance to import external images files
671 * and recode urls in $text must overwrite this method.
672 * @param array $text some HTML text string
673 * @return array with keys text, format and files.
674 */
675 public function text_field($text) {
676 return array(
677 'text' => trim($text),
678 'format' => FORMAT_HTML,
679 'files' => array(),
680 );
681 }
682
683 /**
684 * Return the value of a node, given a path to the node
685 * if it doesn't exist return the default value.
686 * @param array xml data to read
687 * @param array path path to node expressed as array
688 * @param mixed default
689 * @param bool istext process as text
690 * @param string error if set value must exist, return false and issue message if not
691 * @return mixed value
692 */
693 public function getpath($xml, $path, $default, $istext=false, $error='') {
694 foreach ($path as $index) {
695 if (!isset($xml[$index])) {
696 if (!empty($error)) {
697 $this->error($error);
698 return false;
699 } else {
700 return $default;
701 }
702 }
703
704 $xml = $xml[$index];
705 }
706
707 if ($istext) {
708 if (!is_string($xml)) {
709 $this->error(get_string('invalidxml', 'qformat_xml'));
710 }
711 $xml = trim($xml);
712 }
713
714 return $xml;
715 }
716}