Actualización

This commit is contained in:
Xes
2025-04-10 12:49:05 +02:00
parent 4aff98e77b
commit 1cdd00920f
9151 changed files with 1800913 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
<?php
/* For licensing terms, see /license.txt */
/**
* @author Claro Team <cvs@claroline.net>
* @author Yannick Warnier <yannick.warnier@beeznest.com> - updated ImsAnswerHotspot to match QTI norms
* @author César Perales <cesar.perales@gmail.com> Updated function names and import files for Aiken format support
*/
/**
* Aiken2Question transformation class.
*/
class Aiken2Question extends Question
{
/**
* Include the correct answer class and create answer.
*/
public function setAnswer()
{
switch ($this->type) {
case MCUA:
$answer = new AikenAnswerMultipleChoice($this->iid);
return $answer;
default:
$answer = null;
break;
}
return $answer;
}
public function createAnswersForm($form)
{
return true;
}
public function processAnswersCreation($form, $exercise)
{
return true;
}
}
/**
* Class.
*/
class AikenAnswerMultipleChoice extends Answer
{
}

View File

@@ -0,0 +1,594 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Library for the import of Aiken format.
*
* @author claro team <cvs@claroline.net>
* @author Guillaume Lederer <guillaume@claroline.net>
* @author César Perales <cesar.perales@gmail.com> Parse function for Aiken format
*/
/**
* This function displays the form for import of the zip file with qti2.
*
* @param string Report message to show in case of error
*/
function aiken_display_form()
{
$name_tools = get_lang('ImportAikenQuiz');
$form = '<div class="actions">';
$form .= '<a href="exercise.php?show=test&'.api_get_cidreq().'">'.
Display::return_icon(
'back.png',
get_lang('BackToExercisesList'),
'',
ICON_SIZE_MEDIUM
).'</a>';
$form .= '</div>';
$form_validator = new FormValidator(
'aiken_upload',
'post',
api_get_self()."?".api_get_cidreq(),
null,
['enctype' => 'multipart/form-data']
);
$form_validator->addElement('header', $name_tools);
$form_validator->addElement('text', 'total_weight', get_lang('TotalWeight'));
$form_validator->addElement('file', 'userFile', get_lang('File'));
$form_validator->addButtonUpload(get_lang('Upload'), 'submit');
$form .= $form_validator->returnForm();
$form .= '<blockquote>'.get_lang('ImportAikenQuizExplanation').'<br /><pre>'.get_lang('ImportAikenQuizExplanationExample').'</pre></blockquote>';
echo $form;
}
/**
* Generates aiken format using AI api.
* Requires plugin ai_helper to connect to the api.
*/
function generateAikenForm()
{
if (!('true' === api_get_plugin_setting('ai_helper', 'tool_enable') && 'true' === api_get_plugin_setting('ai_helper', 'tool_quiz_enable'))) {
return false;
}
$form = new FormValidator(
'aiken_generate',
'post',
api_get_self()."?".api_get_cidreq(),
null
);
$form->addElement('header', get_lang('AIQuestionsGenerator'));
$form->addElement('text', 'quiz_name', [get_lang('QuestionsTopic'), get_lang('QuestionsTopicHelp')]);
$form->addRule('quiz_name', get_lang('ThisFieldIsRequired'), 'required');
$form->addElement('number', 'nro_questions', [get_lang('NumberOfQuestions'), get_lang('AIQuestionsGeneratorNumberHelper')]);
$form->addRule('nro_questions', get_lang('ThisFieldIsRequired'), 'required');
$options = [
'multiple_choice' => get_lang('MultipleAnswer'),
];
$form->addElement(
'select',
'question_type',
get_lang('QuestionType'),
$options
);
$generateUrl = api_get_path(WEB_PLUGIN_PATH).'ai_helper/tool/answers.php';
$language = api_get_interface_language();
$form->addHtml('<script>
$(function () {
$("#aiken-area").hide();
$("#generate-aiken").on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var btnGenerate = $(this);
var quizName = $("[name=\'quiz_name\']").val();
var nroQ = parseInt($("[name=\'nro_questions\']").val());
var qType = $("[name=\'question_type\']").val();
var valid = (quizName != \'\' && nroQ > 0);
var qWeight = 1;
if (valid) {
btnGenerate.attr("disabled", true);
btnGenerate.text("'.get_lang('PleaseWaitThisCouldTakeAWhile').'");
$("#textarea-aiken").text("");
$("#aiken-area").hide();
$.getJSON("'.$generateUrl.'", {
"quiz_name": quizName,
"nro_questions": nroQ,
"question_type": qType,
"language": "'.$language.'"
}).done(function (data) {
btnGenerate.attr("disabled", false);
btnGenerate.text("'.get_lang('Generate').'");
if (data.success && data.success == true) {
$("#aiken-area").show();
$("#textarea-aiken").text(data.text);
$("input[name=\'ai_total_weight\']").val(nroQ * qWeight);
$("#textarea-aiken").focus();
} else {
var errorMessage = "'.get_lang('NoSearchResults').'. '.get_lang('PleaseTryAgain').'";
if (data.text) {
errorMessage = data.text;
}
alert(errorMessage);
}
});
}
});
});
</script>');
$form->addButton(
'generate_aiken_button',
get_lang('Generate'),
'',
'default',
'default',
null,
['id' => 'generate-aiken']
);
$form->addHtml('<div id="aiken-area">');
$form->addElement(
'textarea',
'aiken_format',
get_lang('Answers'),
[
'id' => 'textarea-aiken',
'style' => 'width: 100%; height: 250px;',
]
);
$form->addElement('number', 'ai_total_weight', get_lang('TotalWeight'));
$form->addButtonImport(get_lang('Import'), 'submit_aiken_generated');
$form->addHtml('</div>');
echo $form->returnForm();
}
/**
* Gets the uploaded file (from $_FILES) and unzip it to the given directory.
*
* @param string The directory where to do the work
* @param string The path of the temporary directory where the exercise was uploaded and unzipped
* @param string $baseWorkDir
* @param string $uploadPath
*
* @return bool True on success, false on failure
*/
function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
{
$_course = api_get_course_info();
$_user = api_get_user_info();
// Check if the file is valid (not to big and exists)
if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
// upload failed
return false;
}
if (preg_match('/.zip$/i', $_FILES['userFile']['name']) &&
handle_uploaded_document(
$_course,
$_FILES['userFile'],
$baseWorkDir,
$uploadPath,
$_user['user_id'],
0,
null,
1,
'overwrite',
false,
true
)
) {
if (!function_exists('gzopen')) {
return false;
}
// upload successful
return true;
} elseif (preg_match('/.txt/i', $_FILES['userFile']['name']) &&
handle_uploaded_document(
$_course,
$_FILES['userFile'],
$baseWorkDir,
$uploadPath,
$_user['user_id'],
0,
null,
0,
'overwrite',
false
)
) {
return true;
}
return false;
}
/**
* Main function to import the Aiken exercise.
*
* @param string $file
* @param array $request
*
* @return mixed True on success, error message on failure
*/
function aikenImportExercise($file = null, $request = [])
{
$exerciseInfo = [];
$fileIsSet = false;
if (isset($file)) {
$fileIsSet = true;
// The import is from aiken file format.
$archivePath = api_get_path(SYS_ARCHIVE_PATH).'aiken/';
$baseWorkDir = $archivePath;
$uploadPath = 'aiken_'.api_get_unique_id();
if (!is_dir($baseWorkDir.$uploadPath)) {
mkdir($baseWorkDir.$uploadPath, api_get_permissions_for_new_directories(), true);
}
// set some default values for the new exercise
$exerciseInfo['name'] = preg_replace('/.(zip|txt)$/i', '', $file);
$exerciseInfo['total_weight'] = !empty($_POST['total_weight']) ? (int) ($_POST['total_weight']) : 20;
$exerciseInfo['question'] = [];
// if file is not a .zip, then we cancel all
if (!preg_match('/.(zip|txt)$/i', $file)) {
return 'YouMustUploadAZipOrTxtFile';
}
// unzip the uploaded file in a tmp directory
if (preg_match('/.(zip|txt)$/i', $file)) {
if (!get_and_unzip_uploaded_exercise($baseWorkDir.$uploadPath, '/')) {
return 'ThereWasAProblemWithYourFile';
}
}
// find the different manifests for each question and parse them
$exerciseHandle = opendir($baseWorkDir.$uploadPath);
$fileFound = false;
$operation = false;
$result = false;
// Parse every subdirectory to search txt question files
while (false !== ($file = readdir($exerciseHandle))) {
if (is_dir($baseWorkDir.'/'.$uploadPath.$file) && $file != "." && $file != "..") {
//find each manifest for each question repository found
$questionHandle = opendir($baseWorkDir.'/'.$uploadPath.$file);
while (false !== ($questionFile = readdir($questionHandle))) {
if (preg_match('/.txt$/i', $questionFile)) {
$result = aiken_parse_file(
$exerciseInfo,
$baseWorkDir,
$file,
$questionFile
);
$fileFound = true;
}
}
} elseif (preg_match('/.txt$/i', $file)) {
$result = aiken_parse_file($exerciseInfo, $baseWorkDir.$uploadPath, '', $file);
$fileFound = true;
}
}
if (!$fileFound) {
$result = 'NoTxtFileFoundInTheZip';
}
if (true !== $result) {
return $result;
}
} elseif (!empty($request)) {
// The import is from aiken generated in textarea.
$exerciseInfo['name'] = $request['quiz_name'];
$exerciseInfo['total_weight'] = !empty($_POST['ai_total_weight']) ? (int) ($_POST['ai_total_weight']) : (int) $request['nro_questions'];
$exerciseInfo['question'] = [];
$exerciseInfo['course_id'] = isset($request['course_id']) ? (int) $request['course_id'] : 0;
setExerciseInfoFromAikenText($request['aiken_format'], $exerciseInfo);
}
// 1. Create exercise.
if (!empty($exerciseInfo)) {
$exercise = new Exercise($exerciseInfo['course_id']);
$exercise->exercise = $exerciseInfo['name'];
$exercise->disable(); // Invisible by default
$exercise->updateResultsDisabled(0); // Auto-evaluation mode: show score and expected answers
$exercise->save();
$lastExerciseId = $exercise->selectId();
$tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
$tableAnswer = Database::get_course_table(TABLE_QUIZ_ANSWER);
if (!empty($lastExerciseId)) {
$courseId = !empty($exerciseInfo['course_id']) ? (int) $exerciseInfo['course_id'] : api_get_course_int_id();
foreach ($exerciseInfo['question'] as $key => $questionArray) {
if (!isset($questionArray['title'])) {
continue;
}
// 2. Create question.
$question = new Aiken2Question();
$question->type = $questionArray['type'];
$question->setAnswer();
$question->updateTitle($questionArray['title']);
if (isset($questionArray['description'])) {
$question->updateDescription($questionArray['description']);
}
$type = $question->selectType();
$question->course = api_get_course_info_by_id($courseId);
$question->type = constant($type);
$question->save($exercise);
$last_question_id = $question->selectId();
// 3. Create answer
$answer = new Answer($last_question_id, $courseId, $exercise, false);
$answer->new_nbrAnswers = isset($questionArray['answer']) ? count($questionArray['answer']) : 0;
$max_score = 0;
$scoreFromFile = 0;
if (isset($questionArray['score']) && !empty($questionArray['score'])) {
$scoreFromFile = $questionArray['score'];
}
foreach ($questionArray['answer'] as $key => $answers) {
$key++;
$answer->new_answer[$key] = $answers['value'];
$answer->new_position[$key] = $key;
$answer->new_comment[$key] = '';
// Correct answers ...
if (isset($questionArray['correct_answers']) &&
in_array($key, $questionArray['correct_answers'])
) {
$answer->new_correct[$key] = 1;
if (isset($questionArray['feedback'])) {
$answer->new_comment[$key] = $questionArray['feedback'];
}
} else {
$answer->new_correct[$key] = 0;
}
if (isset($questionArray['weighting'][$key - 1])) {
$answer->new_weighting[$key] = $questionArray['weighting'][$key - 1];
$max_score += $questionArray['weighting'][$key - 1];
}
if (!empty($scoreFromFile) && $answer->new_correct[$key]) {
$answer->new_weighting[$key] = $scoreFromFile;
}
$params = [
'c_id' => $courseId,
'question_id' => $last_question_id,
'answer' => $answer->new_answer[$key],
'correct' => $answer->new_correct[$key],
'comment' => $answer->new_comment[$key],
'ponderation' => isset($answer->new_weighting[$key]) ? $answer->new_weighting[$key] : '',
'position' => $answer->new_position[$key],
'hotspot_coordinates' => '',
'hotspot_type' => '',
];
$answerId = Database::insert($tableAnswer, $params);
if ($answerId) {
$params = [
'id_auto' => $answerId,
'iid' => $answerId,
];
Database::update($tableAnswer, $params, ['iid = ?' => [$answerId]]);
}
}
if (!empty($scoreFromFile)) {
$max_score = $scoreFromFile;
}
$params = ['ponderation' => $max_score];
Database::update(
$tableQuestion,
$params,
['iid = ?' => [$last_question_id]]
);
}
// Delete the temp dir where the exercise was unzipped
if ($fileIsSet) {
my_delete($baseWorkDir.$uploadPath);
}
// Invisible by default
api_item_property_update(
api_get_course_info(),
TOOL_QUIZ,
$lastExerciseId,
'invisible',
api_get_user_id()
);
return $lastExerciseId;
}
}
return false;
}
/**
* Set the exercise information from an aiken text formatted.
*/
function setExerciseInfoFromAikenText($aikenText, &$exerciseInfo)
{
$detect = mb_detect_encoding($aikenText, 'ASCII', true);
if ('ASCII' === $detect) {
$data = explode("\n", $aikenText);
} else {
if (false !== stripos($aikenText, "\x0D") || false !== stripos($aikenText, "\r\n")) {
$text = str_ireplace(["\x0D", "\r\n"], "\n", $aikenText); // Removes ^M char from win files.
$data = explode("\n\n", $text);
} else {
$data = explode("\n", $aikenText);
}
}
$questionIndex = 0;
$answersArray = [];
foreach ($data as $line => $info) {
$info = trim($info);
if (empty($info)) {
continue;
}
//make sure it is transformed from iso-8859-1 to utf-8 if in that form
if (!mb_check_encoding($info, 'utf-8') && mb_check_encoding($info, 'iso-8859-1')) {
$info = utf8_encode($info);
}
$exerciseInfo['question'][$questionIndex]['type'] = 'MCUA';
if (preg_match('/^([A-Za-z])(\)|\.)\s(.*)/', $info, $matches)) {
//adding one of the possible answers
$exerciseInfo['question'][$questionIndex]['answer'][]['value'] = $matches[3];
$answersArray[] = $matches[1];
} elseif (preg_match('/^ANSWER:\s?([A-Z])\s?/', $info, $matches)) {
//the correct answers
$correctAnswerIndex = array_search($matches[1], $answersArray);
$exerciseInfo['question'][$questionIndex]['correct_answers'][] = $correctAnswerIndex + 1;
//weight for correct answer
$exerciseInfo['question'][$questionIndex]['weighting'][$correctAnswerIndex] = 1;
$next = $line + 1;
if (isset($data[$next]) && false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
continue;
}
if (isset($data[$next]) && false !== strpos($data[$next], 'DESCRIPTION:')) {
continue;
}
// Check if next has score, otherwise loop too next question.
if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
$answersArray = [];
$questionIndex++;
continue;
}
} elseif (preg_match('/^SCORE:\s?(.*)/', $info, $matches)) {
$exerciseInfo['question'][$questionIndex]['score'] = (float) $matches[1];
$answersArray = [];
$questionIndex++;
continue;
} elseif (preg_match('/^DESCRIPTION:\s?(.*)/', $info, $matches)) {
$exerciseInfo['question'][$questionIndex]['description'] = $matches[1];
$next = $line + 1;
if (isset($data[$next]) && false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
continue;
}
// Check if next has score, otherwise loop too next question.
if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
$answersArray = [];
$questionIndex++;
continue;
}
} elseif (preg_match('/^ANSWER_EXPLANATION:\s?(.*)/', $info, $matches)) {
// Comment of correct answer
$correctAnswerIndex = array_search($matches[1], $answersArray);
$exerciseInfo['question'][$questionIndex]['feedback'] = $matches[1];
$next = $line + 1;
// Check if next has score, otherwise loop too next question.
if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
$answersArray = [];
$questionIndex++;
continue;
}
} elseif (preg_match('/^TEXTO_CORRECTA:\s?(.*)/', $info, $matches)) {
//Comment of correct answer (Spanish e-ducativa format)
$correctAnswerIndex = array_search($matches[1], $answersArray);
$exerciseInfo['question'][$questionIndex]['feedback'] = $matches[1];
} elseif (preg_match('/^T:\s?(.*)/', $info, $matches)) {
//Question Title
$correctAnswerIndex = array_search($matches[1], $answersArray);
$exerciseInfo['question'][$questionIndex]['title'] = $matches[1];
} elseif (preg_match('/^TAGS:\s?([A-Z])\s?/', $info, $matches)) {
//TAGS for chamilo >= 1.10
$exerciseInfo['question'][$questionIndex]['answer_tags'] = explode(',', $matches[1]);
} elseif (preg_match('/^ETIQUETAS:\s?([A-Z])\s?/', $info, $matches)) {
//TAGS for chamilo >= 1.10 (Spanish e-ducativa format)
$exerciseInfo['question'][$questionIndex]['answer_tags'] = explode(',', $matches[1]);
} else {
if (empty($exerciseInfo['question'][$questionIndex]['title'])) {
$exerciseInfo['question'][$questionIndex]['title'] = $info;
}
}
}
$totalQuestions = count($exerciseInfo['question']);
$totalWeight = (int) $exerciseInfo['total_weight'];
foreach ($exerciseInfo['question'] as $key => $question) {
if (!isset($exerciseInfo['question'][$key]['weighting'])) {
continue;
}
$exerciseInfo['question'][$key]['weighting'][current(array_keys($exerciseInfo['question'][$key]['weighting']))] = $totalWeight / $totalQuestions;
}
}
/**
* Parses an Aiken file and builds an array of exercise + questions to be
* imported by the import_exercise() function.
*
* @param array The reference to the array in which to store the questions
* @param string Path to the directory with the file to be parsed (without final /)
* @param string Name of the last directory part for the file (without /)
* @param string Name of the file to be parsed (including extension)
* @param string $exercisePath
* @param string $file
* @param string $questionFile
*
* @return string|bool True on success, error message on error
* @assert ('','','') === false
*/
function aiken_parse_file(&$exercise_info, $exercisePath, $file, $questionFile)
{
$questionTempDir = $exercisePath.'/'.$file.'/';
$questionFilePath = $questionTempDir.$questionFile;
if (!is_file($questionFilePath)) {
return 'FileNotFound';
}
$text = file_get_contents($questionFilePath);
setExerciseInfoFromAikenText($text, $exercise_info);
return true;
}
/**
* Imports the zip file.
*
* @param array $array_file ($_FILES)
*
* @return bool
*/
function aiken_import_file($array_file)
{
$unzip = 0;
$process = process_uploaded_file($array_file, false);
if (preg_match('/\.(zip|txt)$/i', $array_file['name'])) {
// if it's a zip, allow zip upload
$unzip = 1;
}
if ($process && $unzip == 1) {
$imported = aikenImportExercise($array_file['name']);
if (is_numeric($imported) && !empty($imported)) {
Display::addFlash(Display::return_message(get_lang('Uploaded')));
return $imported;
} else {
Display::addFlash(Display::return_message(get_lang($imported), 'error'));
return false;
}
}
}

