weekly on-sync 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;
304 default:
305 $result->error = "Unsupported question type ($question->qtype)!";
306 return $result;
307 }
308 return true;
309}
394c97c8 310
394c97c8 311
90455bb3 312class qformat_default {
394c97c8 313
314 var $displayerrors = true;
ecea65ca 315 var $category = null;
394c97c8 316 var $questionids = array();
efbe07b0 317 protected $importcontext = null;
e231a3ff
TH
318 var $qtypeconvert = array('numerical' => LESSON_PAGE_NUMERICAL,
319 'multichoice' => LESSON_PAGE_MULTICHOICE,
320 'truefalse' => LESSON_PAGE_TRUEFALSE,
321 'shortanswer' => LESSON_PAGE_SHORTANSWER,
322 'match' => LESSON_PAGE_MATCHING
90455bb3 323 );
394c97c8 324
0a4abb73
SH
325 // Importing functions
326 function provide_import() {
327 return false;
328 }
394c97c8 329
efbe07b0
JMV
330 function set_importcontext($context) {
331 $this->importcontext = $context;
332 }
333
f88d75e5
JMV
334 /**
335 * Handle parsing error
336 *
337 * @param string $message information about error
338 * @param string $text imported text that triggered the error
339 * @param string $questionname imported question name
340 */
341 protected function error($message, $text='', $questionname='') {
342 $importerrorquestion = get_string('importerrorquestion', 'question');
343
344 echo "<div class=\"importerror\">\n";
345 echo "<strong>$importerrorquestion $questionname</strong>";
346 if (!empty($text)) {
347 $text = s($text);
348 echo "<blockquote>$text</blockquote>\n";
349 }
350 echo "<strong>$message</strong>\n";
351 echo "</div>";
352 }
353
a174a0ac
JMV
354 /**
355 * Import for questiontype plugins
356 * @param mixed $data The segment of data containing the question
357 * @param object $question processed (so far) by standard import code if appropriate
358 * @param object $extra mixed any additional format specific data that may be passed by the format
359 * @param string $qtypehint hint about a question type from format
360 * @return object question object suitable for save_options() or false if cannot handle
361 */
362 public function try_importing_using_qtypes($data, $question = null, $extra = null,
363 $qtypehint = '') {
364
365 return false;
366 }
367
394c97c8 368 function importpreprocess() {
0a4abb73 369 // Does any pre-processing that may be desired
394c97c8 370 return true;
371 }
372
373 function importprocess($filename, $lesson, $pageid) {
d68ccdba 374 global $DB, $OUTPUT;
86342d63 375
394c97c8 376 /// Processes a given file. There's probably little need to change this
377 $timenow = time();
378
379 if (! $lines = $this->readdata($filename)) {
d68ccdba 380 echo $OUTPUT->notification("File could not be read, or was empty");
394c97c8 381 return false;
382 }
383
384 if (! $questions = $this->readquestions($lines)) { // Extract all the questions
d68ccdba 385 echo $OUTPUT->notification("There are no questions in this file!");
394c97c8 386 return false;
387 }
86342d63 388
912ea4bc
RT
389 //Avoid category as question type
390 echo $OUTPUT->notification(get_string('importcount', 'lesson',
391 $this->count_questions($questions)), 'notifysuccess');
394c97c8 392
393 $count = 0;
eebc821c
RW
394 $addquestionontop = false;
395 if ($pageid == 0) {
396 $addquestionontop = true;
397 $updatelessonpage = $DB->get_record('lesson_pages', array('lessonid' => $lesson->id, 'prevpageid' => 0));
398 } else {
84c5f641 399 $updatelessonpage = $DB->get_record('lesson_pages', array('lessonid' => $lesson->id, 'id' => $pageid));
eebc821c 400 }
394c97c8 401
0a4abb73
SH
402 $unsupportedquestions = 0;
403
394c97c8 404 foreach ($questions as $question) { // Process and store each question
405 switch ($question->qtype) {
912ea4bc
RT
406 //TODO: Bad way to bypass category in data... Quickfix for MDL-27964
407 case 'category':
408 break;
394c97c8 409 // the good ones
e231a3ff
TH
410 case 'shortanswer' :
411 case 'numerical' :
412 case 'truefalse' :
413 case 'multichoice' :
414 case 'match' :
394c97c8 415 $count++;
416
912ea4bc
RT
417 //Show nice formated question in one line.
418 echo "<hr><p><b>$count</b>. ".$this->format_question_text($question)."</p>";
419
f7ffb898 420 $newpage = new stdClass;
394c97c8 421 $newpage->lessonid = $lesson->id;
90455bb3 422 $newpage->qtype = $this->qtypeconvert[$question->qtype];
394c97c8 423 switch ($question->qtype) {
e231a3ff 424 case 'shortanswer' :
90455bb3 425 if (isset($question->usecase)) {
426 $newpage->qoption = $question->usecase;
427 }
394c97c8 428 break;
e231a3ff 429 case 'multichoice' :
394c97c8 430 if (isset($question->single)) {
431 $newpage->qoption = !$question->single;
432 }
433 break;
434 }
435 $newpage->timecreated = $timenow;
436 if ($question->name != $question->questiontext) {
437 $newpage->title = $question->name;
438 } else {
439 $newpage->title = "Page $count";
440 }
441 $newpage->contents = $question->questiontext;
1c3b1f7a
EL
442 $newpage->contentsformat = isset($question->questionformat) ? $question->questionformat : FORMAT_HTML;
443
394c97c8 444 // set up page links
445 if ($pageid) {
446 // the new page follows on from this page
646fc290 447 if (!$page = $DB->get_record("lesson_pages", array("id" => $pageid))) {
771dc7b2 448 print_error('invalidpageid', 'lesson');
394c97c8 449 }
450 $newpage->prevpageid = $pageid;
451 $newpage->nextpageid = $page->nextpageid;
452 // insert the page and reset $pageid
6d40f12e 453 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 454 // update the linked list
6d40f12e 455 $DB->set_field("lesson_pages", "nextpageid", $newpageid, array("id" => $pageid));
394c97c8 456 } else {
457 // new page is the first page
458 // get the existing (first) page (if any)
646fc290 459 $params = array ("lessonid" => $lesson->id, "prevpageid" => 0);
460 if (!$page = $DB->get_record_select("lesson_pages", "lessonid = :lessonid AND prevpageid = :prevpageid", $params)) {
394c97c8 461 // there are no existing pages
462 $newpage->prevpageid = 0; // this is a first page
463 $newpage->nextpageid = 0; // this is the only page
646fc290 464 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 465 } else {
466 // there are existing pages put this at the start
467 $newpage->prevpageid = 0; // this is a first page
468 $newpage->nextpageid = $page->id;
646fc290 469 $newpageid = $DB->insert_record("lesson_pages", $newpage);
394c97c8 470 // update the linked list
6d40f12e 471 $DB->set_field("lesson_pages", "prevpageid", $newpageid, array("id" => $page->id));
394c97c8 472 }
473 }
eebc821c 474
394c97c8 475 // reset $pageid and put the page ID in $question, used in save_question_option()
476 $pageid = $newpageid;
477 $question->id = $newpageid;
86342d63 478
394c97c8 479 $this->questionids[] = $question->id;
480
efbe07b0
JMV
481 // Import images in question text.
482 if (isset($question->questiontextitemid)) {
483 $questiontext = file_save_draft_area_files($question->questiontextitemid,
484 $this->importcontext->id, 'mod_lesson', 'page_contents', $newpageid,
485 null , $question->questiontext);
486 // Update content with recoded urls.
487 $DB->set_field("lesson_pages", "contents", $questiontext, array("id" => $newpageid));
488 }
489
394c97c8 490 // Now to save all the answers and type-specific options
491
492 $question->lessonid = $lesson->id; // needed for foreign key
90455bb3 493 $question->qtype = $this->qtypeconvert[$question->qtype];
ce3cfc8f 494 $result = lesson_save_question_options($question, $lesson, $this->importcontext->id);
394c97c8 495
496 if (!empty($result->error)) {
d68ccdba 497 echo $OUTPUT->notification($result->error);
394c97c8 498 return false;
499 }
500
501 if (!empty($result->notice)) {
d68ccdba 502 echo $OUTPUT->notification($result->notice);
394c97c8 503 return true;
504 }
505 break;
506 // the Bad ones
507 default :
0a4abb73
SH
508 $unsupportedquestions++;
509 break;
394c97c8 510 }
eebc821c 511 }
84c5f641
DW
512 // Update the prev links if there were existing pages.
513 if (!empty($updatelessonpage)) {
514 if ($addquestionontop) {
515 $DB->set_field("lesson_pages", "prevpageid", $pageid, array("id" => $updatelessonpage->id));
516 } else {
517 $DB->set_field("lesson_pages", "prevpageid", $pageid, array("id" => $updatelessonpage->nextpageid));
518 }
394c97c8 519 }
0a4abb73
SH
520 if ($unsupportedquestions) {
521 echo $OUTPUT->notification(get_string('unknownqtypesnotimported', 'lesson', $unsupportedquestions));
522 }
394c97c8 523 return true;
524 }
525
912ea4bc
RT
526 /**
527 * Count all non-category questions in the questions array.
528 *
529 * @param array questions An array of question objects.
530 * @return int The count.
531 *
532 */
533 protected function count_questions($questions) {
534 $count = 0;
535 if (!is_array($questions)) {
536 return $count;
537 }
538 foreach ($questions as $question) {
539 if (!is_object($question) || !isset($question->qtype) ||
540 ($question->qtype == 'category')) {
541 continue;
542 }
543 $count++;
544 }
545 return $count;
546 }
394c97c8 547
548 function readdata($filename) {
549 /// Returns complete file with an array, one item per line
550
551 if (is_readable($filename)) {
552 $filearray = file($filename);
553
554 /// Check for Macintosh OS line returns (ie file on one line), and fix
6dbcacee 555 if (preg_match("/\r/", $filearray[0]) AND !preg_match("/\n/", $filearray[0])) {
394c97c8 556 return explode("\r", $filearray[0]);
557 } else {
558 return $filearray;
559 }
560 }
561 return false;
562 }
563
ba15c346 564 protected function readquestions($lines) {
86342d63
PS
565 /// Parses an array of lines into an array of questions,
566 /// where each item is a question object as defined by
567 /// readquestion(). Questions are defined as anything
394c97c8 568 /// between blank lines.
86342d63 569
394c97c8 570 $questions = array();
571 $currentquestion = array();
572
573 foreach ($lines as $line) {
574 $line = trim($line);
575 if (empty($line)) {
576 if (!empty($currentquestion)) {
577 if ($question = $this->readquestion($currentquestion)) {
578 $questions[] = $question;
579 }
580 $currentquestion = array();
581 }
582 } else {
583 $currentquestion[] = $line;
584 }
585 }
586
587 if (!empty($currentquestion)) { // There may be a final question
588 if ($question = $this->readquestion($currentquestion)) {
589 $questions[] = $question;
590 }
591 }
592
593 return $questions;
594 }
595
596
e8eb2b00 597 protected function readquestion($lines) {
86342d63
PS
598 /// Given an array of lines known to define a question in
599 /// this format, this function converts it into a question
394c97c8 600 /// object suitable for processing and insertion into Moodle.
601
762ee139
JMV
602 // We should never get there unless the qformat plugin is broken.
603 throw new coding_exception('Question format plugin is missing important code: readquestion.');
394c97c8 604
ecea65ca 605 return null;
394c97c8 606 }
607
cacb8fa0
TH
608 /**
609 * Construct a reasonable default question name, based on the start of the question text.
610 * @param string $questiontext the question text.
611 * @param string $default default question name to use if the constructed one comes out blank.
612 * @return string a reasonable question name.
613 */
614 public function create_default_question_name($questiontext, $default) {
615 $name = $this->clean_question_name(shorten_text($questiontext, 80));
616 if ($name) {
617 return $name;
618 } else {
619 return $default;
620 }
621 }
622
623 /**
624 * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
625 * @param string $name the raw question name.
626 * @return string a safe question name.
627 */
628 public function clean_question_name($name) {
629 $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
630 $name = trim($name);
631 $trimlength = 251;
2f1e464a 632 while (core_text::strlen($name) > 255 && $trimlength > 0) {
cacb8fa0
TH
633 $name = shorten_text($name, $trimlength);
634 $trimlength -= 10;
635 }
636 return $name;
637 }
638
61974973
JMV
639 /**
640 * return an "empty" question
641 * Somewhere to specify question parameters that are not handled
642 * by import but are required db fields.
643 * This should not be overridden.
644 * @return object default question
645 */
646 protected function defaultquestion() {
508fe4d8 647 global $CFG;
61974973
JMV
648 static $defaultshuffleanswers = null;
649 if (is_null($defaultshuffleanswers)) {
650 $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
651 }
508fe4d8 652
90455bb3 653 $question = new stdClass();
61974973 654 $question->shuffleanswers = $defaultshuffleanswers;
912ea4bc 655 $question->defaultmark = 1;
508fe4d8 656 $question->image = "";
657 $question->usecase = 0;
658 $question->multiplier = array();
61974973 659 $question->questiontextformat = FORMAT_MOODLE;
508fe4d8 660 $question->generalfeedback = '';
61974973 661 $question->generalfeedbackformat = FORMAT_MOODLE;
508fe4d8 662 $question->correctfeedback = '';
663 $question->partiallycorrectfeedback = '';
664 $question->incorrectfeedback = '';
665 $question->answernumbering = 'abc';
61974973 666 $question->penalty = 0.3333333;
508fe4d8 667 $question->length = 1;
90455bb3 668 $question->qoption = 0;
669 $question->layout = 1;
86342d63 670
912ea4bc
RT
671 // this option in case the questiontypes class wants
672 // to know where the data came from
673 $question->export_process = true;
674 $question->import_process = true;
675
90455bb3 676 return $question;
677 }
394c97c8 678
679 function importpostprocess() {
0a4abb73
SH
680 /// Does any post-processing that may be desired
681 /// Argument is a simple array of question ids that
682 /// have just been added.
394c97c8 683 return true;
684 }
685
912ea4bc
RT
686 /**
687 * Convert the question text to plain text, so it can safely be displayed
688 * during import to let the user see roughly what is going on.
689 */
690 protected function format_question_text($question) {
691 $formatoptions = new stdClass();
692 $formatoptions->noclean = true;
efbe07b0
JMV
693 // The html_to_text call strips out all URLs, but format_text complains
694 // if it finds @@PLUGINFILE@@ tokens. So, we need to replace
695 // @@PLUGINFILE@@ with a real URL, but it doesn't matter what.
696 // We use http://example.com/.
697 $text = str_replace('@@PLUGINFILE@@/', 'http://example.com/', $question->questiontext);
698 return html_to_text(format_text($text,
912ea4bc
RT
699 $question->questiontextformat, $formatoptions), 0, false);
700 }
bba5e716
TH
701
702 /**
703 * Since the lesson module tries to re-use the question bank import classes in
704 * a crazy way, this is necessary to stop things breaking.
705 */
706 protected function add_blank_combined_feedback($question) {
707 return $question;
708 }
394c97c8 709}
710
86342d63 711
bba5e716
TH
712/**
713 * Since the lesson module tries to re-use the question bank import classes in
714 * a crazy way, this is necessary to stop things breaking. This should be exactly
715 * the same as the class defined in question/format.php.
716 */
717class qformat_based_on_xml extends qformat_default {
718 /**
719 * A lot of imported files contain unwanted entities.
720 * This method tries to clean up all known problems.
721 * @param string str string to correct
722 * @return string the corrected string
723 */
724 public function cleaninput($str) {
725
726 $html_code_list = array(
727 "&#039;" => "'",
728 "&#8217;" => "'",
729 "&#8220;" => "\"",
730 "&#8221;" => "\"",
731 "&#8211;" => "-",
732 "&#8212;" => "-",
733 );
734 $str = strtr($str, $html_code_list);
2f1e464a
PS
735 // Use core_text entities_to_utf8 function to convert only numerical entities.
736 $str = core_text::entities_to_utf8($str, false);
bba5e716
TH
737 return $str;
738 }
739
740 /**
741 * Return the array moodle is expecting
742 * for an HTML text. No processing is done on $text.
743 * qformat classes that want to process $text
744 * for instance to import external images files
745 * and recode urls in $text must overwrite this method.
746 * @param array $text some HTML text string
747 * @return array with keys text, format and files.
748 */
749 public function text_field($text) {
750 return array(
751 'text' => trim($text),
752 'format' => FORMAT_HTML,
753 'files' => array(),
754 );
755 }
756
757 /**
758 * Return the value of a node, given a path to the node
759 * if it doesn't exist return the default value.
760 * @param array xml data to read
761 * @param array path path to node expressed as array
762 * @param mixed default
763 * @param bool istext process as text
764 * @param string error if set value must exist, return false and issue message if not
765 * @return mixed value
766 */
767 public function getpath($xml, $path, $default, $istext=false, $error='') {
768 foreach ($path as $index) {
769 if (!isset($xml[$index])) {
770 if (!empty($error)) {
771 $this->error($error);
772 return false;
773 } else {
774 return $default;
775 }
776 }
777
778 $xml = $xml[$index];
779 }
780
781 if ($istext) {
782 if (!is_string($xml)) {
783 $this->error(get_string('invalidxml', 'qformat_xml'));
784 }
785 $xml = trim($xml);
786 }
787
788 return $xml;
789 }
790}