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