View File

@@ -0,0 +1,737 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
use Symfony\Component\DomCrawler\Crawler;
/**
* @copyright (c) 2001-2006 Universite catholique de Louvain (UCL)
* @author claro team <cvs@claroline.net>
* @author Guillaume Lederer <guillaume@claroline.net>
* @author Yannick Warnier <yannick.warnier@beeznest.com>
*/
/**
* Unzip the exercise in the temp folder.
*
* @param string $baseWorkDir The path of the temporary directory where the exercise was uploaded and unzipped
* @param string $uploadPath
*
* @return bool
*/
function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
{
$_course = api_get_course_info();
$_user = api_get_user_info();
//Check if the file is valid (not to big and exists)
if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
// upload failed
return false;
}
if (preg_match('/.zip$/i', $_FILES['userFile']['name'])) {
return handle_uploaded_document(
$_course,
$_FILES['userFile'],
$baseWorkDir,
$uploadPath,
$_user['user_id'],
0,
null,
1,
null,
null,
true,
null,
null,
false
);
}
return false;
}
/**
* Imports an exercise in QTI format if the XML structure can be found in it.
*
* @param array $file
*
* @return string|array as a backlog of what was really imported, and error or debug messages to display
*/
function import_exercise($file)
{
global $exerciseInfo;
global $resourcesLinks;
$baseWorkDir = api_get_path(SYS_ARCHIVE_PATH).'qti2/';
if (!is_dir($baseWorkDir)) {
mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
}
$uploadPath = api_get_unique_id().'/';
if (!is_dir($baseWorkDir.$uploadPath)) {
mkdir($baseWorkDir.$uploadPath, api_get_permissions_for_new_directories(), true);
}
// set some default values for the new exercise
$exerciseInfo = [];
$exerciseInfo['name'] = preg_replace('/.zip$/i', '', $file);
$exerciseInfo['question'] = [];
// if file is not a .zip, then we cancel all
if (!preg_match('/.zip$/i', $file)) {
return 'UplZipCorrupt';
}
// unzip the uploaded file in a tmp directory
if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
return 'UplZipCorrupt';
}
$baseWorkDir = $baseWorkDir.$uploadPath;
// find the different manifests for each question and parse them.
$exerciseHandle = opendir($baseWorkDir);
$fileFound = false;
$result = false;
$filePath = null;
$resourcesLinks = [];
// parse every subdirectory to search xml question files and other assets to be imported
// The assets-related code is a bit fragile as it has to deal with files renamed by Chamilo and it only works if
// the imsmanifest.xml file is read.
while (false !== ($file = readdir($exerciseHandle))) {
if (is_dir($baseWorkDir.'/'.$file) && $file != "." && $file != "..") {
// Find each manifest for each question repository found
$questionHandle = opendir($baseWorkDir.'/'.$file);
// Only analyse one level of subdirectory - no recursivity here
while (false !== ($questionFile = readdir($questionHandle))) {
if (preg_match('/.xml$/i', $questionFile)) {
$isQti = isQtiQuestionBank($baseWorkDir.'/'.$file.'/'.$questionFile);
if ($isQti) {
$result = qti_parse_file($baseWorkDir, $file, $questionFile);
$filePath = $baseWorkDir.$file;
$fileFound = true;
} else {
$isManifest = isQtiManifest($baseWorkDir.'/'.$file.'/'.$questionFile);
if ($isManifest) {
$resourcesLinks = qtiProcessManifest($baseWorkDir.'/'.$file.'/'.$questionFile);
}
}
}
}
} elseif (preg_match('/.xml$/i', $file)) {
$isQti = isQtiQuestionBank($baseWorkDir.'/'.$file);
if ($isQti) {
$result = qti_parse_file($baseWorkDir, '', $file);
$filePath = $baseWorkDir.'/'.$file;
$fileFound = true;
} else {
$isManifest = isQtiManifest($baseWorkDir.'/'.$file);
if ($isManifest) {
$resourcesLinks = qtiProcessManifest($baseWorkDir.'/'.$file);
}
}
}
}
if (!$fileFound) {
return 'NoXMLFileFoundInTheZip';
}
if ($result == false) {
return false;
}
// 1. Create exercise.
$exercise = new Exercise();
$exercise->exercise = $exerciseInfo['name'];
// Random QTI support
if (isset($exerciseInfo['order_type'])) {
if ($exerciseInfo['order_type'] == 'Random') {
$exercise->setQuestionSelectionType(2);
$exercise->random = -1;
}
}
if (!empty($exerciseInfo['description'])) {
$exercise->updateDescription(formatText(strip_tags($exerciseInfo['description'])));
}
$exercise->save();
$last_exercise_id = $exercise->selectId();
$courseId = api_get_course_int_id();
if (!empty($last_exercise_id)) {
// For each question found...
foreach ($exerciseInfo['question'] as $question_array) {
if (!in_array($question_array['type'], [UNIQUE_ANSWER, MULTIPLE_ANSWER, FREE_ANSWER])) {
continue;
}
//2. Create question
$question = new Ims2Question();
$question->type = $question_array['type'];
if (empty($question->type)) {
// If the type was not provided, assume this is a multiple choice, unique answer type (the most basic)
$question->type = MCUA;
}
$question->setAnswer();
$description = '';
$question->updateTitle(formatText(strip_tags($question_array['title'])));
if (isset($question_array['category'])) {
$category = formatText(strip_tags($question_array['category']));
if (!empty($category)) {
$categoryId = TestCategory::get_category_id_for_title(
$category,
$courseId
);
if (empty($categoryId)) {
$cat = new TestCategory();
$cat->name = $category;
$cat->description = '';
$categoryId = $cat->save($courseId);
if ($categoryId) {
$question->category = $categoryId;
}
} else {
$question->category = $categoryId;
}
}
}
if (!empty($question_array['description'])) {
$description .= $question_array['description'];
}
$question->updateDescription($description);
$question->save($exercise);
$last_question_id = $question->selectId();
//3. Create answer
$answer = new Answer($last_question_id);
$answerList = $question_array['answer'];
$answer->new_nbrAnswers = count($answerList);
$totalCorrectWeight = 0;
$j = 1;
$matchAnswerIds = [];
if (!empty($answerList)) {
foreach ($answerList as $key => $answers) {
if (preg_match('/_/', $key)) {
$split = explode('_', $key);
$i = $split[1];
} else {
$i = $j;
$j++;
$matchAnswerIds[$key] = $j;
}
// Answer
$answer->new_answer[$i] = isset($answers['value']) ? formatText($answers['value']) : '';
// Comment
$answer->new_comment[$i] = isset($answers['feedback']) ? formatText($answers['feedback']) : null;
// Position
$answer->new_position[$i] = $i;
// Correct answers
if (in_array($key, $question_array['correct_answers'])) {
$answer->new_correct[$i] = 1;
} else {
$answer->new_correct[$i] = 0;
}
$answer->new_weighting[$i] = 0;
if (isset($question_array['weighting'][$key])) {
$answer->new_weighting[$i] = $question_array['weighting'][$key];
}
if ($answer->new_correct[$i]) {
$totalCorrectWeight += $answer->new_weighting[$i];
}
}
}
if ($question->type == FREE_ANSWER) {
$totalCorrectWeight = $question_array['weighting'][0];
}
if (!empty($question_array['default_weighting'])) {
$totalCorrectWeight = (float) $question_array['default_weighting'];
}
$question->updateWeighting($totalCorrectWeight);
$question->save($exercise);
$answer->save();
}
// delete the temp dir where the exercise was unzipped
my_delete($baseWorkDir.$uploadPath);
return $last_exercise_id;
}
return false;
}
/**
* We assume the file charset is UTF8.
*/
function formatText($text)
{
return api_html_entity_decode($text);
}
/**
* Parses a given XML file and fills global arrays with the elements.
*
* @param string $exercisePath
* @param string $file
* @param string $questionFile
*
* @return bool
*/
function qti_parse_file($exercisePath, $file, $questionFile)
{
global $record_item_body;
global $questionTempDir;
$questionTempDir = $exercisePath.'/'.$file.'/';
$questionFilePath = $questionTempDir.$questionFile;
if (!($fp = fopen($questionFilePath, 'r'))) {
Display::addFlash(Display::return_message(get_lang('Error opening question\'s XML file'), 'error'));
return false;
}
$data = fread($fp, filesize($questionFilePath));
//close file
fclose($fp);
//parse XML question file
//$data = str_replace(array('<p>', '</p>', '<front>', '</front>'), '', $data);
$data = ChamiloApi::stripGivenTags($data, ['p', 'front']);
$qtiVersion = [];
$match = preg_match('/ims_qtiasiv(\d)p(\d)/', $data, $qtiVersion);
$qtiMainVersion = 2; //by default, assume QTI version 2
if ($match) {
$qtiMainVersion = $qtiVersion[1];
}
//used global variable start values declaration:
$record_item_body = false;
if ($qtiMainVersion != 2) {
Display::addFlash(
Display::return_message(
get_lang('UnsupportedQtiVersion'),
'error'
)
);
return false;
}
parseQti2($data);
return true;
}
/**
* Function used to parser a QTI2 xml file.
*
* @param string $xmlData
*/
function parseQti2($xmlData)
{
global $exerciseInfo;
global $questionTempDir;
global $resourcesLinks;
$crawler = new Crawler($xmlData);
$nodes = $crawler->filter('*');
$currentQuestionIdent = '';
$currentAnswerId = '';
$currentQuestionItemBody = '';
$cardinality = '';
$nonHTMLTagToAvoid = [
'prompt',
'simpleChoice',
'choiceInteraction',
'inlineChoiceInteraction',
'inlineChoice',
'soMPLEMATCHSET',
'simpleAssociableChoice',
'textEntryInteraction',
'feedbackInline',
'matchInteraction',
'extendedTextInteraction',
'itemBody',
'br',
'img',
];
$currentMatchSet = null;
/** @var DOMElement $node */
foreach ($nodes as $node) {
if ('#text' === $node->nodeName) {
continue;
}
switch ($node->nodeName) {
case 'assessmentItem':
$currentQuestionIdent = $node->getAttribute('identifier');
$exerciseInfo['question'][$currentQuestionIdent] = [
'answer' => [],
'correct_answers' => [],
'title' => $node->getAttribute('title'),
'category' => $node->getAttribute('category'),
'type' => '',
'tempdir' => $questionTempDir,
'description' => null,
];
break;
case 'section':
$title = $node->getAttribute('title');
if (!empty($title)) {
$exerciseInfo['name'] = $title;
}
break;
case 'responseDeclaration':
if ('multiple' === $node->getAttribute('cardinality')) {
$exerciseInfo['question'][$currentQuestionIdent]['type'] = MCMA;
$cardinality = 'multiple';
}
if ('single' === $node->getAttribute('cardinality')) {
$exerciseInfo['question'][$currentQuestionIdent]['type'] = MCUA;
$cardinality = 'single';
}
$currentAnswerId = $node->getAttribute('identifier');
break;
case 'inlineChoiceInteraction':
$exerciseInfo['question'][$currentQuestionIdent]['type'] = FIB;
$exerciseInfo['question'][$currentQuestionIdent]['subtype'] = 'LISTBOX_FILL';
$currentAnswerId = $node->getAttribute('responseIdentifier');
break;
case 'inlineChoice':
$answerIdentifier = $exerciseInfo['question'][$currentQuestionIdent]['correct_answers'][$currentAnswerId];
if ($node->getAttribute('identifier') == $answerIdentifier) {
$currentQuestionItemBody = str_replace(
"**claroline_start**".$currentAnswerId."**claroline_end**",
"[".$node->nodeValue."]",
$currentQuestionItemBody
);
} else {
if (!isset($exerciseInfo['question'][$currentQuestionIdent]['wrong_answers'])) {
$exerciseInfo['question'][$currentQuestionIdent]['wrong_answers'] = [];
}
$exerciseInfo['question'][$currentQuestionIdent]['wrong_answers'][] = $node->nodeValue;
}
break;
case 'textEntryInteraction':
$exerciseInfo['question'][$currentQuestionIdent]['type'] = FIB;
$exerciseInfo['question'][$currentQuestionIdent]['subtype'] = 'TEXTFIELD_FILL';
$exerciseInfo['question'][$currentQuestionIdent]['response_text'] = $currentQuestionItemBody;
break;
case 'matchInteraction':
$exerciseInfo['question'][$currentQuestionIdent]['type'] = MATCHING;
break;
case 'extendedTextInteraction':
$exerciseInfo['question'][$currentQuestionIdent]['type'] = FREE_ANSWER;
$exerciseInfo['question'][$currentQuestionIdent]['description'] = $node->nodeValue;
break;
case 'simpleMatchSet':
if (!isset($currentMatchSet)) {
$currentMatchSet = 1;
} else {
$currentMatchSet++;
}
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentMatchSet] = [];
break;
case 'simpleAssociableChoice':
$currentAssociableChoice = $node->getAttribute('identifier');
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentMatchSet][$currentAssociableChoice] = trim($node->nodeValue);
break;
case 'simpleChoice':
$currentAnswerId = $node->getAttribute('identifier');
if (!isset($exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId])) {
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId] = [];
}
//$simpleChoiceValue = $node->nodeValue;
$simpleChoiceValue = '';
/** @var DOMElement $childNode */
foreach ($node->childNodes as $childNode) {
if ('feedbackInline' === $childNode->nodeName) {
continue;
}
$simpleChoiceValue .= $childNode->nodeValue;
}
$simpleChoiceValue = trim($simpleChoiceValue);
if (!isset($exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['value'])) {
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['value'] = $simpleChoiceValue;
} else {
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['value'] .= $simpleChoiceValue;
}
break;
case 'mapEntry':
if (in_array($node->parentNode->nodeName, ['mapping', 'mapEntry'])) {
$answer_id = $node->getAttribute('mapKey');
if (!isset($exerciseInfo['question'][$currentQuestionIdent]['weighting'])) {
$exerciseInfo['question'][$currentQuestionIdent]['weighting'] = [];
}
$exerciseInfo['question'][$currentQuestionIdent]['weighting'][$answer_id] = $node->getAttribute(
'mappedValue'
);
}
break;
case 'mapping':
$defaultValue = $node->getAttribute('defaultValue');
if (!empty($defaultValue)) {
$exerciseInfo['question'][$currentQuestionIdent]['default_weighting'] = $defaultValue;
}
// no break ?
case 'itemBody':
$nodeValue = $node->nodeValue;
$currentQuestionItemBody = '';
/** @var DOMElement $childNode */
foreach ($node->childNodes as $childNode) {
if ('#text' === $childNode->nodeName) {
continue;
}
if (!in_array($childNode->nodeName, $nonHTMLTagToAvoid)) {
$currentQuestionItemBody .= '<'.$childNode->nodeName;
if ($childNode->attributes) {
foreach ($childNode->attributes as $attribute) {
$currentQuestionItemBody .= ' '.$attribute->nodeName.'="'.$attribute->nodeValue.'"';
}
}
$currentQuestionItemBody .= '>'.$childNode->nodeValue.'</'.$node->nodeName.'>';
continue;
}
if ('inlineChoiceInteraction' === $childNode->nodeName) {
$currentQuestionItemBody .= "**claroline_start**".$childNode->attr('responseIdentifier')
."**claroline_end**";
continue;
}
if ('textEntryInteraction' === $childNode->nodeName) {
$correct_answer_value = $exerciseInfo['question'][$currentQuestionIdent]['correct_answers'][$currentAnswerId];
$currentQuestionItemBody .= "[".$correct_answer_value."]";
continue;
}
if ('br' === $childNode->nodeName) {
$currentQuestionItemBody .= '<br>';
}
}
// Replace relative links by links to the documents in the course
// $resourcesLinks is only defined by qtiProcessManifest()
if (isset($resourcesLinks) && isset($resourcesLinks['manifest']) && isset($resourcesLinks['web'])) {
foreach ($resourcesLinks['manifest'] as $key => $value) {
$nodeValue = preg_replace('|'.$value.'|', $resourcesLinks['web'][$key], $nodeValue);
}
}
$currentQuestionItemBody .= $node->firstChild->nodeValue;
if ($exerciseInfo['question'][$currentQuestionIdent]['type'] == FIB) {
$exerciseInfo['question'][$currentQuestionIdent]['response_text'] = $currentQuestionItemBody;
} else {
if ($exerciseInfo['question'][$currentQuestionIdent]['type'] == FREE_ANSWER) {
$currentQuestionItemBody = trim($currentQuestionItemBody);
if (!empty($currentQuestionItemBody)) {
$exerciseInfo['question'][$currentQuestionIdent]['description'] = $currentQuestionItemBody;
}
} else {
$exerciseInfo['question'][$currentQuestionIdent]['statement'] = $currentQuestionItemBody;
}
}
break;
case 'img':
$exerciseInfo['question'][$currentQuestionIdent]['attached_file_url'] = $node->getAttribute('src');
break;
case 'order':
$orderType = $node->getAttribute('order_type');
if (!empty($orderType)) {
$exerciseInfo['order_type'] = $orderType;
}
break;
case 'feedbackInline':
if (!isset($exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['feedback'])) {
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['feedback'] = trim(
$node->nodeValue
);
} else {
$exerciseInfo['question'][$currentQuestionIdent]['answer'][$currentAnswerId]['feedback'] .= trim(
$node->nodeValue
);
}
break;
case 'value':
if ('correctResponse' === $node->parentNode->nodeName) {
$nodeValue = trim($node->nodeValue);
if ('single' === $cardinality) {
$exerciseInfo['question'][$currentQuestionIdent]['correct_answers'][$nodeValue] = $nodeValue;
} else {
$exerciseInfo['question'][$currentQuestionIdent]['correct_answers'][] = $nodeValue;
}
}
if ('outcomeDeclaration' === $node->parentNode->parentNode->nodeName) {
$nodeValue = trim($node->nodeValue);
if (!empty($nodeValue)) {
$exerciseInfo['question'][$currentQuestionIdent]['weighting'][0] = $nodeValue;
}
}
break;
case 'mattext':
if ('flow_mat' === $node->parentNode->parentNode->nodeName &&
('presentation_material' === $node->parentNode->parentNode->parentNode->nodeName ||
'section' === $node->parentNode->parentNode->parentNode->nodeName
)
) {
$nodeValue = trim($node->nodeValue);
if (!empty($nodeValue)) {
$exerciseInfo['description'] = $node->nodeValue;
}
}
break;
case 'prompt':
$description = trim($node->nodeValue);
$description = htmlspecialchars_decode($description);
$description = Security::remove_XSS($description);
if (!empty($description)) {
$exerciseInfo['question'][$currentQuestionIdent]['description'] = $description;
}
break;
}
}
}
/**
* Check if a given file is an IMS/QTI question bank file.
*
* @param string $filePath The absolute filepath
*
* @return bool Whether it is an IMS/QTI question bank or not
*/
function isQtiQuestionBank($filePath)
{
$data = file_get_contents($filePath);
if (!empty($data)) {
$match = preg_match('/ims_qtiasiv(\d)p(\d)/', $data);
// @todo allow other types
//$match2 = preg_match('/imsqti_v(\d)p(\d)/', $data);
if ($match) {
return true;
}
}
return false;
}
/**
* Check if a given file is an IMS/QTI manifest file (listing of extra files).
*
* @param string $filePath The absolute filepath
*
* @return bool Whether it is an IMS/QTI manifest file or not
*/
function isQtiManifest($filePath)
{
$data = file_get_contents($filePath);
if (!empty($data)) {
$match = preg_match('/imsccv(\d)p(\d)/', $data);
if ($match) {
return true;
}
}
return false;
}
/**
* Processes an IMS/QTI manifest file: store links to new files
* to be able to transform them into the questions text.
*
* @param string $filePath The absolute filepath
*
* @return bool
*/
function qtiProcessManifest($filePath)
{
$xml = simplexml_load_file($filePath);
$course = api_get_course_info();
$sessionId = api_get_session_id();
$courseDir = $course['path'];
$sysPath = api_get_path(SYS_COURSE_PATH);
$exercisesSysPath = $sysPath.$courseDir.'/document/';
$webPath = api_get_path(WEB_CODE_PATH);
$exercisesWebPath = $webPath.'document/document.php?'.api_get_cidreq().'&action=download&id=';
$links = [
'manifest' => [],
'system' => [],
'web' => [],
];
$tableDocuments = Database::get_course_table(TABLE_DOCUMENT);
$countResources = count($xml->resources->resource->file);
for ($i = 0; $i < $countResources; $i++) {
$file = $xml->resources->resource->file[$i];
$href = '';
foreach ($file->attributes() as $key => $value) {
if ('href' == $key) {
if ('xml' != substr($value, -3, 3)) {
$href = $value;
}
}
}
if (!empty($href)) {
$links['manifest'][] = (string) $href;
$links['system'][] = $exercisesSysPath.strtolower($href);
$specialHref = Database::escape_string(preg_replace('/_/', '-', strtolower($href)));
$specialHref = preg_replace('/(-){2,8}/', '-', $specialHref);
$sql = "SELECT iid FROM $tableDocuments
WHERE
c_id = ".$course['real_id']." AND
session_id = $sessionId AND
path = '/".$specialHref."'";
$result = Database::query($sql);
$documentId = 0;
while ($row = Database::fetch_assoc($result)) {
$documentId = $row['iid'];
}
$links['web'][] = $exercisesWebPath.$documentId;
}
}
return $links;
}

