aiken_import.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Library for the import of Aiken format
  5. * @author claro team <cvs@claroline.net>
  6. * @author Guillaume Lederer <guillaume@claroline.net>
  7. * @author César Perales <cesar.perales@gmail.com> Parse function for Aiken format
  8. * @package chamilo.exercise
  9. */
  10. /**
  11. * Security check
  12. */
  13. if (count(get_included_files()) == 1)
  14. die('---');
  15. /**
  16. * Creates a temporary directory
  17. * @param $dir
  18. * @param string $prefix
  19. * @param int $mode
  20. * @return string
  21. */
  22. function tempdir($dir, $prefix = 'tmp', $mode = 0777) {
  23. if (substr($dir, -1) != '/')
  24. $dir .= '/';
  25. do {
  26. $path = $dir . $prefix . mt_rand(0, 9999999);
  27. } while (!mkdir($path, $mode));
  28. return $path;
  29. }
  30. /**
  31. * This function displays the form for import of the zip file with qti2
  32. * @param string Report message to show in case of error
  33. */
  34. function aiken_display_form()
  35. {
  36. $name_tools = get_lang('ImportAikenQuiz');
  37. $form = '<div class="actions">';
  38. $form .= '<a href="exercise.php?show=test&'.api_get_cidreq().'">' .
  39. Display :: return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
  40. $form .= '</div>';
  41. $form_validator = new FormValidator(
  42. 'aiken_upload',
  43. 'post',
  44. api_get_self()."?".api_get_cidreq(),
  45. null,
  46. array('enctype' => 'multipart/form-data')
  47. );
  48. $form_validator->addElement('header', $name_tools);
  49. $form_validator->addElement('text', 'total_weight', get_lang('TotalWeight'));
  50. $form_validator->addElement('file', 'userFile', get_lang('DownloadFile'));
  51. $form_validator->addButtonUpload(get_lang('Upload'), 'submit');
  52. $form .= $form_validator->returnForm();
  53. $form .= '<blockquote>'.get_lang('ImportAikenQuizExplanation').'<br /><pre>'.get_lang('ImportAikenQuizExplanationExample').'</pre></blockquote>';
  54. echo $form;
  55. }
  56. /**
  57. * Gets the uploaded file (from $_FILES) and unzip it to the given directory
  58. * @param string The directory where to do the work
  59. * @param string The path of the temporary directory where the exercise was uploaded and unzipped
  60. * @param string $baseWorkDir
  61. * @param string $uploadPath
  62. * @return bool True on success, false on failure
  63. */
  64. function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath) {
  65. $_course = api_get_course_info();
  66. $_user = api_get_user_info();
  67. //Check if the file is valid (not to big and exists)
  68. if (!isset ($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
  69. // upload failed
  70. return false;
  71. }
  72. if (preg_match('/.zip$/i', $_FILES['userFile']['name']) && handle_uploaded_document($_course, $_FILES['userFile'], $baseWorkDir, $uploadPath, $_user['user_id'], 0, null, 1, 'overwrite', false)) {
  73. if (!function_exists('gzopen')) {
  74. return false;
  75. }
  76. // upload successful
  77. return true;
  78. } elseif (preg_match('/.txt/i', $_FILES['userFile']['name']) && handle_uploaded_document($_course, $_FILES['userFile'], $baseWorkDir, $uploadPath, $_user['user_id'], 0, null, 0, 'overwrite', false)) {
  79. return true;
  80. } else {
  81. return false;
  82. }
  83. }
  84. /**
  85. * Main function to import the Aiken exercise
  86. * @return mixed True on success, error message on failure
  87. */
  88. function aiken_import_exercise($file)
  89. {
  90. global $exercise_info;
  91. $archive_path = api_get_path(SYS_ARCHIVE_PATH) . 'aiken';
  92. $baseWorkDir = $archive_path;
  93. if (!is_dir($baseWorkDir)) {
  94. mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
  95. }
  96. $uploadPath = '/';
  97. // set some default values for the new exercise
  98. $exercise_info = array();
  99. $exercise_info['name'] = preg_replace('/.(zip|txt)$/i', '', $file);
  100. $exercise_info['question'] = array();
  101. // if file is not a .zip, then we cancel all
  102. if (!preg_match('/.(zip|txt)$/i', $file)) {
  103. //Display :: display_error_message(get_lang('YouMustUploadAZipOrTxtFile'));
  104. return 'YouMustUploadAZipOrTxtFile';
  105. }
  106. // unzip the uploaded file in a tmp directory
  107. if (preg_match('/.(zip|txt)$/i', $file)) {
  108. if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
  109. return 'ThereWasAProblemWithYourFile';
  110. }
  111. }
  112. // find the different manifests for each question and parse them
  113. $exerciseHandle = opendir($baseWorkDir);
  114. $file_found = false;
  115. $operation = false;
  116. $result = false;
  117. // Parse every subdirectory to search txt question files
  118. while (false !== ($file = readdir($exerciseHandle))) {
  119. if (is_dir($baseWorkDir . '/' . $file) && $file != "." && $file != "..") {
  120. //find each manifest for each question repository found
  121. $questionHandle = opendir($baseWorkDir . '/' . $file);
  122. while (false !== ($questionFile = readdir($questionHandle))) {
  123. if (preg_match('/.txt$/i', $questionFile)) {
  124. $result = aiken_parse_file(
  125. $exercise_info,
  126. $baseWorkDir,
  127. $file,
  128. $questionFile
  129. );
  130. $file_found = true;
  131. }
  132. }
  133. } elseif (preg_match('/.txt$/i', $file)) {
  134. $result = aiken_parse_file($exercise_info, $baseWorkDir, '', $file);
  135. $file_found = true;
  136. } // else ignore file
  137. }
  138. if (!$file_found) {
  139. $result = 'NoTxtFileFoundInTheZip';
  140. }
  141. if ($result !== true) {
  142. return $result;
  143. }
  144. // Add exercise in tool
  145. // 1.create exercise
  146. $exercise = new Exercise();
  147. $exercise->exercise = $exercise_info['name'];
  148. $exercise->save();
  149. $last_exercise_id = $exercise->selectId();
  150. if (!empty($last_exercise_id)) {
  151. // For each question found...
  152. foreach ($exercise_info['question'] as $key => $question_array) {
  153. //2.create question
  154. $question = new Aiken2Question();
  155. $question->type = $question_array['type'];
  156. $question->setAnswer();
  157. $question->updateTitle($question_array['title']);
  158. if (isset($question_array['description'])) {
  159. $question->updateDescription($question_array['description']);
  160. }
  161. $type = $question->selectType();
  162. $question->type = constant($type);
  163. $question->save($last_exercise_id);
  164. $last_question_id = $question->selectId();
  165. //3. Create answer
  166. $answer = new Answer($last_question_id);
  167. $answer->new_nbrAnswers = count($question_array['answer']);
  168. $max_score = 0;
  169. foreach ($question_array['answer'] as $key => $answers) {
  170. $key++;
  171. $answer->new_answer[$key] = $answers['value'];
  172. $answer->new_position[$key] = $key;
  173. // Correct answers ...
  174. if (in_array($key, $question_array['correct_answers'])) {
  175. $answer->new_correct[$key] = 1;
  176. if (isset($question_array['feedback'])) {
  177. $answer->new_comment[$key] = $question_array['feedback'];
  178. }
  179. } else {
  180. $answer->new_correct[$key] = 0;
  181. }
  182. if (isset($question_array['weighting'][$key - 1])) {
  183. $answer->new_weighting[$key] = $question_array['weighting'][$key - 1];
  184. $max_score += $question_array['weighting'][$key - 1];
  185. }
  186. }
  187. $answer->save();
  188. // Now that we know the question score, set it!
  189. $question->updateWeighting($max_score);
  190. $question->save();
  191. }
  192. // Delete the temp dir where the exercise was unzipped
  193. my_delete($baseWorkDir . $uploadPath);
  194. $operation = $last_exercise_id;
  195. }
  196. return $operation;
  197. }
  198. /**
  199. * Parses an Aiken file and builds an array of exercise + questions to be
  200. * imported by the import_exercise() function
  201. * @param array The reference to the array in which to store the questions
  202. * @param string Path to the directory with the file to be parsed (without final /)
  203. * @param string Name of the last directory part for the file (without /)
  204. * @param string Name of the file to be parsed (including extension)
  205. * @param string $exercisePath
  206. * @param string $file
  207. * @param string $questionFile
  208. * @return string|boolean True on success, error message on error
  209. * @assert ('','','') === false
  210. */
  211. function aiken_parse_file(&$exercise_info, $exercisePath, $file, $questionFile) {
  212. global $questionTempDir;
  213. $questionTempDir = $exercisePath . '/' . $file . '/';
  214. $questionFilePath = $questionTempDir . $questionFile;
  215. if (!is_file($questionFilePath)) {
  216. return 'FileNotFound';
  217. }
  218. $data = file($questionFilePath);
  219. $question_index = 0;
  220. $correct_answer = '';
  221. $answers_array = array();
  222. $new_question = true;
  223. foreach ($data as $line => $info) {
  224. if ($question_index > 0 && $new_question == true && preg_match('/^(\r)?\n/',$info)) {
  225. // double empty line
  226. continue;
  227. }
  228. $new_question = false;
  229. //make sure it is transformed from iso-8859-1 to utf-8 if in that form
  230. if (!mb_check_encoding($info,'utf-8') && mb_check_encoding($info,'iso-8859-1')) {
  231. $info = utf8_encode($info);
  232. }
  233. $exercise_info['question'][$question_index]['type'] = 'MCUA';
  234. if (preg_match('/^([A-Za-z])(\)|\.)\s(.*)/', $info, $matches)) {
  235. //adding one of the possible answers
  236. $exercise_info['question'][$question_index]['answer'][]['value'] = $matches[3];
  237. $answers_array[] = $matches[1];
  238. } elseif (preg_match('/^ANSWER:\s?([A-Z])\s?/', $info, $matches)) {
  239. //the correct answers
  240. $correct_answer_index = array_search($matches[1], $answers_array);
  241. $exercise_info['question'][$question_index]['correct_answers'][] = $correct_answer_index + 1;
  242. //weight for correct answer
  243. $exercise_info['question'][$question_index]['weighting'][$correct_answer_index] = 1;
  244. } elseif (preg_match('/^ANSWER_EXPLANATION:\s?(.*)/', $info, $matches)) {
  245. //Comment of correct answer
  246. $correct_answer_index = array_search($matches[1], $answers_array);
  247. $exercise_info['question'][$question_index]['feedback'] = $matches[1];
  248. } elseif (preg_match('/^TEXTO_CORRECTA:\s?(.*)/', $info, $matches)) {
  249. //Comment of correct answer (Spanish e-ducativa format)
  250. $correct_answer_index = array_search($matches[1], $answers_array);
  251. $exercise_info['question'][$question_index]['feedback'] = $matches[1];
  252. } elseif (preg_match('/^T:\s?(.*)/', $info, $matches)) {
  253. //Question Title
  254. $correct_answer_index = array_search($matches[1], $answers_array);
  255. $exercise_info['question'][$question_index]['title'] = $matches[1];
  256. } elseif (preg_match('/^TAGS:\s?([A-Z])\s?/', $info, $matches)) {
  257. //TAGS for chamilo >= 1.10
  258. $exercise_info['question'][$question_index]['answer_tags'] = explode(',', $matches[1]);
  259. } elseif (preg_match('/^ETIQUETAS:\s?([A-Z])\s?/', $info, $matches)) {
  260. //TAGS for chamilo >= 1.10 (Spanish e-ducativa format)
  261. $exercise_info['question'][$question_index]['answer_tags'] = explode(',', $matches[1]);
  262. } elseif (preg_match('/^(\r)?\n/',$info)) {
  263. //moving to next question (tolerate \r\n or just \n)
  264. if (empty($exercise_info['question'][$question_index]['correct_answers'])) {
  265. error_log('Aiken: Error in question index '.$question_index.': no correct answer defined');
  266. return 'ExerciseAikenErrorNoCorrectAnswerDefined';
  267. }
  268. if (empty($exercise_info['question'][$question_index]['answer'])) {
  269. error_log('Aiken: Error in question index '.$question_index.': no answer option given');
  270. return 'ExerciseAikenErrorNoAnswerOptionGiven';
  271. }
  272. $question_index++;
  273. //emptying answers array when moving to next question
  274. $answers_array = array();
  275. $new_question = true;
  276. } else {
  277. if (empty($exercise_info['question'][$question_index]['title'])) {
  278. if (strlen($info) < 100) {
  279. $exercise_info['question'][$question_index]['title'] = $info;
  280. } else {
  281. //Question itself (use a 100-chars long title and a larger description)
  282. $exercise_info['question'][$question_index]['title'] = trim(substr($info, 0, 100)) . '...';
  283. $exercise_info['question'][$question_index]['description'] = $info;
  284. }
  285. } else {
  286. $exercise_info['question'][$question_index]['description'] = $info;
  287. }
  288. }
  289. }
  290. $total_questions = count($exercise_info['question']);
  291. $total_weight = (!empty($_POST['total_weight'])) ? intval($_POST['total_weight']) : 20;
  292. foreach ($exercise_info['question'] as $key => $question) {
  293. $exercise_info['question'][$key]['weighting'][current(array_keys($exercise_info['question'][$key]['weighting']))] = $total_weight / $total_questions;
  294. }
  295. return true;
  296. }
  297. /**
  298. * Imports the zip file
  299. * @param array $array_file ($_FILES)
  300. */
  301. function aiken_import_file($array_file)
  302. {
  303. $unzip = 0;
  304. $process = process_uploaded_file($array_file, false);
  305. if (preg_match('/\.(zip|txt)$/i', $array_file['name'])) {
  306. // if it's a zip, allow zip upload
  307. $unzip = 1;
  308. }
  309. if ($process && $unzip == 1) {
  310. $imported = aiken_import_exercise($array_file['name']);
  311. if (is_numeric($imported) && !empty($imported)) {
  312. Display::addFlash(Display::return_message(get_lang('Uploaded')));
  313. return $imported;
  314. } else {
  315. Display::addFlash(Display::return_message(get_lang($imported), 'error'));
  316. return false;
  317. }
  318. }
  319. }