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