View File

@@ -0,0 +1,117 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This script exports the PDF reports from a test for several students at once.
* This script is the teacher view of a similar script (for admins) at main/admin/export_exercise_results.php.
*/
require_once __DIR__.'/../../inc/global.inc.php';
// Setting the section (for the tabs).
$this_section = SECTION_COURSES;
api_protect_course_script(true);
if (!api_is_allowed_to_edit()) {
api_not_allowed(true);
}
$sessionId = api_get_session_id();
$courseId = api_get_course_int_id();
$exerciseId = isset($_REQUEST['exerciseId']) ? (int) $_REQUEST['exerciseId'] : null;
$exerciseIdChanged = isset($_GET['exercise_id_changed']) ? (int) $_GET['exercise_id_changed'] : null;
$courseInfo = [];
if (empty($courseId)) {
$exerciseId = 0;
} else {
$courseInfo = api_get_course_info_by_id($courseId);
}
$interbreadcrumb[] = ['url' => '../exercise.php?'.api_get_cidreq(), 'name' => get_lang('Exercises')];
$confirmYourChoice = addslashes(get_lang('ConfirmYourChoice'));
$htmlHeadXtra[] = "
<script>
function submit_form(obj) {
document.export_all_results_form.submit();
}
function mark_exercise_id_changed() {
$('#exercise_id_changed').val('0');
}
function confirm_your_choice() {
return confirm('$confirmYourChoice');
}
</script>";
// Get exercise list for this course
$exerciseList = ExerciseLib::get_all_exercises_for_course_id(
$courseInfo,
$sessionId,
$courseId,
false
);
$exerciseSelectList = [];
$exerciseSelectList = [0 => get_lang('All')];
if (is_array($exerciseList)) {
foreach ($exerciseList as $row) {
$exerciseTitle = $row['title'];
$exerciseSelectList[$row['iid']] = $exerciseTitle;
}
}
$url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query(
[
'session_id' => $sessionId,
'exerciseId' => $exerciseId,
'exercise_id_changed' => $exerciseIdChanged,
]
);
// Form
$form = new FormValidator('export_all_results_form', 'GET', $url);
$form->addHeader(get_lang('ExportExerciseAllResults'));
$form
->addSelect(
'exerciseId',
get_lang('Exercise'),
$exerciseSelectList
)
->setSelected($exerciseId);
$form->addDateTimePicker('start_date', get_lang('StartDate'));
$form->addDateTimePicker('end_date', get_lang('EndDate'));
$form->addRule('start_date', get_lang('InvalidDate'), 'datetime');
$form->addRule('end_date', get_lang('InvalidDate'), 'datetime');
$form->addRule(
['start_date', 'end_date'],
get_lang('StartDateShouldBeBeforeEndDate'),
'date_compare',
'lte'
);
$form->addHidden('exercise_id_changed', '0');
$form->addButtonExport(get_lang('Export'), 'name');
if ($form->validate()) {
$values = $form->getSubmitValues();
$exerciseId = (int) $values['exerciseId'];
$filterDates = [
'start_date' => (!empty($values['start_date']) ? $values['start_date'] : ''),
'end_date' => (!empty($values['end_date']) ? $values['end_date'] : ''),
];
if ($exerciseId === 0) {
ExerciseLib::exportAllExercisesResultsZip($sessionId, $courseId, $filterDates);
} else {
ExerciseLib::exportExerciseAllResultsZip($sessionId, $courseId, $exerciseId, $filterDates);
}
}
Display::display_header(get_lang('ExportExerciseAllResults'));
echo $form->display();
Display::display_footer();

