View source
<?php
require_once "{$CFG->dirroot}/question/format/qti2/qt_common.php";
define('CLOZE_TRAILING_TEXT_ID', 9999999);
class qformat_qti2 extends qformat_default {
var $lang;
function provide_export() {
return true;
}
function indent_xhtml($source, $indenter = ' ') {
$source = str_replace("\n", '', $source);
$source = str_replace("\r", '', $source);
$source = str_replace("\t", '', $source);
$source = ereg_replace(">( )*", ">", $source);
$source = ereg_replace("( )*<", "<", $source);
$level = 0;
$source_len = strlen($source);
$pt = 0;
while ($pt < $source_len) {
if ($source[$pt] === '<') {
$started_at = $pt;
$tag_level = 1;
if ($source[$pt + 1] === '/') {
$tag_level = -1;
}
if ($source[$pt + 1] === '!') {
$tag_level = 0;
}
while ($source[$pt] !== '>') {
$pt++;
}
if ($source[$pt - 1] === '/') {
$tag_level = 0;
}
$tag_lenght = $pt + 1 - $started_at;
if ($tag_level === -1) {
$level--;
}
$array[] = str_repeat($indenter, $level) . substr($source, $started_at, $tag_lenght);
if ($tag_level === 1) {
$level++;
}
}
if ($pt + 1 < $source_len) {
if ($source[$pt + 1] !== '<') {
$started_at = $pt + 1;
while ($source[$pt] !== '<' && $pt < $source_len) {
$pt++;
}
if ($source[$pt] === '<') {
$tag_lenght = $pt - $started_at;
$array[] = str_repeat($indenter, $level) . substr($source, $started_at, $tag_lenght);
}
}
else {
$pt++;
}
}
else {
break;
}
}
$source = implode($array, "\n");
return $source;
}
function importpreprocess() {
global $CFG;
error("Sorry, importing this format is not yet implemented!", "{$CFG->wwwroot}/mod/quiz/import.php?category={$category->id}");
}
function exportpreprocess() {
global $CFG;
require_once "{$CFG->libdir}/smarty/Smarty.class.php";
$lang = current_language();
$this->lang = $lang;
return parent::exportpreprocess();
}
function export_file_extension() {
return ".zip";
}
function get_qtype($type_id) {
switch ($type_id) {
case TRUEFALSE:
$name = 'truefalse';
break;
case MULTICHOICE:
$name = 'multichoice';
break;
case SHORTANSWER:
$name = 'shortanswer';
break;
case NUMERICAL:
$name = 'numerical';
break;
case MATCH:
$name = 'matching';
break;
case DESCRIPTION:
$name = 'description';
break;
case MULTIANSWER:
$name = 'multianswer';
break;
default:
$name = 'Unknown';
}
return $name;
}
function writetext($raw) {
$raw = strip_tags($raw);
return "<text>{$raw}</text>\n";
}
function copy_and_flatten(&$object, $path, $courseid) {
global $CFG;
if (!empty($object['media'])) {
$location = $object['media'];
$object['media'] = $this
->flatten_image_name($location);
if (!@copy("{$CFG->dataroot}/{$courseid}/{$location}", "{$path}/{$object['media']}")) {
return "Failed to copy {$CFG->dataroot}/{$courseid}/{$location} to {$path}/{$object['media']}";
}
if (empty($object['mediamimetype'])) {
$object['mediamimetype'] = mimeinfo('type', $object['media']);
}
}
return true;
}
function handle_questions_media(&$questions, $path, $courseid) {
global $CFG;
$errors = array();
foreach ($questions as $key => $question) {
if (!empty($question->image)) {
$location = $questions[$key]->image;
$questions[$key]->mediaurl = $this
->flatten_image_name($location);
if (!@copy("{$CFG->dataroot}/{$courseid}/{$location}", "{$path}/{$questions[$key]->mediaurl}")) {
$errors[] = "Failed to copy {$CFG->dataroot}/{$courseid}/{$location} to {$path}/{$questions[$key]->mediaurl}";
}
if (empty($question->mediamimetype)) {
$questions[$key]->mediamimetype = mimeinfo('type', $question->image);
}
}
}
return empty($errors) ? true : $errors;
}
function exportprocess() {
global $CFG;
$courseid = $this->course->id;
if (!($export_dir = make_upload_directory($this
->question_get_export_dir() . '/' . $this->filename))) {
error(get_string('cannotcreatepath', 'quiz', $export_dir));
}
$path = $CFG->dataroot . '/' . $this
->question_get_export_dir() . '/' . $this->filename;
$questions = $this->questions;
notify("Exporting " . count($questions) . " questions.");
$count = 0;
$smarty =& $this
->init_smarty();
$this
->add_qti_info($questions);
$result = $this
->handle_questions_media($questions, $path, $courseid);
if ($result !== true) {
notify(implode("<br />", $result));
}
$manifestquestions = $this
->objects_to_array($questions);
$manifestid = str_replace(array(
':',
'/',
), array(
'-',
'_',
), "question_category_{$this->category->id}---{$CFG->wwwroot}");
$smarty
->assign('externalfiles', 1);
$smarty
->assign('manifestidentifier', $manifestid);
$smarty
->assign('quiztitle', "question_category_{$this->category->id}");
$smarty
->assign('quizinfo', "All questions in category {$this->category->id}");
$smarty
->assign('questions', $manifestquestions);
$smarty
->assign('lang', $this->lang);
$smarty->error_reporting = 99;
$expout = $smarty
->fetch('imsmanifest.tpl');
$filepath = $path . '/imsmanifest.xml';
if (empty($expout)) {
error("Unkown error - empty imsmanifest.xml");
}
if (!($fh = fopen($filepath, "w"))) {
error("Cannot open for writing: {$filepath}");
}
if (!fwrite($fh, $expout)) {
error("Cannot write exported questions to {$filepath}");
}
fclose($fh);
foreach ($questions as $question) {
$count++;
echo "<hr /><p><b>{$count}</b>. " . stripslashes($question->questiontext) . "</p>";
$expout = $this
->writequestion($question, null, true, $path) . "\n";
$expout = $this
->presave_process($expout);
$filepath = $path . '/' . $this
->get_assesment_item_id($question) . ".xml";
if (!($fh = fopen($filepath, "w"))) {
error("Cannot open for writing: {$filepath}");
}
if (!fwrite($fh, $expout)) {
error("Cannot write exported questions to {$filepath}");
}
fclose($fh);
}
print "path: {$path}";
zip_files(array(
$path,
), "{$path}.zip");
$this->filename = basename($path);
remove_dir($path);
return true;
}
function export_quiz($course, $quiz, $questions, $result, $redirect, $submiturl = null) {
$this
->xml_entitize($course);
$this
->xml_entitize($quiz);
$this
->xml_entitize($questions);
$this
->xml_entitize($result);
$this
->xml_entitize($submiturl);
if (!$this
->exportpreprocess(0, $course)) {
error("Error occurred during pre-processing!", $redirect);
}
if (!$this
->exportprocess_quiz($quiz, $questions, $result, $submiturl, $course)) {
error("Error occurred during processing!", $redirect);
}
if (!$this
->exportpostprocess()) {
error("Error occurred during post-processing!", $redirect);
}
}
function exportprocess_quiz($quiz, $questions, $result, $submiturl, $course) {
global $USER;
global $CFG;
$gradingmethod = array(
1 => 'GRADEHIGHEST',
2 => 'GRADEAVERAGE',
3 => 'ATTEMPTFIRST',
4 => 'ATTEMPTLAST',
);
$questions = $this
->quiz_export_prepare_questions($questions, $quiz->id, $course->id, $quiz->shuffleanswers);
$smarty =& $this
->init_smarty();
$smarty
->assign('questions', $questions);
$manifestid = str_replace(array(
':',
'/',
), array(
'-',
'_',
), "quiz{$quiz->id}-{$CFG->wwwroot}");
$smarty
->assign('manifestidentifier', $manifestid);
$smarty
->assign('submiturl', $submiturl);
$smarty
->assign('userid', $USER->id);
$smarty
->assign('username', htmlspecialchars($USER->username, ENT_COMPAT, 'UTF-8'));
$smarty
->assign('quiz_level_export', 1);
$smarty
->assign('quiztitle', format_string($quiz->name, true));
$smarty
->assign('quiztimeopen', date('Y-m-d\\TH:i:s', $quiz->timeopen));
$smarty
->assign('quiztimeclose', date('Y-m-d\\TH:i:s', $quiz->timeclose));
$smarty
->assign('grademethod', $gradingmethod[$quiz->grademethod]);
$smarty
->assign('quiz', $quiz);
$smarty
->assign('course', $course);
$smarty
->assign('lang', $this->lang);
$expout = $smarty
->fetch('imsmanifest.tpl');
echo $expout;
return true;
}
function quiz_export_prepare_questions($questions, $quizid, $courseid, $shuffleanswers = null) {
global $CFG;
foreach ($questions as $key => $question) {
$questions[$key] = get_question_data($question);
$questions[$key]->courseid = $courseid;
$questions[$key]->quizid = $quizid;
if ($question->image) {
if (empty($question->mediamimetype)) {
$questions[$key]->mediamimetype = mimeinfo('type', $question->image);
}
$localfile = substr(strtolower($question->image), 0, 7) == 'http://' ? false : true;
if ($localfile) {
if ($CFG->slasharguments) {
$questions[$key]->mediaurl = "{$CFG->wwwroot}/file.php/{$question->image}";
}
else {
$questions[$key]->mediaurl = "{$CFG->wwwroot}/file.php?file={$question->image}";
}
}
else {
$questions[$key]->mediaurl = $question->image;
}
}
}
$this
->add_qti_info($questions);
$questions = $this
->questions_with_export_info($questions, $shuffleanswers);
$questions = $this
->objects_to_array($questions);
return $questions;
}
function xml_entitize(&$collection) {
if (is_array($collection)) {
foreach ($collection as $key => $var) {
if (is_string($var)) {
$collection[$key] = htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
}
else {
if (is_array($var) || is_object($var)) {
$this
->xml_entitize($collection[$key]);
}
}
}
}
else {
if (is_object($collection)) {
$vars = get_object_vars($collection);
foreach ($vars as $key => $var) {
if (is_string($var)) {
$collection->{$key} = htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
}
else {
if (is_array($var) || is_object($var)) {
$this
->xml_entitize($collection->{$key});
}
}
}
}
else {
if (is_string($collection)) {
$collection = htmlspecialchars($collection, ENT_COMPAT, 'UTF-8');
}
}
}
}
function questions_with_export_info($questions, $shuffleanswers = null) {
$exportquestions = array();
foreach ($questions as $key => $question) {
$expout = $this
->writequestion($question, $shuffleanswers) . "\n";
$expout = $this
->presave_process($expout);
$key = $this
->get_assesment_item_id($question);
$exportquestions[$key] = $question;
$exportquestions[$key]->exporttext = $expout;
}
return $exportquestions;
}
function writequestion($question, $shuffleanswers = null, $courselevel = false, $path = '') {
global $CFG;
$expout = '';
$question->questiontext = html_entity_decode($question->questiontext, ENT_COMPAT);
$hasimage = empty($question->image) ? 0 : 1;
$hassize = empty($question->mediax) ? 0 : 1;
$allowedtags = '<a><br><b><h1><h2><h3><h4><i><img><li><ol><strong><table><tr><td><th><u><ul><object>';
$smarty =& $this
->init_smarty();
$assesmentitemid = $this
->get_assesment_item_id($question);
$question_type = $this
->get_qtype($question->qtype);
$questionid = "question{$question->id}{$question_type}";
$smarty
->assign('question_has_image', $hasimage);
$smarty
->assign('hassize', $hassize);
$smarty
->assign('questionid', $questionid);
$smarty
->assign('assessmentitemidentifier', $assesmentitemid);
$smarty
->assign('assessmentitemtitle', $question->name);
$smarty
->assign('courselevelexport', $courselevel);
if ($question->qtype == MULTIANSWER) {
$question->questiontext = strip_tags($question->questiontext, $allowedtags . '<intro>');
$smarty
->assign('questionText', $this
->get_cloze_intro($question->questiontext));
}
else {
$smarty
->assign('questionText', strip_tags($question->questiontext, $allowedtags));
}
$smarty
->assign('question', $question);
switch ($question->qtype) {
case TRUEFALSE:
$qanswers = $question->options->answers;
$answers[0] = (array) $qanswers['true'];
$answers[0]['answer'] = get_string("true", "quiz");
$answers[1] = (array) $qanswers['false'];
$answers[1]['answer'] = get_string("false", "quiz");
if (!empty($shuffleanswers)) {
$answers = $this
->shuffle_things($answers);
}
if (isset($question->response)) {
$correctresponseid = $question->response[$questionid];
if ($answers[0]['id'] == $correctresponseid) {
$correctresponse = $answers[0];
}
else {
$correctresponse = $answers[1];
}
}
else {
$correctresponse = '';
}
$smarty
->assign('correctresponse', $correctresponse);
$smarty
->assign('answers', $answers);
$expout = $smarty
->fetch('choice.tpl');
break;
case MULTICHOICE:
$answers = $this
->objects_to_array($question->options->answers);
$correctresponses = $this
->get_correct_answers($answers);
$correctcount = count($correctresponses);
$smarty
->assign('responsedeclarationcardinality', $question->options->single ? 'single' : 'multiple');
$smarty
->assign('operator', $question->options->single ? 'match' : 'member');
$smarty
->assign('correctresponses', $correctresponses);
$smarty
->assign('answers', $answers);
$smarty
->assign('maxChoices', $question->options->single ? '1' : count($answers));
$smarty
->assign('maxChoices', $question->options->single ? '1' : count($answers));
$smarty
->assign('shuffle', empty($shuffleanswers) ? 'false' : 'true');
$smarty
->assign('generalfeedback', $question->generalfeedback);
$smarty
->assign('correctfeedback', $question->options->correctfeedback);
$smarty
->assign('partiallycorrectfeedback', $question->options->partiallycorrectfeedback);
$smarty
->assign('incorrectfeedback', $question->options->incorrectfeedback);
$expout = $smarty
->fetch('choiceMultiple.tpl');
break;
case SHORTANSWER:
$answers = $this
->objects_to_array($question->options->answers);
if (!empty($shuffleanswers)) {
$answers = $this
->shuffle_things($answers);
}
$correctresponses = $this
->get_correct_answers($answers);
$correctcount = count($correctresponses);
$smarty
->assign('responsedeclarationcardinality', $correctcount > 1 ? 'multiple' : 'single');
$smarty
->assign('correctresponses', $correctresponses);
$smarty
->assign('answers', $answers);
$expout = $smarty
->fetch('textEntry.tpl');
break;
case NUMERICAL:
$qanswer = array_pop($question->options->answers);
$smarty
->assign('lowerbound', $qanswer->answer - $qanswer->tolerance);
$smarty
->assign('upperbound', $qanswer->answer + $qanswer->tolerance);
$smarty
->assign('answer', $qanswer->answer);
$expout = $smarty
->fetch('numerical.tpl');
break;
case MATCH:
$this
->xml_entitize($question->options->subquestions);
$subquestions = $this
->objects_to_array($question->options->subquestions);
if (!empty($shuffleanswers)) {
$subquestions = $this
->shuffle_things($subquestions);
}
$setcount = count($subquestions);
$smarty
->assign('setcount', $setcount);
$smarty
->assign('matchsets', $subquestions);
$expout = $smarty
->fetch('match.tpl');
break;
case DESCRIPTION:
$expout = $smarty
->fetch('extendedText.tpl');
break;
default:
$smarty
->assign('questionText', "This question type (Unknown: type {$question_type}) has not yet been implemented");
$expout = $smarty
->fetch('notimplemented.tpl');
}
return $expout;
}
function get_assesment_item_id($question) {
return "question{$question->id}";
}
function get_correct_answers($answers) {
$correctanswers = array();
foreach ($answers as $answer) {
if ($answer['fraction'] > 0) {
$correctanswers[] = $answer;
}
}
return $correctanswers;
}
function &init_smarty() {
global $CFG;
$path = $CFG->dataroot . "/smarty_c";
if (!is_dir($path)) {
if (!mkdir($path, $CFG->directorypermissions)) {
error("Cannot create path: {$path}");
}
}
$smarty = new Smarty();
$smarty->template_dir = "{$CFG->dirroot}/question/format/qti2/templates";
$smarty->compile_dir = "{$path}";
return $smarty;
}
function objects_to_array($objectarray) {
$arrayarray = array();
foreach ($objectarray as $object) {
$arrayarray[] = (array) $object;
}
return $arrayarray;
}
function get_cloze_answers_array($question) {
$answers = $this
->get_answers($question);
$this
->xml_entitize($answers);
foreach ($answers as $answerkey => $answer) {
$answers[$answerkey]->subanswers = $this
->objects_to_array($answer->subanswers);
}
return $this
->objects_to_array($answers);
}
function get_cloze_questions($question, $answers, $allowabletags) {
$questiontext = strip_tags($question->questiontext, $allowabletags);
if (preg_match_all('/(.*){#([0-9]+)}/U', $questiontext, $matches)) {
if (preg_match('/.*{#[0-9]+}(.*)$/', $questiontext, $tail)) {
$matches[1][] = $tail[1];
$tailadded = true;
}
$questions['text'] = $matches[1];
$questions['question'] = array();
foreach ($matches[2] as $key => $questionid) {
foreach ($answers as $answer) {
if ($answer['positionkey'] == $questionid) {
$questions['question'][$key] = $answer;
break;
}
}
}
if ($tailadded) {
$questions['question'][] = array(
'id' => CLOZE_TRAILING_TEXT_ID,
'answertype' => SHORTANSWER,
);
}
}
else {
$questions['text'][0] = $question->questiontext;
$questions['question'][0] = array(
'id' => CLOZE_TRAILING_TEXT_ID,
'answertype' => SHORTANSWER,
);
}
return $questions;
}
function get_cloze_intro(&$text) {
if (preg_match('/(.*)?\\<intro>(.+)?\\<\\/intro>(.*)/s', $text, $matches)) {
$text = $matches[1] . $matches[3];
return $matches[2];
}
else {
return '';
}
}
function add_qti_info(&$questions) {
foreach ($questions as $key => $question) {
$questions[$key]->qtiinteractiontype = $this
->get_qti_interaction_type($question->qtype);
$questions[$key]->qtiscoreable = $this
->get_qti_scoreable($question);
$questions[$key]->qtisolutionavailable = $this
->get_qti_solution_available($question);
}
}
function get_qti_scoreable($question) {
switch ($question->qtype) {
case DESCRIPTION:
return 'false';
default:
return 'true';
}
}
function get_qti_solution_available($question) {
switch ($question->qtype) {
case TRUEFALSE:
return 'true';
case MULTICHOICE:
return 'true';
case SHORTANSWER:
return 'true';
case NUMERICAL:
return 'true';
case MATCH:
return 'true';
case DESCRIPTION:
return 'false';
case MULTIANSWER:
return 'true';
default:
return 'true';
}
}
function get_qti_interaction_type($type_id) {
switch ($type_id) {
case TRUEFALSE:
$name = 'choiceInteraction';
break;
case MULTICHOICE:
$name = 'choiceInteraction';
break;
case SHORTANSWER:
$name = 'textInteraction';
break;
case NUMERICAL:
$name = 'textInteraction';
break;
case MATCH:
$name = 'matchInteraction';
break;
case DESCRIPTION:
$name = 'extendedTextInteraction';
break;
case MULTIANSWER:
$name = 'textInteraction';
break;
default:
$name = 'textInteraction';
}
return $name;
}
function shuffle_things($things) {
$things = swapshuffle_assoc($things);
$oldthings = $things;
$things = array();
foreach ($oldthings as $key => $value) {
$things[] = $value;
}
return $things;
}
function flatten_image_name($name) {
return str_replace(array(
'/',
'\\',
':',
), array(
'_',
'-',
'.',
), $name);
}
function file_full_path($file, $courseid) {
global $CFG;
if (substr(strtolower($file), 0, 7) == 'http://') {
$url = $file;
}
else {
if ($CFG->slasharguments) {
$url = "{$CFG->wwwroot}/file.php/{$courseid}/{$file}";
}
else {
$url = "{$CFG->wwwroot}/file.php?file=/{$courseid}/{$file}";
}
}
return $url;
}
}