exercise_import.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. <?php
  2. /**
  3. * @copyright (c) 2001-2006 Universite catholique de Louvain (UCL)
  4. *
  5. * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
  6. *
  7. * @package chamilo.exercise
  8. *
  9. * @author claro team <cvs@claroline.net>
  10. * @author Guillaume Lederer <guillaume@claroline.net>
  11. */
  12. /**
  13. * function to create a temporary directory (SAME AS IN MODULE ADMIN)
  14. */
  15. function tempdir($dir, $prefix = 'tmp', $mode = 0777) {
  16. if (substr($dir, -1) != '/')
  17. $dir .= '/';
  18. do {
  19. $path = $dir . $prefix . mt_rand(0, 9999999);
  20. } while (!mkdir($path, $mode));
  21. return $path;
  22. }
  23. /**
  24. * the path of the temporary directory where the exercise was uploaded and unzipped
  25. * @param string
  26. * @param string
  27. * @return bool
  28. */
  29. function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
  30. {
  31. $_course = api_get_course_info();
  32. $_user = api_get_user_info();
  33. //Check if the file is valid (not to big and exists)
  34. if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
  35. // upload failed
  36. return false;
  37. }
  38. if (preg_match('/.zip$/i', $_FILES['userFile']['name']) &&
  39. handle_uploaded_document(
  40. $_course,
  41. $_FILES['userFile'],
  42. $baseWorkDir,
  43. $uploadPath,
  44. $_user['user_id'],
  45. 0,
  46. null,
  47. 1
  48. )
  49. ) {
  50. return true;
  51. }
  52. return false;
  53. }
  54. /**
  55. * Imports an exercise,
  56. * @param array $file
  57. * @return an array as a backlog of what was really imported, and error or debug messages to display
  58. */
  59. function import_exercise($file)
  60. {
  61. global $exercise_info;
  62. global $element_pile;
  63. global $non_HTML_tag_to_avoid;
  64. global $record_item_body;
  65. // used to specify the question directory where files could be found in relation in any question
  66. global $questionTempDir;
  67. $archive_path = api_get_path(SYS_ARCHIVE_PATH) . 'qti2';
  68. $baseWorkDir = $archive_path;
  69. if (!is_dir($baseWorkDir)) {
  70. mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
  71. }
  72. $uploadPath = '/';
  73. // set some default values for the new exercise
  74. $exercise_info = array ();
  75. $exercise_info['name'] = preg_replace('/.zip$/i', '', $file);
  76. $exercise_info['question'] = array();
  77. $element_pile = array ();
  78. // create parser and array to retrieve info from manifest
  79. $element_pile = array (); //pile to known the depth in which we are
  80. //$module_info = array (); //array to store the info we need
  81. // if file is not a .zip, then we cancel all
  82. if (!preg_match('/.zip$/i', $file)) {
  83. return 'UplZipCorrupt';
  84. }
  85. // unzip the uploaded file in a tmp directory
  86. if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
  87. return 'UplZipCorrupt';
  88. }
  89. // find the different manifests for each question and parse them.
  90. $exerciseHandle = opendir($baseWorkDir);
  91. //$question_number = 0;
  92. $file_found = false;
  93. $operation = false;
  94. $result = false;
  95. $filePath = null;
  96. // parse every subdirectory to search xml question files
  97. while (false !== ($file = readdir($exerciseHandle))) {
  98. if (is_dir($baseWorkDir . '/' . $file) && $file != "." && $file != "..") {
  99. // Find each manifest for each question repository found
  100. $questionHandle = opendir($baseWorkDir . '/' . $file);
  101. while (false !== ($questionFile = readdir($questionHandle))) {
  102. if (preg_match('/.xml$/i', $questionFile)) {
  103. $result = parse_file($baseWorkDir, $file, $questionFile);
  104. $filePath = $baseWorkDir.$file;
  105. $file_found = true;
  106. }
  107. }
  108. } elseif (preg_match('/.xml$/i', $file)) {
  109. // Else ignore file
  110. $result = parse_file($baseWorkDir, '', $file);
  111. $filePath = $baseWorkDir.'/'.$file;
  112. $file_found = true;
  113. }
  114. }
  115. if (!$file_found) {
  116. return 'No XML file found in the zip';
  117. }
  118. if ($result == false) {
  119. return false;
  120. }
  121. $doc = new DOMDocument();
  122. $doc->load($filePath);
  123. $encoding = $doc->encoding;
  124. // 1. Create exercise.
  125. $exercise = new Exercise();
  126. $exercise->exercise = $exercise_info['name'];
  127. $exercise->save();
  128. $last_exercise_id = $exercise->selectId();
  129. if (!empty($last_exercise_id)) {
  130. // For each question found...
  131. foreach ($exercise_info['question'] as $question_array) {
  132. //2. Create question
  133. $question = new Ims2Question();
  134. $question->type = $question_array['type'];
  135. $question->setAnswer();
  136. $question->updateTitle(formatText($question_array['title']));
  137. //$question->updateDescription($question_array['title']);
  138. $type = $question->selectType();
  139. $question->type = constant($type);
  140. $question->save($last_exercise_id);
  141. $last_question_id = $question->selectId();
  142. //3. Create answer
  143. $answer = new Answer($last_question_id);
  144. $answer->new_nbrAnswers = count($question_array['answer']);
  145. $totalCorrectWeight = 0;
  146. foreach ($question_array['answer'] as $key => $answers) {
  147. $split = explode('_', $key);
  148. $i = $split[1];
  149. // Answer
  150. $answer->new_answer[$i] = formatText($answers['value']);
  151. // Comment
  152. $answer->new_comment[$i] = isset($answers['feedback']) ? formatText($answers['feedback']) : null;
  153. // Position
  154. $answer->new_position[$i] = $i;
  155. // Correct answers
  156. if (in_array($key, $question_array['correct_answers'])) {
  157. $answer->new_correct[$i] = 1;
  158. } else {
  159. $answer->new_correct[$i] = 0;
  160. }
  161. $answer->new_weighting[$i] = $question_array['weighting'][$key];
  162. if ($answer->new_correct[$i]) {
  163. $totalCorrectWeight = $answer->new_weighting[$i];
  164. }
  165. }
  166. $question->updateWeighting($totalCorrectWeight);
  167. $question->save($last_exercise_id);
  168. $answer->save();
  169. }
  170. // delete the temp dir where the exercise was unzipped
  171. my_delete($baseWorkDir . $uploadPath);
  172. return $last_exercise_id;
  173. }
  174. return false;
  175. }
  176. /**
  177. * We assume the file charset is UTF8
  178. **/
  179. function formatText($text)
  180. {
  181. return api_html_entity_decode($text);
  182. }
  183. function parse_file($exercisePath, $file, $questionFile)
  184. {
  185. global $exercise_info;
  186. global $element_pile;
  187. global $non_HTML_tag_to_avoid;
  188. global $record_item_body;
  189. global $questionTempDir;
  190. $questionTempDir = $exercisePath . '/' . $file . '/';
  191. $questionFilePath = $questionTempDir . $questionFile;
  192. if (!($fp = fopen($questionFilePath, 'r'))) {
  193. Display :: display_error_message(get_lang('Error opening question\'s XML file'));
  194. return false;
  195. } else {
  196. $data = fread($fp, filesize($questionFilePath));
  197. }
  198. //parse XML question file
  199. $data = str_replace(array('<p>', '</p>','<front>','</front>'), '', $data);
  200. //used global variable start values declaration :
  201. $record_item_body = false;
  202. $non_HTML_tag_to_avoid = array (
  203. "SIMPLECHOICE",
  204. "CHOICEINTERACTION",
  205. "INLINECHOICEINTERACTION",
  206. "INLINECHOICE",
  207. "SIMPLEMATCHSET",
  208. "SIMPLEASSOCIABLECHOICE",
  209. "TEXTENTRYINTERACTION",
  210. "FEEDBACKINLINE",
  211. "MATCHINTERACTION",
  212. "ITEMBODY",
  213. "BR",
  214. "IMG"
  215. );
  216. //this array to detect tag not supported by claroline import in the xml file to warn the user.
  217. $non_supported_content_in_question = array (
  218. "GAPMATCHINTERACTION",
  219. "EXTENDEDTEXTINTERACTION",
  220. "HOTTEXTINTERACTION",
  221. "HOTSPOTINTERACTION",
  222. "SELECTPOINTINTERACTION",
  223. "GRAPHICORDERINTERACTION",
  224. "GRAPHICASSOCIATIONINTERACTION",
  225. "GRAPHICGAPMATCHINTERACTION",
  226. "POSITIONOBJECTINTERACTION",
  227. "SLIDERINTERACTION",
  228. "DRAWINGINTERACTION",
  229. "UPLOADINTERACTION",
  230. "RESPONSECONDITION",
  231. "RESPONSEIF"
  232. );
  233. $question_format_supported = true;
  234. $xml_parser = xml_parser_create();
  235. xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, false);
  236. xml_set_element_handler($xml_parser, 'startElement', 'endElement');
  237. xml_set_character_data_handler($xml_parser, 'elementData');
  238. if (!xml_parse($xml_parser, $data, feof($fp))) {
  239. // if reading of the xml file in not successful :
  240. // set errorFound, set error msg, break while statement
  241. Display :: display_error_message(get_lang('Error reading XML file'));
  242. return false;
  243. }
  244. //close file
  245. fclose($fp);
  246. if (!$question_format_supported) {
  247. Display :: display_error_message(get_lang('Unknown question format in file %file', array (
  248. '%file' => $questionFile
  249. )));
  250. return false;
  251. }
  252. return true;
  253. }
  254. /**
  255. * Function used by the SAX xml parser when the parser meets a opening tag
  256. *
  257. * @param unknown_type $parser xml parser created with "xml_parser_create()"
  258. * @param unknown_type $name name of the element
  259. * @param unknown_type $attributes
  260. */
  261. function startElement($parser, $name, $attributes) {
  262. global $element_pile;
  263. global $exercise_info;
  264. global $current_question_ident;
  265. global $current_answer_id;
  266. global $current_match_set;
  267. global $currentAssociableChoice;
  268. global $current_question_item_body;
  269. global $record_item_body;
  270. global $non_HTML_tag_to_avoid;
  271. global $current_inlinechoice_id;
  272. global $cardinality;
  273. global $questionTempDir;
  274. array_push($element_pile, $name);
  275. $current_element = end($element_pile);
  276. if (sizeof($element_pile) >= 2)
  277. $parent_element = $element_pile[sizeof($element_pile) - 2];
  278. else
  279. $parent_element = "";
  280. if (sizeof($element_pile) >= 3)
  281. $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
  282. else
  283. $grant_parent_element = "";
  284. if ($record_item_body) {
  285. if ((!in_array($current_element, $non_HTML_tag_to_avoid))) {
  286. $current_question_item_body .= "<" . $name;
  287. foreach ($attributes as $attribute_name => $attribute_value) {
  288. $current_question_item_body .= " " . $attribute_name . "=\"" . $attribute_value . "\"";
  289. }
  290. $current_question_item_body .= ">";
  291. } else {
  292. //in case of FIB question, we replace the IMS-QTI tag b y the correct answer between "[" "]",
  293. //we first save with claroline tags ,then when the answer will be parsed, the claroline tags will be replaced
  294. if ($current_element == 'INLINECHOICEINTERACTION') {
  295. $current_question_item_body .= "**claroline_start**" . $attributes['RESPONSEIDENTIFIER'] . "**claroline_end**";
  296. }
  297. if ($current_element == 'TEXTENTRYINTERACTION') {
  298. $correct_answer_value = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
  299. $current_question_item_body .= "[" . $correct_answer_value . "]";
  300. }
  301. if ($current_element == 'BR') {
  302. $current_question_item_body .= "<BR/>";
  303. }
  304. }
  305. }
  306. switch ($current_element) {
  307. case 'ASSESSMENTITEM' :
  308. //retrieve current question
  309. $current_question_ident = $attributes['IDENTIFIER'];
  310. $exercise_info['question'][$current_question_ident] = array ();
  311. $exercise_info['question'][$current_question_ident]['answer'] = array ();
  312. $exercise_info['question'][$current_question_ident]['correct_answers'] = array ();
  313. $exercise_info['question'][$current_question_ident]['title'] = $attributes['TITLE'];
  314. $exercise_info['question'][$current_question_ident]['tempdir'] = $questionTempDir;
  315. break;
  316. case 'SECTION':
  317. //retrieve exercise name
  318. $exercise_info['name'] = $attributes['TITLE'];
  319. break;
  320. case 'RESPONSEDECLARATION':
  321. // Retrieve question type
  322. if ("multiple" == $attributes['CARDINALITY']) {
  323. $exercise_info['question'][$current_question_ident]['type'] = 'MCMA';
  324. $cardinality = 'multiple';
  325. }
  326. if ("single" == $attributes['CARDINALITY']) {
  327. $exercise_info['question'][$current_question_ident]['type'] = 'MCUA';
  328. $cardinality = 'single';
  329. }
  330. //needed for FIB
  331. $current_answer_id = $attributes['IDENTIFIER'];
  332. break;
  333. case 'INLINECHOICEINTERACTION' :
  334. $exercise_info['question'][$current_question_ident]['type'] = 'FIB';
  335. $exercise_info['question'][$current_question_ident]['subtype'] = 'LISTBOX_FILL';
  336. $current_answer_id = $attributes['RESPONSEIDENTIFIER'];
  337. break;
  338. case 'INLINECHOICE' :
  339. $current_inlinechoice_id = $attributes['IDENTIFIER'];
  340. break;
  341. case 'TEXTENTRYINTERACTION':
  342. $exercise_info['question'][$current_question_ident]['type'] = 'FIB';
  343. $exercise_info['question'][$current_question_ident]['subtype'] = 'TEXTFIELD_FILL';
  344. $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
  345. //replace claroline tags
  346. break;
  347. case 'MATCHINTERACTION':
  348. $exercise_info['question'][$current_question_ident]['type'] = 'MATCHING';
  349. break;
  350. case 'SIMPLEMATCHSET' :
  351. if (!isset ($current_match_set)) {
  352. $current_match_set = 1;
  353. } else {
  354. $current_match_set++;
  355. }
  356. $exercise_info['question'][$current_question_ident]['answer'][$current_match_set] = array ();
  357. break;
  358. case 'SIMPLEASSOCIABLECHOICE':
  359. $currentAssociableChoice = $attributes['IDENTIFIER'];
  360. break;
  361. //retrieve answers id for MCUA and MCMA questions
  362. case 'SIMPLECHOICE':
  363. $current_answer_id = $attributes['IDENTIFIER'];
  364. if (!isset($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id])) {
  365. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id] = array ();
  366. }
  367. break;
  368. case 'MAPENTRY':
  369. if ($parent_element == "MAPPING") {
  370. $answer_id = $attributes['MAPKEY'];
  371. if (!isset ($exercise_info['question'][$current_question_ident]['weighting'])) {
  372. $exercise_info['question'][$current_question_ident]['weighting'] = array ();
  373. }
  374. $exercise_info['question'][$current_question_ident]['weighting'][$answer_id] = $attributes['MAPPEDVALUE'];
  375. }
  376. break;
  377. case 'MAPPING':
  378. if (isset ($attributes['DEFAULTVALUE'])) {
  379. $exercise_info['question'][$current_question_ident]['default_weighting'] = $attributes['DEFAULTVALUE'];
  380. }
  381. case 'ITEMBODY':
  382. $record_item_body = true;
  383. $current_question_item_body = '';
  384. break;
  385. case 'IMG':
  386. $exercise_info['question'][$current_question_ident]['attached_file_url'] = $attributes['SRC'];
  387. break;
  388. }
  389. }
  390. /**
  391. * Function used by the SAX xml parser when the parser meets a closing tag
  392. *
  393. * @param $parser xml parser created with "xml_parser_create()"
  394. * @param $name name of the element
  395. */
  396. function endElement($parser, $name) {
  397. global $element_pile;
  398. global $exercise_info;
  399. global $current_question_ident;
  400. global $record_item_body;
  401. global $current_question_item_body;
  402. global $non_HTML_tag_to_avoid;
  403. global $cardinality;
  404. $current_element = end($element_pile);
  405. //treat the record of the full content of itembody tag :
  406. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  407. $current_question_item_body .= "</" . $name . ">";
  408. }
  409. switch ($name) {
  410. case 'ITEMBODY':
  411. $record_item_body = false;
  412. if ($exercise_info['question'][$current_question_ident]['type'] == 'FIB') {
  413. $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
  414. } else {
  415. $exercise_info['question'][$current_question_ident]['statement'] = $current_question_item_body;
  416. }
  417. break;
  418. }
  419. array_pop($element_pile);
  420. }
  421. function elementData($parser, $data) {
  422. global $element_pile;
  423. global $exercise_info;
  424. global $current_question_ident;
  425. global $current_answer_id;
  426. global $current_match_set;
  427. global $currentAssociableChoice;
  428. global $current_question_item_body;
  429. global $record_item_body;
  430. global $non_HTML_tag_to_avoid;
  431. global $current_inlinechoice_id;
  432. global $cardinality;
  433. $current_element = end($element_pile);
  434. if (sizeof($element_pile) >= 2)
  435. $parent_element = $element_pile[sizeof($element_pile) - 2];
  436. else
  437. $parent_element = "";
  438. if (sizeof($element_pile) >= 3)
  439. $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
  440. else
  441. $grant_parent_element = "";
  442. //treat the record of the full content of itembody tag (needed for question statment and/or FIB text:
  443. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  444. $current_question_item_body .= $data;
  445. }
  446. switch ($current_element) {
  447. case 'SIMPLECHOICE':
  448. if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'])) {
  449. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] = trim($data);
  450. } else {
  451. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] .= ''.trim($data);
  452. }
  453. break;
  454. case 'FEEDBACKINLINE' :
  455. if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'])) {
  456. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] = trim($data);
  457. } else {
  458. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] .= ' ' . trim($data);
  459. }
  460. break;
  461. case 'SIMPLEASSOCIABLECHOICE':
  462. $exercise_info['question'][$current_question_ident]['answer'][$current_match_set][$currentAssociableChoice] = trim($data);
  463. break;
  464. case 'VALUE' :
  465. if ($parent_element == "CORRECTRESPONSE") {
  466. if ($cardinality == "single") {
  467. $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id] = $data;
  468. } else {
  469. $exercise_info['question'][$current_question_ident]['correct_answers'][] = $data;
  470. }
  471. }
  472. break;
  473. case 'ITEMBODY' :
  474. $current_question_item_body .= $data;
  475. break;
  476. case 'INLINECHOICE' :
  477. // if this is the right answer, then we must replace the claroline tags in the FIB text bye the answer between "[" and "]" :
  478. $answer_identifier = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
  479. if ($current_inlinechoice_id == $answer_identifier) {
  480. $current_question_item_body = str_replace("**claroline_start**" . $current_answer_id . "**claroline_end**", "[" . $data . "]", $current_question_item_body);
  481. } else {
  482. if (!isset ($exercise_info['question'][$current_question_ident]['wrong_answers'])) {
  483. $exercise_info['question'][$current_question_ident]['wrong_answers'] = array ();
  484. }
  485. $exercise_info['question'][$current_question_ident]['wrong_answers'][] = $data;
  486. }
  487. break;
  488. }
  489. }