@ -43,6 +43,106 @@ function aiken_display_form()
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')) {
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('Topic'));
$form->addRule('quiz_name', get_lang('ThisFieldIsRequired'), 'required');
$form->addElement('number', 'nro_questions', get_lang('NumberOfQuestions'));
$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);
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);
$("#textarea-aiken").focus();
} else {
alert("'.get_lang('NoSearchResults').'. '.get_lang('PleaseTryAgain').'");
}
});
}
});
});
< / 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', '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.
*
@ -108,208 +208,201 @@ function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
* Main function to import the Aiken exercise.
*
* @param string $file
* @param array $request
*
* @return mixed True on success, error message on failure
*/
function aiken_import_exercise($file )
function aikenImportExercise($file = null, $request = [] )
{
$archive_path = api_get_path(SYS_ARCHIVE_PATH).'aiken/';
$baseWorkDir = $archive_path;
$exerciseInfo = [];
$uploadPath = 'aiken_'.api_get_unique_id();
if (!is_dir($baseWorkDir.$uploadPath)) {
mkdir($baseWorkDir.$uploadPath, api_get_permissions_for_new_directories(), true) ;
}
if (isset($file)) {
// The import is from aiken file format.
$archivePath = api_get_path(SYS_ARCHIVE_PATH).'aiken/' ;
$baseWorkDir = $archivePath;
// set some default values for the new exercise
$exercise_info = [];
$exercise_info['name'] = preg_replace('/.(zip|txt)$/i', '', $fil e);
$exercise_info['question'] = [];
$uploadPath = 'aiken_'.api_get_unique_id();
if (!is_dir($baseWorkDir.$uploadPath)) {
mkdir($baseWorkDir.$uploadPath, api_get_permissions_for_new_directories(), tru e);
}
// if file is not a .zip, then we cancel all
if (!preg_match('/.(zip|txt)$/i', $file)) {
return 'YouMustUploadAZipOrTxtFile';
}
// set some default values for the new exercise
$exerciseInfo['name'] = preg_replace('/.(zip|txt)$/i', '', $file);
$exerciseInfo['question'] = [];
// 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';
// 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);
$file_found = 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(
$exercise_info,
$baseWorkDir,
$file,
$questionFile
);
$file_found = true;
// 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;
}
} elseif (preg_match('/.txt$/i', $file)) {
$result = aiken_parse_file($exercise_info, $baseWorkDir.$uploadPath, '', $file);
$file_found = true;
}
}
if (!$file_f ound) {
$result = 'NoTxtFileFoundInTheZip';
}
if (!$fileFound) {
$result = 'NoTxtFileFoundInTheZip';
}
if (true !== $result) {
return $result;
if (true !== $result) {
return $result;
}
} elseif (!empty($request)) {
// The import is from aiken generated in textarea.
$exerciseInfo['name'] = $request['quiz_name'];
$exerciseInfo['question'] = [];
setExerciseInfoFromAikenText($request['aiken_format'], $exerciseInfo);
}
// 1. Create exercise.
$exercise = new Exercise();
$exercise->exercise = $exercise_info['name'];
$exercise->save();
$last_exercise_id = $exercise->selectId();
$tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
$tableAnswer = Database::get_course_table(TABLE_QUIZ_ANSWER);
if (!empty($last_exercise_id)) {
$courseId = api_get_course_int_id();
foreach ($exercise_info['question'] as $key => $question_array) {
// 2. Create question.
$question = new Aiken2Question();
$question->type = $question_array['type'];
$question->setAnswer();
$question->updateTitle($question_array['title']);
if (isset($question_array['description'])) {
$question->updateDescription($question_array['description']);
}
$type = $question->selectType();
$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 = count($question_array['answer']);
$max_score = 0;
$scoreFromFile = 0;
if (isset($question_array['score']) & & !empty($question_array['score'])) {
$scoreFromFile = $question_array['score'];
}
if (!empty($exerciseInfo)) {
$exercise = new Exercise();
$exercise->exercise = $exerciseInfo['name'];
$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 = api_get_course_int_id();
foreach ($exerciseInfo['question'] as $key => $questionArray) {
// 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->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 = count($questionArray['answer']);
$max_score = 0;
$scoreFromFile = 0;
if (isset($questionArray['score']) & & !empty($questionArray['score'])) {
$scoreFromFile = $questionArray['score'];
}
foreach ($question_array['answer'] as $key => $answers) {
$key++;
$answer->new_answer[$key] = $answers['value'];
$answer->new_position[$key] = $key;
$answer->new_comment[$key] = '';
// Correct answers ...
if (isset($question_array['correct_answers']) & &
in_array($key, $question_array['correct_answers'])
) {
$answer->new_correct[$key] = 1;
if (isset($question_array['feedback'])) {
$answer->new_comment[$key] = $question_array['feedback'];
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;
}
} else {
$answer->new_correct[$key] = 0;
}
if (isset($question_a rray['weighting'][$key - 1])) {
$answer->new_weighting[$key] = $question_a rray['weighting'][$key - 1];
$max_score += $question_a rray['weighting'][$key - 1];
}
if (isset($questionArray['weighting'][$key - 1])) {
$answer->new_weighting[$key] = $questionArray['weighting'][$key - 1];
$max_score += $questionA rray['weighting'][$key - 1];
}
if (!empty($scoreFromFile) & & $answer->new_correct[$key]) {
$answer->new_weighting[$key] = $scoreFromFile;
}
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,
'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' => '',
];
Database::update($tableAnswer, $params, ['iid = ?' => [$answerId]]);
$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;
if (!empty($scoreFromFile)) {
$max_score = $scoreFromFile;
}
$params = ['ponderation' => $max_score];
Database::update(
$tableQuestion,
$params,
['iid = ?' => [$last_question_id]]
);
}
$params = ['ponderation' => $max_score];
Database::update(
$tableQuestion,
$params,
['iid = ?' => [$last_question_id]]
);
}
// Delete the temp dir where the exercise was unzipped
my_delete($baseWorkDir.$uploadPath);
$operation = $last_exercise_id;
// Delete the temp dir where the exercise was unzipped
my_delete($baseWorkDir.$uploadPath);
return $lastExerciseId;
}
}
return $operation ;
return false ;
}
/**
* 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
* Set the exercise information from an aiken text formatted.
*/
function aiken_parse_file(& $exercise_info, $exercisePath, $file, $questionFile )
function setExerciseInfoFromAikenText($aikenText, & $exerciseInfo)
{
$questionTempDir = $exercisePath.'/'.$file.'/';
$questionFilePath = $questionTempDir.$questionFile;
if (!is_file($questionFilePath)) {
return 'FileNotFound';
}
$text = file_get_contents($questionFilePath);
$detect = mb_detect_encoding($text, 'ASCII', true);
$detect = mb_detect_encoding($aikenText, 'ASCII', true);
if ('ASCII' === $detect) {
$data = explode("\n", $t ext);
$data = explode("\n", $aikenText);
} else {
$text = str_ireplace(["\x0D", "\r\n"], "\n", $t ext); // Removes ^M char from win files.
$text = str_ireplace(["\x0D", "\r\n"], "\n", $aikenText); // Removes ^M char from win files.
$data = explode("\n\n", $text);
}
$question_i ndex = 0;
$answers_a rray = [];
$questionIndex = 0;
$answersA rray = [];
foreach ($data as $line => $info) {
$info = trim($info);
if (empty($info)) {
@ -320,117 +413,121 @@ function aiken_parse_file(&$exercise_info, $exercisePath, $file, $questionFile)
if (!mb_check_encoding($info, 'utf-8') & & mb_check_encoding($info, 'iso-8859-1')) {
$info = utf8_encode($info);
}
$exercise_info['question'][$question_i ndex]['type'] = 'MCUA';
$exerciseInfo['question'][$questionI ndex]['type'] = 'MCUA';
if (preg_match('/^([A-Za-z])(\)|\.)\s(.*)/', $info, $matches)) {
//adding one of the possible answers
$exercise_info['question'][$question_i ndex]['answer'][]['value'] = $matches[3];
$answers_a rray[] = $matches[1];
$exerciseInfo['question'][$questionI ndex]['answer'][]['value'] = $matches[3];
$answersA rray[] = $matches[1];
} elseif (preg_match('/^ANSWER:\s?([A-Z])\s?/', $info, $matches)) {
//the correct answers
$correct_answer_index = array_search($matches[1], $answers_a rray);
$exercise_info['question'][$question_index]['correct_answers'][] = $correct_answer_i ndex + 1;
$correctAnswerIndex = array_search($matches[1], $answersA rray);
$exerciseInfo['question'][$questionIndex]['correct_answers'][] = $correctAnswerI ndex + 1;
//weight for correct answer
$exercise_info['question'][$question_index]['weighting'][$correct_answer_i ndex] = 1;
$exerciseInfo['question'][$questionIndex]['weighting'][$correctAnswerI ndex] = 1;
$next = $line + 1;
if (false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
if (isset($data[$next]) & & false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
continue;
}
if (false !== strpos($data[$next], 'DESCRIPTION:')) {
if (isset($data[$next]) & & false !== strpos($data[$next], 'DESCRIPTION:')) {
continue;
}
// Check if next has score, otherwise loop too next question.
if (false === strpos($data[$next], 'SCORE:')) {
$answers_a rray = [];
$question_i ndex++;
if (isset($data[$next]) & & false === strpos($data[$next], 'SCORE:')) {
$answersA rray = [];
$questionI ndex++;
continue;
}
} elseif (preg_match('/^SCORE:\s?(.*)/', $info, $matches)) {
$exercise_info['question'][$question_i ndex]['score'] = (float) $matches[1];
$answers_a rray = [];
$question_i ndex++;
$exerciseInfo['question'][$questionI ndex]['score'] = (float) $matches[1];
$answersA rray = [];
$questionI ndex++;
continue;
} elseif (preg_match('/^DESCRIPTION:\s?(.*)/', $info, $matches)) {
$exercise_info['question'][$question_i ndex]['description'] = $matches[1];
$exerciseInfo['question'][$questionI ndex]['description'] = $matches[1];
$next = $line + 1;
if (false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
if (isset($data[$next]) & & false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
continue;
}
// Check if next has score, otherwise loop too next question.
if (false === strpos($data[$next], 'SCORE:')) {
$answers_a rray = [];
$question_i ndex++;
if (isset($data[$next]) & & false === strpos($data[$next], 'SCORE:')) {
$answersA rray = [];
$questionI ndex++;
continue;
}
} elseif (preg_match('/^ANSWER_EXPLANATION:\s?(.*)/', $info, $matches)) {
// Comment of correct answer
$correct_answer_index = array_search($matches[1], $answers_a rray);
$exercise_info['question'][$question_i ndex]['feedback'] = $matches[1];
$correctAnswerIndex = array_search($matches[1], $answersA rray);
$exerciseInfo['question'][$questionI ndex]['feedback'] = $matches[1];
$next = $line + 1;
// Check if next has score, otherwise loop too next question.
if (false === strpos($data[$next], 'SCORE:')) {
$answers_a rray = [];
$question_i ndex++;
if (isset($data[$next]) & & false === strpos($data[$next], 'SCORE:')) {
$answersA rray = [];
$questionI ndex++;
continue;
}
} elseif (preg_match('/^TEXTO_CORRECTA:\s?(.*)/', $info, $matches)) {
//Comment of correct answer (Spanish e-ducativa format)
$correct_answer_index = array_search($matches[1], $answers_a rray);
$exercise_info['question'][$question_i ndex]['feedback'] = $matches[1];
$correctAnswerIndex = array_search($matches[1], $answersA rray);
$exerciseInfo['question'][$questionI ndex]['feedback'] = $matches[1];
} elseif (preg_match('/^T:\s?(.*)/', $info, $matches)) {
//Question Title
$correct_answer_index = array_search($matches[1], $answers_a rray);
$exercise_info['question'][$question_i ndex]['title'] = $matches[1];
$correctAnswerIndex = array_search($matches[1], $answersA rray);
$exerciseInfo['question'][$questionI ndex]['title'] = $matches[1];
} elseif (preg_match('/^TAGS:\s?([A-Z])\s?/', $info, $matches)) {
//TAGS for chamilo >= 1.10
$exercise_info['question'][$question_i ndex]['answer_tags'] = explode(',', $matches[1]);
$exerciseInfo['question'][$questionI ndex]['answer_tags'] = explode(',', $matches[1]);
} elseif (preg_match('/^ETIQUETAS:\s?([A-Z])\s?/', $info, $matches)) {
//TAGS for chamilo >= 1.10 (Spanish e-ducativa format)
$exercise_info['question'][$question_index]['answer_tags'] = explode(',', $matches[1]);
} elseif (empty($info)) {
/*if (empty($exercise_info['question'][$question_index]['title'])) {
$exercise_info['question'][$question_index]['title'] = $info;
}
//moving to next question (tolerate \r\n or just \n)
if (empty($exercise_info['question'][$question_index]['correct_answers'])) {
error_log('Aiken: Error in question index '.$question_index.': no correct answer defined');
return 'ExerciseAikenErrorNoCorrectAnswerDefined';
}
if (empty($exercise_info['question'][$question_index]['answer'])) {
error_log('Aiken: Error in question index '.$question_index.': no answer option given');
return 'ExerciseAikenErrorNoAnswerOptionGiven';
}
$question_index++;
//emptying answers array when moving to next question
$answers_array = [];
//$new_question = true;*/
$exerciseInfo['question'][$questionIndex]['answer_tags'] = explode(',', $matches[1]);
} else {
if (empty($exercise_info['question'][$question_i ndex]['title'])) {
$exercise_info['question'][$question_i ndex]['title'] = $info;
if (empty($exerciseInfo['question'][$questionIndex]['title'])) {
$exerciseInfo['question'][$questionIndex]['title'] = $info;
}
/*$question_index++;
//emptying answers array when moving to next question
$answers_array = [];
$new_question = true;*/
}
}
$total_questions = count($exercise_i nfo['question']);
$total_w eight = !empty($_POST['total_weight']) ? (int) ($_POST['total_weight']) : 20;
foreach ($exercise_i nfo['question'] as $key => $question) {
if (!isset($exercise_i nfo['question'][$key]['weighting'])) {
$totalQuestions = count($exerciseInfo['question']);
$totalWeight = !empty($_POST['total_weight']) ? (int) ($_POST['total_weight']) : 20;
foreach ($exerciseInfo['question'] as $key => $question) {
if (!isset($exerciseInfo['question'][$key]['weighting'])) {
continue;
}
$exercise_info['question'][$key]['weighting'][current(array_keys($exercise_info['question'][$key]['weighting']))] = $total_weight / $total_q uestions;
$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);
//exit;
return true;
}
@ -451,7 +548,7 @@ function aiken_import_file($array_file)
}
if ($process & & $unzip == 1) {
$imported = aiken_import_e xercise($array_file['name']);
$imported = aikenImportE xercise($array_file['name']);
if (is_numeric($imported) & & !empty($imported)) {
Display::addFlash(Display::return_message(get_lang('Uploaded')));