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