View File

@@ -0,0 +1,11 @@
<?php
/* For licensing terms, see /license.txt */
/**
* @author Claro Team <cvs@claroline.net>
*/
/**
* Redirection.
*/
header('Location: ../../../');
exit();

View File

@@ -0,0 +1,471 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Interface ImsAnswerInterface.
*/
interface ImsAnswerInterface
{
/**
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '');
/**
* @param $questionIdent
*
* @return mixed
*/
public function imsExportResponsesDeclaration($questionIdent, Question $question = null);
}
/**
* @author Claro Team <cvs@claroline.net>
* @author Yannick Warnier <yannick.warnier@beeznest.com> -
* updated ImsAnswerHotspot to match QTI norms
*/
class Ims2Question extends Question
{
/**
* Include the correct answer class and create answer.
*
* @return Answer
*/
public function setAnswer()
{
switch ($this->type) {
case MCUA:
$answer = new ImsAnswerMultipleChoice($this->iid);
return $answer;
case MCMA:
case MULTIPLE_ANSWER_DROPDOWN:
case MULTIPLE_ANSWER_DROPDOWN_COMBINATION:
$answer = new ImsAnswerMultipleChoice($this->iid);
return $answer;
case TF:
$answer = new ImsAnswerMultipleChoice($this->iid);
return $answer;
case FIB:
$answer = new ImsAnswerFillInBlanks($this->iid);
return $answer;
case MATCHING:
case MATCHING_DRAGGABLE:
$answer = new ImsAnswerMatching($this->iid);
return $answer;
case FREE_ANSWER:
$answer = new ImsAnswerFree($this->iid);
return $answer;
case HOT_SPOT:
case HOT_SPOT_COMBINATION:
$answer = new ImsAnswerHotspot($this->iid);
return $answer;
default:
$answer = null;
break;
}
return $answer;
}
public function createAnswersForm($form)
{
return true;
}
public function processAnswersCreation($form, $exercise)
{
return true;
}
}
/**
* Class.
*/
class ImsAnswerMultipleChoice extends Answer implements ImsAnswerInterface
{
/**
* Return the XML flow for the possible answers.
*
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '')
{
// @todo getAnswersList() converts the answers using api_html_entity_decode()
$this->answerList = $this->getAnswersList(true);
$out = ' <choiceInteraction responseIdentifier="'.$questionIdent.'" >'."\n";
$out .= ' <prompt><![CDATA['.formatExerciseQtiText($questionDesc).']]></prompt>'."\n";
if (is_array($this->answerList)) {
foreach ($this->answerList as $current_answer) {
$out .= '<simpleChoice identifier="answer_'.$current_answer['iid'].'" fixed="false">
<![CDATA['.formatExerciseQtiText($current_answer['answer']).']]>';
if (isset($current_answer['comment']) && $current_answer['comment'] != '') {
$out .= '<feedbackInline identifier="answer_'.$current_answer['iid'].'">
<![CDATA['.formatExerciseQtiText($current_answer['comment']).']]>
</feedbackInline>';
}
$out .= '</simpleChoice>'."\n";
}
}
$out .= ' </choiceInteraction>'."\n";
return $out;
}
/**
* Return the XML flow of answer ResponsesDeclaration.
*/
public function imsExportResponsesDeclaration($questionIdent, Question $question = null)
{
$this->answerList = $this->getAnswersList(true);
$type = $this->getQuestionType();
if (in_array($type, [MCMA, MULTIPLE_ANSWER_DROPDOWN, MULTIPLE_ANSWER_DROPDOWN_COMBINATION])) {
$cardinality = 'multiple';
} else {
$cardinality = 'single';
}
$out = ' <responseDeclaration identifier="'.$questionIdent.'" cardinality="'.$cardinality.'" baseType="identifier">'."\n";
// Match the correct answers.
if (is_array($this->answerList)) {
$out .= ' <correctResponse>'."\n";
foreach ($this->answerList as $current_answer) {
if ($current_answer['correct']) {
$out .= ' <value>answer_'.$current_answer['iid'].'</value>'."\n";
}
}
$out .= ' </correctResponse>'."\n";
}
// Add the grading
if (is_array($this->answerList)) {
$out .= ' <mapping';
if (MULTIPLE_ANSWER_DROPDOWN_COMBINATION == $this->getQuestionType()) {
$out .= ' defaultValue="'.$question->selectWeighting().'"';
}
$out .= '>'."\n";
foreach ($this->answerList as $current_answer) {
if (isset($current_answer['grade'])) {
$out .= ' <mapEntry mapKey="answer_'.$current_answer['iid'].'" mappedValue="'.$current_answer['grade'].'" />'."\n";
}
}
$out .= ' </mapping>'."\n";
}
$out .= ' </responseDeclaration>'."\n";
return $out;
}
}
/**
* Class.
*
* @package chamilo.exercise
*/
class ImsAnswerFillInBlanks extends Answer implements ImsAnswerInterface
{
private $answerList = [];
private $gradeList = [];
/**
* Export the text with missing words.
*
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '')
{
$this->answerList = $this->getAnswersList(true);
$text = isset($this->answerText) ? $this->answerText : '';
if (is_array($this->answerList)) {
foreach ($this->answerList as $key => $answer) {
$key = $answer['iid'];
$answer = $answer['answer'];
$len = api_strlen($answer);
$text = str_replace('['.$answer.']', '<textEntryInteraction responseIdentifier="fill_'.$key.'" expectedLength="'.api_strlen($answer).'"/>', $text);
}
}
return $text;
}
public function imsExportResponsesDeclaration($questionIdent, Question $question = null)
{
$this->answerList = $this->getAnswersList(true);
$this->gradeList = $this->getGradesList();
$out = '';
if (is_array($this->answerList)) {
foreach ($this->answerList as $answer) {
$answerKey = $answer['iid'];
$answer = $answer['answer'];
$out .= ' <responseDeclaration identifier="fill_'.$answerKey.'" cardinality="single" baseType="identifier">'."\n";
$out .= ' <correctResponse>'."\n";
$out .= ' <value><![CDATA['.formatExerciseQtiText($answer).']]></value>'."\n";
$out .= ' </correctResponse>'."\n";
if (isset($this->gradeList[$answerKey])) {
$out .= ' <mapping>'."\n";
$out .= ' <mapEntry mapKey="'.$answer.'" mappedValue="'.$this->gradeList[$answerKey].'"/>'."\n";
$out .= ' </mapping>'."\n";
}
$out .= ' </responseDeclaration>'."\n";
}
}
return $out;
}
}
/**
* Class.
*
* @package chamilo.exercise
*/
class ImsAnswerMatching extends Answer implements ImsAnswerInterface
{
public $leftList = [];
public $rightList = [];
private $answerList = [];
/**
* Export the question part as a matrix-choice, with only one possible answer per line.
*
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '')
{
$this->answerList = $this->getAnswersList(true);
$maxAssociation = max(count($this->leftList), count($this->rightList));
$out = '<matchInteraction responseIdentifier="'.$questionIdent.'" maxAssociations="'.$maxAssociation.'">'."\n";
$out .= $questionStatment;
//add left column
$out .= ' <simpleMatchSet>'."\n";
if (is_array($this->leftList)) {
foreach ($this->leftList as $leftKey => $leftElement) {
$out .= '
<simpleAssociableChoice identifier="left_'.$leftKey.'" >
<![CDATA['.formatExerciseQtiText($leftElement['answer']).']]>
</simpleAssociableChoice>'."\n";
}
}
$out .= ' </simpleMatchSet>'."\n";
//add right column
$out .= ' <simpleMatchSet>'."\n";
$i = 0;
if (is_array($this->rightList)) {
foreach ($this->rightList as $rightKey => $rightElement) {
$out .= '<simpleAssociableChoice identifier="right_'.$i.'" >
<![CDATA['.formatExerciseQtiText($rightElement['answer']).']]>
</simpleAssociableChoice>'."\n";
$i++;
}
}
$out .= ' </simpleMatchSet>'."\n";
$out .= '</matchInteraction>'."\n";
return $out;
}
public function imsExportResponsesDeclaration($questionIdent, Question $question = null)
{
$this->answerList = $this->getAnswersList(true);
$out = ' <responseDeclaration identifier="'.$questionIdent.'" cardinality="single" baseType="identifier">'."\n";
$out .= ' <correctResponse>'."\n";
$gradeArray = [];
if (isset($this->leftList) && is_array($this->leftList)) {
foreach ($this->leftList as $leftKey => $leftElement) {
$i = 0;
foreach ($this->rightList as $rightKey => $rightElement) {
if (($leftElement['match'] == $rightElement['code'])) {
$out .= ' <value>left_'.$leftKey.' right_'.$i.'</value>'."\n";
$gradeArray['left_'.$leftKey.' right_'.$i] = $leftElement['grade'];
}
$i++;
}
}
}
$out .= ' </correctResponse>'."\n";
if (is_array($gradeArray)) {
$out .= ' <mapping>'."\n";
foreach ($gradeArray as $gradeKey => $grade) {
$out .= ' <mapEntry mapKey="'.$gradeKey.'" mappedValue="'.$grade.'"/>'."\n";
}
$out .= ' </mapping>'."\n";
}
$out .= ' </responseDeclaration>'."\n";
return $out;
}
}
/**
* Class.
*
* @package chamilo.exercise
*/
class ImsAnswerHotspot extends Answer implements ImsAnswerInterface
{
private $answerList = [];
private $gradeList = [];
/**
* @todo update this to match hot spots instead of copying matching
* Export the question part as a matrix-choice, with only one possible answer per line.
*
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '')
{
$this->answerList = $this->getAnswersList(true);
$mediaFilePath = api_get_course_path().'/document/images/'.$questionMedia;
$sysQuestionMediaPath = api_get_path(SYS_COURSE_PATH).$mediaFilePath;
$questionMedia = api_get_path(WEB_COURSE_PATH).$mediaFilePath;
$mimetype = mime_content_type($sysQuestionMediaPath);
if (empty($mimetype)) {
$mimetype = 'image/jpeg';
}
$text = ' <p>'.$questionStatment.'</p>'."\n";
$text .= ' <graphicOrderInteraction responseIdentifier="hotspot_'.$questionIdent.'">'."\n";
$text .= ' <prompt>'.$questionDesc.'</prompt>'."\n";
$text .= ' <object type="'.$mimetype.'" width="250" height="230" data="'.$questionMedia.'">-</object>'."\n";
if (is_array($this->answerList)) {
foreach ($this->answerList as $key => $answer) {
$key = $answer['iid'];
$answerTxt = $answer['answer'];
$len = api_strlen($answerTxt);
//coords are transformed according to QTIv2 rules here: http://www.imsproject.org/question/qtiv2p1pd/imsqti_infov2p1pd.html#element10663
$coords = '';
$type = 'default';
switch ($answer['hotspot_type']) {
case 'square':
$type = 'rect';
$res = [];
$coords = preg_match('/^\s*(\d+);(\d+)\|(\d+)\|(\d+)\s*$/', $answer['hotspot_coord'], $res);
$coords = $res[1].','.$res[2].','.((int) $res[1] + (int) $res[3]).",".((int) $res[2] + (int) $res[4]);
break;
case 'circle':
$type = 'circle';
$res = [];
$coords = preg_match('/^\s*(\d+);(\d+)\|(\d+)\|(\d+)\s*$/', $answer['hotspot_coord'], $res);
$coords = $res[1].','.$res[2].','.sqrt(pow(($res[1] - $res[3]), 2) + pow(($res[2] - $res[4])));
break;
case 'poly':
$type = 'poly';
$coords = str_replace([';', '|'], [',', ','], $answer['hotspot_coord']);
break;
case 'delineation':
$type = 'delineation';
$coords = str_replace([';', '|'], [',', ','], $answer['hotspot_coord']);
break;
}
$text .= ' <hotspotChoice shape="'.$type.'" coords="'.$coords.'" identifier="'.$key.'"/>'."\n";
}
}
$text .= ' </graphicOrderInteraction>'."\n";
return $text;
}
public function imsExportResponsesDeclaration($questionIdent, Question $question = null)
{
$this->answerList = $this->getAnswersList(true);
$this->gradeList = $this->getGradesList();
$out = ' <responseDeclaration identifier="hotspot_'.$questionIdent.'" cardinality="ordered" baseType="identifier">'."\n";
if (is_array($this->answerList)) {
$out .= ' <correctResponse>'."\n";
foreach ($this->answerList as $answerKey => $answer) {
$answerKey = $answer['iid'];
$answer = $answer['answer'];
$out .= '<value><![CDATA['.formatExerciseQtiText($answerKey).']]></value>';
}
$out .= ' </correctResponse>'."\n";
}
$out .= ' </responseDeclaration>'."\n";
return $out;
}
}
/**
* Class.
*
* @package chamilo.exercise
*/
class ImsAnswerFree extends Answer implements ImsAnswerInterface
{
/**
* @todo implement
* Export the question part as a matrix-choice, with only one possible answer per line.
*
* @param string $questionIdent
* @param string $questionStatment
* @param string $questionDesc
* @param string $questionMedia
*
* @return string
*/
public function imsExportResponses($questionIdent, $questionStatment, $questionDesc = '', $questionMedia = '')
{
$questionDesc = formatExerciseQtiText($questionDesc);
return '<extendedTextInteraction responseIdentifier="'.$questionIdent.'" >
<prompt>
'.$questionDesc.'
</prompt>
</extendedTextInteraction>';
}
public function imsExportResponsesDeclaration($questionIdent, Question $question = null)
{
$out = ' <responseDeclaration identifier="'.$questionIdent.'" cardinality="single" baseType="string">';
$out .= '<outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
<defaultValue><value>'.$question->weighting.'</value></defaultValue></outcomeDeclaration>';
$out .= ' </responseDeclaration>'."\n";
return $out;
}
}

View File

@@ -0,0 +1,515 @@
<?php
/* For licensing terms, see /license.txt */
/**
* @author Claro Team <cvs@claroline.net>
* @author Yannick Warnier <yannick.warnier@beeznest.com>
*/
require __DIR__.'/qti2_classes.php';
/**
* An IMS/QTI item. It corresponds to a single question.
* This class allows export from Claroline to IMS/QTI2.0 XML format of a single question.
* It is not usable as-is, but must be subclassed, to support different kinds of questions.
*
* Every start_*() and corresponding end_*(), as well as export_*() methods return a string.
*
* note: Attached files are NOT exported.
*/
class ImsAssessmentItem
{
/**
* @var Ims2Question
*/
public $question;
/**
* @var string
*/
public $questionIdent;
/**
* @var ImsAnswerInterface
*/
public $answer;
/**
* Constructor.
*
* @param Ims2Question $question ims2Question object we want to export
*/
public function __construct($question)
{
$this->question = $question;
$this->answer = $this->question->setAnswer();
$this->questionIdent = 'QST_'.$question->iid;
}
/**
* Start the XML flow.
*
* This opens the <item> block, with correct attributes.
*/
public function start_item()
{
$categoryTitle = '';
if (!empty($this->question->category)) {
$category = new TestCategory();
$category = $category->getCategory($this->question->category);
if ($category) {
$categoryTitle = htmlspecialchars(formatExerciseQtiText($category->name));
}
}
return '<assessmentItem xmlns="http://www.imsglobal.org/xsd/imsqti_v2p1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.imsglobal.org/xsd/imsqti_v2p1 imsqti_v2p1.xsd"
identifier="'.$this->questionIdent.'"
title = "'.htmlspecialchars(formatExerciseQtiText($this->question->selectTitle())).'"
category = "'.$categoryTitle.'"
>'."\n";
}
/**
* End the XML flow, closing the </item> tag.
*/
public function end_item()
{
return "</assessmentItem>\n";
}
/**
* Start the itemBody.
*/
public function start_item_body()
{
return ' <itemBody>'."\n";
}
/**
* End the itemBody part.
*/
public function end_item_body()
{
return " </itemBody>\n";
}
/**
* add the response processing template used.
*/
public function add_response_processing()
{
return ' <responseProcessing template="http://www.imsglobal.org/question/qti_v2p1/rptemplates/map_correct"/>'."\n";
}
/**
* Export the question as an IMS/QTI Item.
*
* This is a default behaviour, some classes may want to override this.
*
* @return string string, the XML flow for an Item
*/
public function export($standalone = false)
{
$head = $foot = '';
if ($standalone) {
$head = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'."\n";
}
//TODO understand why answer might be a non-object sometimes
if (!is_object($this->answer)) {
return $head;
}
return $head
.$this->start_item()
.$this->answer->imsExportResponsesDeclaration($this->questionIdent, $this->question)
.$this->start_item_body()
.$this->answer->imsExportResponses(
$this->questionIdent,
$this->question->question,
$this->question->description,
$this->question->getPictureFilename()
)
.$this->end_item_body()
.$this->add_response_processing()
.$this->end_item()
.$foot;
}
}
/**
* This class represents an entire exercise to be exported in IMS/QTI.
* It will be represented by a single <section> containing several <item>.
*
* Some properties cannot be exported, as IMS does not support them :
* - type (one page or multiple pages)
* - start_date and end_date
* - max_attempts
* - show_answer
* - anonymous_attempts
*
* @author Amand Tihon <amand@alrj.org>
*/
class ImsSection
{
public $exercise;
/**
* Constructor.
*
* @param Exercise $exe The Exercise instance to export
*
* @author Amand Tihon <amand@alrj.org>
*/
public function __construct($exe)
{
$this->exercise = $exe;
}
public function start_section()
{
return '<section
ident = "EXO_'.$this->exercise->selectId().'"
title = "'.cleanAttribute(formatExerciseQtiDescription($this->exercise->selectTitle())).'"
>'."\n";
}
public function end_section()
{
return "</section>\n";
}
public function export_duration()
{
if ($max_time = $this->exercise->selectTimeLimit()) {
// return exercise duration in ISO8601 format.
$minutes = floor($max_time / 60);
$seconds = $max_time % 60;
return '<duration>PT'.$minutes.'M'.$seconds."S</duration>\n";
} else {
return '';
}
}
/**
* Export the presentation (Exercise's description).
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export_presentation()
{
return "<presentation_material><flow_mat><material>\n"
.' <mattext><![CDATA['.formatExerciseQtiDescription($this->exercise->selectDescription())."]]></mattext>\n"
."</material></flow_mat></presentation_material>\n";
}
/**
* Export the ordering information.
* Either sequential, through all questions, or random, with a selected number of questions.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export_ordering()
{
$out = '';
if ($n = $this->exercise->getShuffle()) {
$out .= "<selection_ordering>"
." <selection>\n"
." <selection_number>".$n."</selection_number>\n"
." </selection>\n"
.' <order order_type="Random" />'
."\n</selection_ordering>\n";
} else {
$out .= '<selection_ordering sequence_type="Normal">'."\n"
." <selection />\n"
."</selection_ordering>\n";
}
return $out;
}
/**
* Export the questions, as a succession of <items>.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function exportQuestions()
{
$out = '';
foreach ($this->exercise->selectQuestionList() as $q) {
$out .= export_question_qti($q, false);
}
return $out;
}
/**
* Export the exercise in IMS/QTI.
*
* @param bool $standalone wether it should include XML tag and DTD line
*
* @return string string containing the XML flow
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export($standalone)
{
$head = $foot = '';
if ($standalone) {
$head = '<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?>'."\n"
.'<!DOCTYPE questestinterop SYSTEM "ims_qtiasiv2p1.dtd">'."\n"
."<questestinterop>\n";
$foot = "</questestinterop>\n";
}
return $head
.$this->start_section()
.$this->export_duration()
.$this->export_presentation()
.$this->export_ordering()
.$this->exportQuestions()
.$this->end_section()
.$foot;
}
}
/*
Some quick notes on identifiers generation.
The IMS format requires some blocks, like items, responses, feedbacks, to be uniquely
identified.
The unicity is mandatory in a single XML, of course, but it's prefered that the identifier stays
coherent for an entire site.
Here's the method used to generate those identifiers.
Question identifier :: "QST_" + <Question Id from the DB> + "_" + <Question numeric type>
Response identifier :: <Question identifier> + "_A_" + <Response Id from the DB>
Condition identifier :: <Question identifier> + "_C_" + <Response Id from the DB>
Feedback identifier :: <Question identifier> + "_F_" + <Response Id from the DB>
*/
/**
* Class ImsItem.
*
* An IMS/QTI item. It corresponds to a single question.
* This class allows export from Claroline to IMS/QTI XML format.
* It is not usable as-is, but must be subclassed, to support different kinds of questions.
*
* Every start_*() and corresponding end_*(), as well as export_*() methods return a string.
*
* warning: Attached files are NOT exported.
*
* @author Amand Tihon <amand@alrj.org>
*/
class ImsItem
{
public $question;
public $questionIdent;
public $answer;
/**
* Constructor.
*
* @param Question $question the Question object we want to export
*
* @author Anamd Tihon
*/
public function __construct($question)
{
$this->question = $question;
$this->answer = $question->answer;
$this->questionIdent = 'QST_'.$question->selectId();
}
/**
* Start the XML flow.
*
* This opens the <item> block, with correct attributes.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function start_item()
{
return '<item title="'.cleanAttribute(formatExerciseQtiDescription($this->question->selectTitle())).'" ident="'.$this->questionIdent.'">'."\n";
}
/**
* End the XML flow, closing the </item> tag.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function end_item()
{
return "</item>\n";
}
/**
* Create the opening, with the question itself.
*
* This means it opens the <presentation> but doesn't close it, as this is the role of end_presentation().
* In between, the export_responses from the subclass should have been called.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function start_presentation()
{
return '<presentation label="'.$this->questionIdent.'"><flow>'."\n"
.'<material><mattext>'.formatExerciseQtiDescription($this->question->selectDescription())."</mattext></material>\n";
}
/**
* End the </presentation> part, opened by export_header.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function end_presentation()
{
return "</flow></presentation>\n";
}
/**
* Start the response processing, and declare the default variable, SCORE, at 0 in the outcomes.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function start_processing()
{
return '<resprocessing><outcomes><decvar vartype="Integer" defaultval="0" /></outcomes>'."\n";
}
/**
* End the response processing part.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function end_processing()
{
return "</resprocessing>\n";
}
/**
* Export the question as an IMS/QTI Item.
*
* This is a default behaviour, some classes may want to override this.
*
* @param bool $standalone Boolean stating if it should be exported as a stand-alone question
*
* @return string string, the XML flow for an Item
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export($standalone = false)
{
global $charset;
$head = $foot = '';
if ($standalone) {
$head = '<?xml version = "1.0" encoding = "'.$charset.'" standalone = "no"?>'."\n"
.'<!DOCTYPE questestinterop SYSTEM "ims_qtiasiv2p1.dtd">'."\n"
."<questestinterop>\n";
$foot = "</questestinterop>\n";
}
return $head
.$this->start_item()
.$this->start_presentation()
.$this->answer->imsExportResponses($this->questionIdent)
.$this->end_presentation()
.$this->start_processing()
.$this->answer->imsExportProcessing($this->questionIdent)
.$this->end_processing()
.$this->answer->imsExportFeedback($this->questionIdent)
.$this->end_item()
.$foot;
}
}
/**
* Send a complete exercise in IMS/QTI format, from its ID.
*
* @param int $exerciseId The exercise to export
* @param bool $standalone wether it should include XML tag and DTD line
*
* @return string XML as a string, or an empty string if there's no exercise with given ID
*/
function export_exercise_to_qti($exerciseId, $standalone = true)
{
$exercise = new Exercise();
if (!$exercise->read($exerciseId)) {
return '';
}
$ims = new ImsSection($exercise);
return $ims->export($standalone);
}
/**
* Returns the XML flow corresponding to one question.
*
* @param int $questionId
* @param bool $standalone (ie including XML tag, DTD declaration, etc)
*
* @return string
*/
function export_question_qti($questionId, $standalone = true)
{
$question = new Ims2Question();
$qst = $question->read($questionId);
if (!$qst) {
return '';
}
$isValid = $qst instanceof UniqueAnswer
|| $qst instanceof MultipleAnswer
|| $qst instanceof FreeAnswer
|| $qst instanceof MultipleAnswerDropdown
|| $qst instanceof MultipleAnswerDropdownCombination
;
if (!$isValid) {
return '';
}
$question->iid = $qst->iid;
$question->type = $qst->type;
$question->question = $qst->question;
$question->description = $qst->description;
$question->weighting = $qst->weighting;
$question->position = $qst->position;
$question->picture = $qst->picture;
$question->category = $qst->category;
$ims = new ImsAssessmentItem($question);
return $ims->export($standalone);
}
/**
* Clean text like a description.
*/
function formatExerciseQtiDescription($text)
{
$entities = api_html_entity_decode($text);
return htmlspecialchars($entities);
}
/**
* Clean titles.
*
* @param $text
*
* @return string
*/
function formatExerciseQtiText($text)
{
return htmlspecialchars($text);
}
/**
* @param string $text
*
* @return string
*/
function cleanAttribute($text)
{
return $text;
}

View File

@@ -0,0 +1,79 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This class handles the SCORM export of fill-in-the-blanks questions.
*/
class ScormAnswerFillInBlanks extends Answer
{
/**
* Export the text with missing words.
*
* As a side effect, it stores two lists in the class :
* the missing words and their respective weightings.
*/
public function export()
{
$js = '';
// get all enclosed answers
$blankList = [];
foreach ($this->answer as $i => $answer) {
$blankList[] = '['.$answer.']';
}
// splits text and weightings that are joined with the character '::'
$listAnswerInfo = FillBlanks::getAnswerInfo($answer);
//$switchableAnswerSet = $listAnswerInfo['switchable'];
// display empty [input] with the right width for student to fill it
$answer = '';
$answerList = [];
for ($i = 0; $i < count($listAnswerInfo['common_words']) - 1; $i++) {
// display the common words
$answer .= $listAnswerInfo['common_words'][$i];
// display the blank word
$attributes['style'] = 'width:'.$listAnswerInfo['input_size'][$i].'px';
$answer .= FillBlanks::getFillTheBlankHtml(
$this->questionJSId,
$this->questionJSId + 1,
'',
$attributes,
$answer,
$listAnswerInfo,
true,
$i,
'question_'.$this->questionJSId.'_fib_'.($i + 1)
);
$answerList[] = $i + 1;
}
// display the last common word
$answer .= $listAnswerInfo['common_words'][$i];
// because [] is parsed here we follow this procedure:
// 1. find everything between the [ and ] tags
$jstmpw = 'questions_answers_ponderation['.$this->questionJSId.'] = new Array();'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][0] = 0;'."\n";
foreach ($listAnswerInfo['weighting'] as $key => $weight) {
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.']['.($key + 1).'] = '.$weight.";\n";
}
$wordList = "'".implode("', '", $listAnswerInfo['words'])."'";
$answerList = "'".implode("', '", $answerList)."'";
$html = '<tr><td colspan="2"><table width="100%">';
$html .= '<tr>
<td>
'.$answer.'
</td>
</tr></table></td></tr>';
$js .= 'questions_answers['.$this->questionJSId.'] = new Array('.$answerList.');'."\n";
$js .= 'questions_answers_correct['.$this->questionJSId.'] = new Array('.$wordList.');'."\n";
$js .= 'questions_types['.$this->questionJSId.'] = \'fib\';'."\n";
$js .= $jstmpw;
return [$js, $html];
}
}

View File

@@ -0,0 +1,98 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This class handles the SCORM export of matching questions.
*/
class ScormAnswerMatching extends Answer
{
/**
* Export the question part as a matrix-choice, with only one possible answer per line.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export()
{
$js = '';
// prepare list of right proposition to allow
// - easiest display
// - easiest randomisation if needed one day
// (here I use array_values to change array keys from $code1 $code2 ... to 0 1 ...)
// get max length of displayed array
$nbrAnswers = $this->selectNbrAnswers();
$counter = 1;
$questionId = $this->questionJSId;
$jstmpw = 'questions_answers_ponderation['.$questionId.'] = new Array();'."\n";
$jstmpw .= 'questions_answers_ponderation['.$questionId.'][0] = 0;'."\n";
// Options (A, B, C, ...) that will be put into the list-box
$options = [];
$letter = 'A';
for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
$answerCorrect = $this->isCorrect($answerId);
$answer = $this->selectAnswer($answerId);
$realAnswerId = $this->selectAutoId($answerId);
if (!$answerCorrect) {
$options[$realAnswerId]['Lettre'] = $letter;
// answers that will be shown at the right side
$options[$realAnswerId]['Reponse'] = $answer;
$letter++;
}
}
$html = [];
$jstmp = '';
$jstmpc = '';
// Answers
for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
$identifier = 'question_'.$questionId.'_matching_';
$answer = $this->selectAnswer($answerId);
$answerCorrect = $this->isCorrect($answerId);
$weight = $this->selectWeighting($answerId);
$jstmp .= $answerId.',';
if ($answerCorrect) {
$html[] = '<tr class="option_row">';
$html[] = '<td width="40%" valign="top">&nbsp;'.$answer.'</td>';
$html[] = '<td width="20%" align="center">&nbsp;&nbsp;';
$html[] = '<select name="'.$identifier.$counter.'" id="'.$identifier.$counter.'">';
$html[] = ' <option value="0">--</option>';
// fills the list-box
foreach ($options as $key => $val) {
$html[] = '<option value="'.$key.'">'.$val['Lettre'].'</option>';
}
$html[] = '</select>&nbsp;&nbsp;</td>';
$html[] = '<td width="40%" valign="top">';
foreach ($options as $key => $val) {
$html[] = '<b>'.$val['Lettre'].'.</b> '.$val['Reponse'].'<br />';
}
$html[] = '</td></tr>';
$jstmpc .= '['.$answerCorrect.','.$counter.'],';
$myWeight = explode('@', $weight);
if (2 == count($myWeight)) {
$weight = $myWeight[0];
} else {
$weight = $myWeight[0];
}
$jstmpw .= 'questions_answers_ponderation['.$questionId.']['.$counter.'] = '.$weight.";\n";
$counter++;
}
}
$js .= 'questions_answers['.$questionId.'] = new Array('.substr($jstmp, 0, -1).');'."\n";
$js .= 'questions_answers_correct['.$questionId.'] = new Array('.substr($jstmpc, 0, -1).');'."\n";
$js .= 'questions_types['.$questionId.'] = \'matching\';'."\n";
$js .= $jstmpw;
$htmlResult = '<tr><td colspan="2"><table id="question_'.$questionId.'" width="100%">';
$htmlResult .= implode("\n", $html);
$htmlResult .= '</table></td></tr>'."\n";
return [$js, $htmlResult];
}
}

View File

@@ -0,0 +1,118 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This class handles the export to SCORM of a multiple choice question
* (be it single answer or multiple answers).
*/
class ScormAnswerMultipleChoice extends Answer
{
/**
* Return HTML code for possible answers.
*/
public function export()
{
$js = [];
$type = $this->getQuestionType();
$questionId = $this->questionJSId;
$jstmpw = 'questions_answers_ponderation['.$questionId.'] = new Array();';
$jstmpw .= 'questions_answers_ponderation['.$questionId.'][0] = 0;';
$jstmpw .= 'questions_answers_correct['.$questionId.'] = new Array();';
$html = [];
//not sure if we are going to export also the MULTIPLE_ANSWER_COMBINATION to SCORM
//if ($type == MCMA || $type == MULTIPLE_ANSWER_COMBINATION ) {
if (MCMA == $type) {
$id = 1;
$jstmp = '';
$jstmpc = '';
foreach ($this->answer as $i => $answer) {
$identifier = 'question_'.$questionId.'_multiple_'.$i;
$html[] =
'<tr>
<td align="center" width="5%">
<input name="'.$identifier.'" id="'.$identifier.'" value="'.$i.'" type="checkbox" />
</td>
<td width="95%">
<label for="'.$identifier.'">'.Security::remove_XSS($this->answer[$i]).'</label>
</td>
</tr>';
$jstmp .= $i.',';
if ($this->correct[$i]) {
$jstmpc .= $i.',';
}
$jstmpw .= 'questions_answers_ponderation['.$questionId.']['.$i.'] = '.$this->weighting[$i].';';
$jstmpw .= 'questions_answers_correct['.$questionId.']['.$i.'] = '.$this->correct[$i].';';
$id++;
}
$js[] = 'questions_answers['.$questionId.'] = new Array('.substr($jstmp, 0, -1).');'."\n";
$js[] = 'questions_types['.$questionId.'] = \'mcma\';'."\n";
$js[] = $jstmpw;
} elseif (MULTIPLE_ANSWER_COMBINATION == $type) {
$js = [];
$id = 1;
$jstmp = '';
$jstmpc = '';
foreach ($this->answer as $i => $answer) {
$identifier = 'question_'.$questionId.'_exact_'.$i;
$html[] =
'<tr>
<td align="center" width="5%">
<input name="'.$identifier.'" id="'.$identifier.'" value="'.$i.'" type="checkbox" />
</td>
<td width="95%">
<label for="'.$identifier.'">'.Security::remove_XSS($this->answer[$i]).'</label>
</td>
</tr>';
$jstmp .= $i.',';
if ($this->correct[$i]) {
$jstmpc .= $i.',';
}
$jstmpw .= 'questions_answers_ponderation['.$questionId.']['.$i.'] = '.$this->weighting[$i].';';
$jstmpw .= 'questions_answers_correct['.$questionId.']['.$i.'] = '.$this->correct[$i].';';
$id++;
}
$js[] = 'questions_answers['.$questionId.'] = new Array('.substr($jstmp, 0, -1).');';
$js[] = 'questions_types['.$questionId.'] = "exact";';
$js[] = $jstmpw;
} else {
$id = 1;
$jstmp = '';
$jstmpc = '';
foreach ($this->answer as $i => $answer) {
$identifier = 'question_'.$questionId.'_unique_'.$i;
$identifier_name = 'question_'.$questionId.'_unique_answer';
$html[] =
'<tr>
<td align="center" width="5%">
<input name="'.$identifier_name.'" id="'.$identifier.'" value="'.$i.'" type="checkbox"/>
</td>
<td width="95%">
<label for="'.$identifier.'">'.Security::remove_XSS($this->answer[$i]).'</label>
</td>
</tr>';
$jstmp .= $i.',';
if ($this->correct[$i]) {
$jstmpc .= $i;
}
$jstmpw .= 'questions_answers_ponderation['.$questionId.']['.$i.'] = '.$this->weighting[$i].';';
$jstmpw .= 'questions_answers_correct['.$questionId.']['.$i.'] = '.$this->correct[$i].';';
$id++;
}
$js[] = 'questions_answers['.$questionId.'] = new Array('.substr($jstmp, 0, -1).');';
$js[] = 'questions_types['.$questionId.'] = \'mcua\';';
$js[] = $jstmpw;
}
$htmlResult = '<tr><td colspan="2"><table id="question_'.$questionId.'" width="100%">';
$htmlResult .= implode("\n", $html);
$htmlResult .= '</table></td></tr>';
$js = implode("\n", $js);
return [$js, $htmlResult];
}
}

View File

@@ -0,0 +1,55 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This class handles the SCORM export of true/false questions.
*/
class ScormAnswerTrueFalse extends Answer
{
/**
* Return the XML flow for the possible answers.
* That's one <response_lid>, containing several <flow_label>.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function export()
{
$js = '';
$html = '<tr><td colspan="2"><table width="100%">';
$identifier = 'question_'.$this->questionJSId.'_tf';
$identifier_true = $identifier.'_true';
$identifier_false = $identifier.'_false';
$html .=
'<tr>
<td align="center" width="5%">
<input name="'.$identifier_true.'" id="'.$identifier_true.'" value="'.$this->trueGrade.'" type="radio" />
</td>
<td width="95%">
<label for="'.$identifier_true.'">'.get_lang('True').'</label>
</td>
</tr>';
$html .=
'<tr>
<td align="center" width="5%">
<input name="'.$identifier_false.'" id="'.$identifier_false.'" value="'.$this->falseGrade.'" type="radio" />
</td>
<td width="95%">
<label for="'.$identifier_false.'">'.get_lang('False').'</label>
</td>
</tr></table></td></tr>';
$js .= 'questions_answers['.$this->questionJSId.'] = new Array(\'true\',\'false\');'."\n";
$js .= 'questions_types['.$this->questionJSId.'] = \'tf\';'."\n";
if ('TRUE' === $this->response) {
$js .= 'questions_answers_correct['.$this->questionJSId.'] = new Array(\'true\');'."\n";
} else {
$js .= 'questions_answers_correct['.$this->questionJSId.'] = new Array(\'false\');'."\n";
}
$jstmpw = 'questions_answers_ponderation['.$this->questionJSId.'] = new Array();'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][0] = 0;'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][1] = '.$this->weighting[1].";\n";
$js .= $jstmpw;
return [$js, $html];
}
}

View File

@@ -0,0 +1,159 @@
<?php
/* For licensing terms, see /license.txt */
/**
* A SCORM item. It corresponds to a single question.
* This class allows export from Chamilo SCORM 1.2 format of a single question.
* It is not usable as-is, but must be subclassed, to support different kinds of questions.
*
* Every start_*() and corresponding end_*(), as well as export_*() methods return a string.
*
* Attached files are NOT exported.
*/
class ScormAssessmentItem
{
public $question;
public $question_ident;
public $answer;
/**
* Constructor.
*
* @param ScormQuestion $question the Question object we want to export
*/
public function __construct($question)
{
$this->question = $question;
$this->question->setAnswer();
$this->questionIdent = 'QST_'.$question->iid;
}
/**
* Start the XML flow.
*
* This opens the <item> block, with correct attributes.
*/
public function start_page()
{
return '';
}
/**
* End the XML flow, closing the </item> tag.
*/
public function end_page()
{
/*if ($this->standalone) {
return '</html>';
}*/
return '';
}
/**
* Start document header.
*/
public function start_header()
{
/*if ($this->standalone) {
return '<head>';
}*/
return '';
}
/**
* Print CSS inclusion.
*/
public function css()
{
return '';
}
/**
* End document header.
*/
public function end_header()
{
// if ($this->standalone) {
// return '</head>';
// }
return '';
}
/**
* Start the itemBody.
*/
public function start_js()
{
return '<script type="text/javascript" src="assets/api_wrapper.js"></script>';
}
/**
* End the itemBody part.
*/
public function end_js()
{
/*if ($this->standalone) {
return '</script>';
}*/
return '';
}
/**
* Start the itemBody.
*/
public function start_body()
{
/*if ($this->standalone) {
return '<body><form id="dokeos_scorm_form" method="post" action="">';
}*/
return '';
}
/**
* End the itemBody part.
*/
public function end_body()
{
/*if ($this->standalone) {
return '<br /><input class="btn" type="button" id="dokeos_scorm_submit" name="dokeos_scorm_submit" value="OK" /></form></body>';
}*/
return '';
}
/**
* Export the question as a SCORM Item.
* This is a default behaviour, some classes may want to override this.
*
* @return string|array a string, the XML flow for an Item
*/
public function export()
{
list($js, $html) = $this->question->export();
/*if ($this->standalone) {
$res = $this->start_page()
.$this->start_header()
.$this->css()
.$this->start_js()
.$this->common_js()
.$js
.$this->end_js()
.$this->end_header()
.$this->start_body()
.$html
.$this->end_body()
.$this->end_page();
return $res;
} else {
return [$js, $html];
}*/
return [$js, $html];
}
}

View File

@@ -0,0 +1,216 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CourseBundle\Entity\CQuiz;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
/**
* This class represents an entire exercise to be exported in SCORM.
* It will be represented by a single <section> containing several <item>.
*
* Some properties cannot be exported, as SCORM does not support them :
* - type (one page or multiple pages)
* - start_date and end_date
* - max_attempts
* - show_answer
* - anonymous_attempts
*
* @author Julio Montoya
* @author Amand Tihon <amand@alrj.org>
*/
class ScormExercise
{
public $exercise;
public $standalone;
/**
* ScormExercise constructor.
*
* @param Exercise $exe
* @param bool $standalone
*/
public function __construct($exe, $standalone)
{
$this->exercise = $exe;
$this->standalone = $standalone;
}
/**
* Start the XML flow.
*
* This opens the <item> block, with correct attributes.
*/
public function startPage()
{
$charset = 'UTF-8';
return '<?xml version="1.0" encoding="'.$charset.'" standalone="no"?><html>';
}
/**
* End the XML flow, closing the </item> tag.
*/
public function end_page()
{
return '</html>';
}
/**
* Start document header.
*/
public function start_header()
{
return '<head>';
}
/**
* Common JS functions.
*/
public function common_js()
{
$js = file_get_contents(api_get_path(SYS_CODE_PATH).'exercise/export/scorm/common.js');
return $js."\n";
}
/**
* End the itemBody part.
*/
public function end_js()
{
return '</script>';
}
/**
* Start the itemBody.
*/
public function start_body()
{
return '<body>'.
'<h1>'.$this->exercise->selectTitle().'</h1><p>'.$this->exercise->selectDescription().'</p>'.
'<form id="chamilo_scorm_form" method="post" action="">'.
'<table width="100%">';
}
/**
* End the itemBody part.
*/
public function end_body()
{
$button = '<input
id="chamilo_scorm_submit"
class="btn btn-primary"
type="button"
name="chamilo_scorm_submit"
value="OK" />';
return '</table><br />'.$button.'</form></body>';
}
/**
* Export the question as a SCORM Item.
*
* This is a default behaviour, some classes may want to override this.
*
* @return string string, the XML flow for an Item
*/
public function export()
{
global $charset;
/*$head = '';
if ($this->standalone) {
$head = '<?xml version = "1.0" encoding = "'.$charset.'" standalone = "no"?>'."\n"
.'<!DOCTYPE questestinterop SYSTEM "ims_qtiasiv2p1.dtd">'."\n";
}*/
list($js, $html) = $this->exportQuestions();
return $this->startPage()
.$this->start_header()
.$this->css()
.$this->globalAssets()
.$this->start_js()
.$this->common_js()
.$js
.$this->end_js()
.$this->end_header()
.$this->start_body()
.$html
.$this->end_body()
.$this->end_page();
}
/**
* Export the questions, as a succession of <items>.
*
* @author Amand Tihon <amand@alrj.org>
*/
public function exportQuestions()
{
$js = $html = '';
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$em = Database::getManager();
// Export cquiz data
/** @var CQuiz $exercise */
$exercise = $em->find('ChamiloCourseBundle:CQuiz', $this->exercise->iid);
$exercise->setDescription('');
$exercise->setTextWhenFinished('');
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($exercise, 'json');
$js .= "var exerciseInfo = JSON.parse('".$jsonContent."');\n";
$counter = 0;
$scormQuestion = new ScormQuestion();
foreach ($this->exercise->selectQuestionList() as $q) {
list($jstmp, $htmltmp) = $scormQuestion->exportQuestionToScorm($q, $counter);
$js .= $jstmp."\n";
$html .= $htmltmp."\n";
$counter++;
}
return [$js, $html];
}
/**
* Print CSS inclusion.
*/
private function css()
{
return '';
}
/**
* End document header.
*/
private function end_header()
{
return '</head>';
}
/**
* Start the itemBody.
*/
private function start_js()
{
return '<script>';
}
/**
* @return string
*/
private function globalAssets()
{
$assets = '<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>'."\n";
$assets .= '<script type="text/javascript" src="assets/api_wrapper.js"></script>'."\n";
$assets .= '<link href="assets/bootstrap/bootstrap.min.css" rel="stylesheet" media="screen" type="text/css" />';
return $assets;
}
}

View File

@@ -0,0 +1,221 @@
<?php
/* For licensing terms, see /license.txt */
/**
* The ScormQuestion class is a gateway to getting the answers exported
* (the question is just an HTML text, while the answers are the most important).
* It is important to note that the SCORM export process is done in two parts.
* First, the HTML part (which is the presentation), and second the JavaScript
* part (the process).
* The two bits are separate to allow for a one-big-javascript and a one-big-html
* files to be built. Each export function thus returns an array of HTML+JS.
*
* @author Claro Team <cvs@claroline.net>
* @author Yannick Warnier <yannick.warnier@beeznest.com>
*/
class ScormQuestion extends Question
{
public $js_id;
public $answer;
/**
* ScormQuestion constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* Returns the HTML + JS flow corresponding to one question.
*
* @param int $questionId The question ID
* @param int $jsId The JavaScript ID for this question.
* Due to the nature of interactions, we must have a natural sequence for
* questions in the generated JavaScript.
*
* @return string|array
*/
public function exportQuestionToScorm(
$questionId,
$jsId
) {
$question = self::read($questionId);
if (!$question) {
return '';
}
$this->iid = $question->iid;
$this->js_id = $jsId;
$this->type = $question->type;
$this->question = $question->question;
$this->description = $question->description;
$this->weighting = $question->weighting;
$this->position = $question->position;
$this->picture = $question->picture;
$assessmentItem = new ScormAssessmentItem($this);
return $assessmentItem->export();
}
/**
* Include the correct answer class and create answer.
*/
public function setAnswer()
{
switch ($this->type) {
case MCUA:
$this->answer = new ScormAnswerMultipleChoice($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case MCMA:
case GLOBAL_MULTIPLE_ANSWER:
$this->answer = new ScormAnswerMultipleChoice($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case TF:
$this->answer = new ScormAnswerTrueFalse($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case FIB:
$this->answer = new ScormAnswerFillInBlanks($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case MATCHING:
case MATCHING_DRAGGABLE:
case DRAGGABLE:
$this->answer = new ScormAnswerMatching($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case ORAL_EXPRESSION:
case FREE_ANSWER:
$this->answer = new ScormAnswerFree($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case HOT_SPOT:
case HOT_SPOT_COMBINATION:
$this->answer = new ScormAnswerHotspot($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case MULTIPLE_ANSWER_COMBINATION:
$this->answer = new ScormAnswerMultipleChoice($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case HOT_SPOT_ORDER:
$this->answer = new ScormAnswerHotspot($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
case HOT_SPOT_DELINEATION:
$this->answer = new ScormAnswerHotspot($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
// not supported
case UNIQUE_ANSWER_NO_OPTION:
case MULTIPLE_ANSWER_TRUE_FALSE:
case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
case UNIQUE_ANSWER_IMAGE:
case CALCULATED_ANSWER:
$this->answer = new ScormAnswerMultipleChoice($this->iid);
$this->answer->questionJSId = $this->js_id;
break;
default:
$this->answer = new stdClass();
$this->answer->questionJSId = $this->js_id;
break;
}
return true;
}
/**
* @throws Exception
*
* @return array
*/
public function export()
{
$html = $this->getQuestionHTML();
$js = $this->getQuestionJS();
if (is_object($this->answer) && $this->answer instanceof Answer) {
list($js2, $html2) = $this->answer->export();
$js .= $js2;
$html .= $html2;
} else {
throw new \Exception('Question not supported. Exercise: '.$this->selectTitle());
}
return [$js, $html];
}
/**
* {@inheritdoc}
*/
public function createAnswersForm($form)
{
return true;
}
/**
* {@inheritdoc}
*/
public function processAnswersCreation($form, $exercise)
{
return true;
}
/**
* Returns an HTML-formatted question.
*/
public function getQuestionHTML()
{
$title = $this->selectTitle();
$description = $this->selectDescription();
$cols = 2;
return '<tr>
<td colspan="'.$cols.'" id="question_'.$this->iid.'_title" valign="middle" style="background-color:#d6d6d6;">
'.$title.'
</td>
</tr>
<tr>
<td valign="top" colspan="'.$cols.'">
<i>'.$description.'</i>
</td>
</tr>';
}
/**
* Return the JavaScript code bound to the question.
*/
public function getQuestionJS()
{
$weight = $this->selectWeighting();
$js = '
questions.push('.$this->js_id.');
$(function() {
if (exerciseInfo.randomAnswers == true) {
$("#question_'.$this->js_id.'").shuffleRows();
}
});';
$js .= "\n";
switch ($this->type) {
case ORAL_EXPRESSION:
/*$script = file_get_contents(api_get_path(LIBRARY_PATH) . 'javascript/rtc/RecordRTC.js');
$script .= file_get_contents(api_get_path(LIBRARY_PATH) . 'wami-recorder/recorder.js');
$script .= file_get_contents(api_get_path(LIBRARY_PATH) . 'wami-recorder/gui.js');
$js .= $script;*/
break;
case HOT_SPOT:
case HOT_SPOT_COMBINATION:
//put the max score to 0 to avoid discounting the points of
//non-exported quiz types in the SCORM
$weight = 0;
break;
}
$js .= 'questions_score_max['.$this->js_id.'] = '.$weight.';';
return $js;
}
}

View File

@@ -0,0 +1,25 @@
var questions = new Array();
var questions_answers = new Array();
var questions_answers_correct = new Array();
var questions_types = new Array();
var questions_score_max = new Array();
var questions_answers_ponderation = new Array();
/**
* Adds the event listener
*/
function addListeners(e) {
loadPage();
var myButton = document.getElementById('chamilo_scorm_submit');
addEvent(myButton, 'click', doQuit, false);
addEvent(myButton, 'click', disableButton, false);
addEvent(window, 'unload', unloadPage, false);
}
/** Disables the submit button on SCORM result submission **/
function disableButton() {
var mybtn = document.getElementById('chamilo_scorm_submit');
mybtn.setAttribute('disabled', 'disabled');
}
addEvent(window,'load', addListeners, false);

View File

@@ -0,0 +1,144 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This class handles the SCORM export of free-answer questions.
*/
class ScormAnswerFree extends Answer
{
/**
* Export the text with missing words.
*
* As a side effect, it stores two lists in the class :
* the missing words and their respective weightings.
*/
public function export()
{
$js = '';
$identifier = 'question_'.$this->questionJSId.'_free';
// currently the free answers cannot be displayed, so ignore the textarea
$html = '<tr><td colspan="2">';
$type = $this->getQuestionType();
if (ORAL_EXPRESSION == $type) {
/*
$template = new Template('');
$template->assign('directory', '/tmp/');
$template->assign('user_id', api_get_user_id());
$layout = $template->get_template('document/record_audio.tpl');
$html .= $template->fetch($layout);*/
$html = '<tr><td colspan="2">'.get_lang('ThisItemIsNotExportable').'</td></tr>';
return [$js, $html];
}
$html .= '<textarea minlength="20" name="'.$identifier.'" id="'.$identifier.'" ></textarea>';
$html .= '</td></tr>';
$js .= 'questions_answers['.$this->questionJSId.'] = new Array();';
$js .= 'questions_answers_correct['.$this->questionJSId.'] = "";';
$js .= 'questions_types['.$this->questionJSId.'] = \'free\';';
$jstmpw = 'questions_answers_ponderation['.$this->questionJSId.'] = "0";';
$js .= $jstmpw;
return [$js, $html];
}
}
/**
* This class handles the SCORM export of hotpot questions.
*/
class ScormAnswerHotspot extends Answer
{
/**
* Returns the javascript code that goes with HotSpot exercises.
*
* @return string The JavaScript code
*/
public function get_js_header()
{
$header = '<script>';
$header .= file_get_contents(api_get_path(SYS_CODE_PATH).'inc/lib/javascript/hotspot/js/hotspot.js');
$header .= '</script>';
if ($this->standalone) {
//because this header closes so many times the <script> tag, we have to reopen our own
$header .= '<script>';
$header .= 'questions_answers['.$this->questionJSId.'] = new Array();'."\n";
$header .= 'questions_answers_correct['.$this->questionJSId.'] = new Array();'."\n";
$header .= 'questions_types['.$this->questionJSId.'] = \'hotspot\';'."\n";
$jstmpw = 'questions_answers_ponderation['.$this->questionJSId.'] = new Array();'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][0] = 0;'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][1] = 0;'.";\n";
$header .= $jstmpw;
} else {
$header = '';
$header .= 'questions_answers['.$this->questionJSId.'] = new Array();'."\n";
$header .= 'questions_answers_correct['.$this->questionJSId.'] = new Array();'."\n";
$header .= 'questions_types['.$this->questionJSId.'] = \'hotspot\';'."\n";
$jstmpw = 'questions_answers_ponderation['.$this->questionJSId.'] = new Array();'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][0] = 0;'."\n";
$jstmpw .= 'questions_answers_ponderation['.$this->questionJSId.'][1] = 0;'."\n";
$header .= $jstmpw;
}
return $header;
}
/**
* Export the text with missing words.
*
* As a side effect, it stores two lists in the class :
* the missing words and their respective weightings.
*/
public function export()
{
$js = $this->get_js_header();
$html = '<tr><td colspan="2"><table width="100%">';
// some javascript must be added for that kind of questions
$html .= '';
// Get the answers, make a list
$nbrAnswers = $this->selectNbrAnswers();
$answerList = '<div
style="padding: 10px;
margin-left: -8px;
border: 1px solid #4271b5;
height: 448px;
width: 200px;"><b>'.get_lang('HotspotZones').'</b><ol>';
for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
$answerList .= '<li>'.$this->selectAnswer($answerId).'</li>';
}
$answerList .= '</ol></div>';
$relPath = api_get_path(REL_PATH);
$html .= <<<HTML
<tr>
<td>
<div id="hotspot-{$this->questionJSId}"></div>
<script>
document.addEventListener('DOMContentListener', function () {
new HotspotQuestion({
questionId: {$this->questionJSId},
selector: '#hotspot-{$this->questionJSId}',
for: 'user',
relPath: '$relPath'
});
});
</script>
</td>
<td>
$answerList
</td>
<tr>
HTML;
$html .= '</table></td></tr>';
// currently the free answers cannot be displayed, so ignore the textarea
$html = '<tr><td colspan="2">'.get_lang('ThisItemIsNotExportable').'</td></tr>';
return [$js, $html];
}
}