exercise_import.inc.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * @copyright (c) 2001-2006 Universite catholique de Louvain (UCL)
  5. * @package chamilo.exercise
  6. * @author claro team <cvs@claroline.net>
  7. * @author Guillaume Lederer <guillaume@claroline.net>
  8. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  9. */
  10. /**
  11. * Unzip the exercise in the temp folder
  12. * @param string The path of the temporary directory where the exercise was uploaded and unzipped
  13. * @param string
  14. * @param string $baseWorkDir
  15. * @param string $uploadPath
  16. * @return bool
  17. */
  18. function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
  19. {
  20. $_course = api_get_course_info();
  21. $_user = api_get_user_info();
  22. //Check if the file is valid (not to big and exists)
  23. if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
  24. // upload failed
  25. return false;
  26. }
  27. if (preg_match('/.zip$/i', $_FILES['userFile']['name']) &&
  28. handle_uploaded_document(
  29. $_course,
  30. $_FILES['userFile'],
  31. $baseWorkDir,
  32. $uploadPath,
  33. $_user['user_id'],
  34. 0,
  35. null,
  36. 1
  37. )
  38. ) {
  39. return true;
  40. }
  41. return false;
  42. }
  43. /**
  44. * Imports an exercise in QTI format if the XML structure can be found in it
  45. * @param array $file
  46. * @return string|array as a backlog of what was really imported, and error or debug messages to display
  47. */
  48. function import_exercise($file)
  49. {
  50. global $exercise_info;
  51. global $element_pile;
  52. global $non_HTML_tag_to_avoid;
  53. global $record_item_body;
  54. // used to specify the question directory where files could be found in relation in any question
  55. global $questionTempDir;
  56. global $resourcesLinks;
  57. $baseWorkDir = api_get_path(SYS_ARCHIVE_PATH) . 'qti2';
  58. if (!is_dir($baseWorkDir)) {
  59. mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
  60. }
  61. $uploadPath = '/';
  62. // set some default values for the new exercise
  63. $exercise_info = array();
  64. $exercise_info['name'] = preg_replace('/.zip$/i', '', $file);
  65. $exercise_info['question'] = array();
  66. $element_pile = array();
  67. // create parser and array to retrieve info from manifest
  68. $element_pile = array(); //pile to known the depth in which we are
  69. //$module_info = array (); //array to store the info we need
  70. // if file is not a .zip, then we cancel all
  71. if (!preg_match('/.zip$/i', $file)) {
  72. return 'UplZipCorrupt';
  73. }
  74. // unzip the uploaded file in a tmp directory
  75. if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
  76. return 'UplZipCorrupt';
  77. }
  78. // find the different manifests for each question and parse them.
  79. $exerciseHandle = opendir($baseWorkDir);
  80. //$question_number = 0;
  81. $file_found = false;
  82. $operation = false;
  83. $result = false;
  84. $filePath = null;
  85. $resourcesLinks = array();
  86. // parse every subdirectory to search xml question files and other assets to be imported
  87. // The assets-related code is a bit fragile as it has to deal with files renamed by Chamilo and it only works if
  88. // the imsmanifest.xml file is read.
  89. while (false !== ($file = readdir($exerciseHandle))) {
  90. if (is_dir($baseWorkDir . '/' . $file) && $file != "." && $file != "..") {
  91. // Find each manifest for each question repository found
  92. $questionHandle = opendir($baseWorkDir . '/' . $file);
  93. // Only analyse one level of subdirectory - no recursivity here
  94. while (false !== ($questionFile = readdir($questionHandle))) {
  95. if (preg_match('/.xml$/i', $questionFile)) {
  96. $isQti = isQtiQuestionBank($baseWorkDir . '/' . $file . '/' . $questionFile);
  97. if ($isQti) {
  98. $result = qti_parse_file($baseWorkDir, $file, $questionFile);
  99. $filePath = $baseWorkDir . $file;
  100. $file_found = true;
  101. } else {
  102. $isManifest = isQtiManifest($baseWorkDir . '/' . $file . '/' . $questionFile);
  103. if ($isManifest) {
  104. $resourcesLinks = qtiProcessManifest($baseWorkDir . '/' . $file . '/' . $questionFile);
  105. }
  106. }
  107. }
  108. }
  109. } elseif (preg_match('/.xml$/i', $file)) {
  110. $isQti = isQtiQuestionBank($baseWorkDir . '/' . $file);
  111. if ($isQti) {
  112. $result = qti_parse_file($baseWorkDir, '', $file);
  113. $filePath = $baseWorkDir . '/' . $file;
  114. $file_found = true;
  115. } else {
  116. $isManifest = isQtiManifest($baseWorkDir . '/' . $file);
  117. if ($isManifest) {
  118. $resourcesLinks = qtiProcessManifest($baseWorkDir . '/' . $file);
  119. }
  120. }
  121. }
  122. }
  123. if (!$file_found) {
  124. return 'NoXMLFileFoundInTheZip';
  125. }
  126. if ($result == false) {
  127. return false;
  128. }
  129. $doc = new DOMDocument();
  130. $doc->load($filePath);
  131. // 1. Create exercise.
  132. $exercise = new Exercise();
  133. $exercise->exercise = $exercise_info['name'];
  134. $exercise->save();
  135. $last_exercise_id = $exercise->selectId();
  136. if (!empty($last_exercise_id)) {
  137. // For each question found...
  138. foreach ($exercise_info['question'] as $question_array) {
  139. //2. Create question
  140. $question = new Ims2Question();
  141. $question->type = $question_array['type'];
  142. if (empty($question->type)) {
  143. // If the type was not provided, assume this is a multiple choice, unique answer type (the most basic)
  144. $question->type = MCUA;
  145. }
  146. $question->setAnswer();
  147. if (strlen($question_array['title']) < 50) {
  148. $question->updateTitle(formatText(strip_tags($question_array['title'])) . '...');
  149. } else {
  150. $question->updateTitle(formatText(substr(strip_tags($question_array['title']), 0, 50)));
  151. $question->updateDescription($question_array['title']);
  152. }
  153. //$question->updateDescription($question_array['title']);
  154. $question->save($last_exercise_id);
  155. $last_question_id = $question->selectId();
  156. //3. Create answer
  157. $answer = new Answer($last_question_id);
  158. $answer->new_nbrAnswers = count($question_array['answer']);
  159. $totalCorrectWeight = 0;
  160. $j = 1;
  161. $matchAnswerIds = array();
  162. foreach ($question_array['answer'] as $key => $answers) {
  163. if (preg_match('/_/', $key)) {
  164. $split = explode('_', $key);
  165. $i = $split[1];
  166. } else {
  167. $i = $j;
  168. $j++;
  169. $matchAnswerIds[$key] = $j;
  170. }
  171. // Answer
  172. $answer->new_answer[$i] = formatText($answers['value']);
  173. // Comment
  174. $answer->new_comment[$i] = isset($answers['feedback']) ? formatText($answers['feedback']) : null;
  175. // Position
  176. $answer->new_position[$i] = $i;
  177. // Correct answers
  178. if (in_array($key, $question_array['correct_answers'])) {
  179. $answer->new_correct[$i] = 1;
  180. } else {
  181. $answer->new_correct[$i] = 0;
  182. }
  183. $answer->new_weighting[$i] = $question_array['weighting'][$key];
  184. if ($answer->new_correct[$i]) {
  185. $totalCorrectWeight += $answer->new_weighting[$i];
  186. }
  187. }
  188. $question->updateWeighting($totalCorrectWeight);
  189. $question->save($last_exercise_id);
  190. $answer->save();
  191. }
  192. // delete the temp dir where the exercise was unzipped
  193. my_delete($baseWorkDir . $uploadPath);
  194. return $last_exercise_id;
  195. }
  196. return false;
  197. }
  198. /**
  199. * We assume the file charset is UTF8
  200. **/
  201. function formatText($text)
  202. {
  203. return api_html_entity_decode($text);
  204. }
  205. /**
  206. * Parses a given XML file and fills global arrays with the elements
  207. * @param string $exercisePath
  208. * @param string $file
  209. * @param string $questionFile
  210. * @return bool
  211. */
  212. function qti_parse_file($exercisePath, $file, $questionFile)
  213. {
  214. global $non_HTML_tag_to_avoid;
  215. global $record_item_body;
  216. global $questionTempDir;
  217. $questionTempDir = $exercisePath . '/' . $file . '/';
  218. $questionFilePath = $questionTempDir . $questionFile;
  219. if (!($fp = fopen($questionFilePath, 'r'))) {
  220. Display::addFlash(Display::return_message(get_lang('Error opening question\'s XML file'), 'error'));
  221. return false;
  222. } else {
  223. $data = fread($fp, filesize($questionFilePath));
  224. }
  225. //parse XML question file
  226. //$data = str_replace(array('<p>', '</p>', '<front>', '</front>'), '', $data);
  227. $data = stripGivenTags($data, array('p', 'front'));
  228. $qtiVersion = array();
  229. $match = preg_match('/ims_qtiasiv(\d)p(\d)/', $data, $qtiVersion);
  230. $qtiMainVersion = 2; //by default, assume QTI version 2
  231. if ($match) {
  232. $qtiMainVersion = $qtiVersion[1];
  233. }
  234. //used global variable start values declaration :
  235. $record_item_body = false;
  236. $non_HTML_tag_to_avoid = array(
  237. "SIMPLECHOICE",
  238. "CHOICEINTERACTION",
  239. "INLINECHOICEINTERACTION",
  240. "INLINECHOICE",
  241. "SIMPLEMATCHSET",
  242. "SIMPLEASSOCIABLECHOICE",
  243. "TEXTENTRYINTERACTION",
  244. "FEEDBACKINLINE",
  245. "MATCHINTERACTION",
  246. "ITEMBODY",
  247. "BR",
  248. "IMG"
  249. );
  250. $question_format_supported = true;
  251. $xml_parser = xml_parser_create();
  252. xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, false);
  253. if ($qtiMainVersion == 1) {
  254. xml_set_element_handler($xml_parser, 'startElementQti1', 'endElementQti1');
  255. xml_set_character_data_handler($xml_parser, 'elementDataQti1');
  256. } else {
  257. xml_set_element_handler($xml_parser, 'startElementQti2', 'endElementQti2');
  258. xml_set_character_data_handler($xml_parser, 'elementDataQti2');
  259. }
  260. if (!xml_parse($xml_parser, $data, feof($fp))) {
  261. // if reading of the xml file in not successful :
  262. // set errorFound, set error msg, break while statement
  263. $error = xml_get_error_code();
  264. Display::addFlash(
  265. Display::return_message(
  266. get_lang('Error reading XML file') . sprintf('[%d:%d]', xml_get_current_line_number($xml_parser), xml_get_current_column_number($xml_parser)),
  267. 'error'
  268. )
  269. );
  270. return false;
  271. }
  272. //close file
  273. fclose($fp);
  274. if (!$question_format_supported) {
  275. Display::addFlash(
  276. Display::return_message(
  277. get_lang(
  278. 'Unknown question format in file %file',
  279. array(
  280. '%file' => $questionFile,
  281. )
  282. ),
  283. 'error'
  284. )
  285. );
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * Function used by the SAX xml parser when the parser meets a opening tag
  292. *
  293. * @param object $parser xml parser created with "xml_parser_create()"
  294. * @param string $name name of the element
  295. * @param array $attributes
  296. */
  297. function startElementQti2($parser, $name, $attributes)
  298. {
  299. global $element_pile;
  300. global $exercise_info;
  301. global $current_question_ident;
  302. global $current_answer_id;
  303. global $current_match_set;
  304. global $currentAssociableChoice;
  305. global $current_question_item_body;
  306. global $record_item_body;
  307. global $non_HTML_tag_to_avoid;
  308. global $current_inlinechoice_id;
  309. global $cardinality;
  310. global $questionTempDir;
  311. array_push($element_pile, $name);
  312. $current_element = end($element_pile);
  313. if (sizeof($element_pile) >= 2) {
  314. $parent_element = $element_pile[sizeof($element_pile) - 2];
  315. } else {
  316. $parent_element = "";
  317. }
  318. if (sizeof($element_pile) >= 3) {
  319. $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
  320. } else {
  321. $grant_parent_element = "";
  322. }
  323. if ($record_item_body) {
  324. if ((!in_array($current_element, $non_HTML_tag_to_avoid))) {
  325. $current_question_item_body .= "<" . $name;
  326. foreach ($attributes as $attribute_name => $attribute_value) {
  327. $current_question_item_body .= " " . $attribute_name . "=\"" . $attribute_value . "\"";
  328. }
  329. $current_question_item_body .= ">";
  330. } else {
  331. //in case of FIB question, we replace the IMS-QTI tag b y the correct answer between "[" "]",
  332. //we first save with claroline tags ,then when the answer will be parsed, the claroline tags will be replaced
  333. if ($current_element == 'INLINECHOICEINTERACTION') {
  334. $current_question_item_body .= "**claroline_start**" . $attributes['RESPONSEIDENTIFIER'] . "**claroline_end**";
  335. }
  336. if ($current_element == 'TEXTENTRYINTERACTION') {
  337. $correct_answer_value = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
  338. $current_question_item_body .= "[" . $correct_answer_value . "]";
  339. }
  340. if ($current_element == 'BR') {
  341. $current_question_item_body .= "<br />";
  342. }
  343. }
  344. }
  345. switch ($current_element) {
  346. case 'ASSESSMENTITEM':
  347. //retrieve current question
  348. $current_question_ident = $attributes['IDENTIFIER'];
  349. $exercise_info['question'][$current_question_ident] = array();
  350. $exercise_info['question'][$current_question_ident]['answer'] = array();
  351. $exercise_info['question'][$current_question_ident]['correct_answers'] = array();
  352. $exercise_info['question'][$current_question_ident]['title'] = $attributes['TITLE'];
  353. $exercise_info['question'][$current_question_ident]['tempdir'] = $questionTempDir;
  354. break;
  355. case 'SECTION':
  356. //retrieve exercise name
  357. if (isset($attributes['TITLE']) && !empty($attributes['TITLE'])) {
  358. $exercise_info['name'] = $attributes['TITLE'];
  359. }
  360. break;
  361. case 'RESPONSEDECLARATION':
  362. // Retrieve question type
  363. if ("multiple" == $attributes['CARDINALITY']) {
  364. $exercise_info['question'][$current_question_ident]['type'] = MCMA;
  365. $cardinality = 'multiple';
  366. }
  367. if ("single" == $attributes['CARDINALITY']) {
  368. $exercise_info['question'][$current_question_ident]['type'] = MCUA;
  369. $cardinality = 'single';
  370. }
  371. //needed for FIB
  372. $current_answer_id = $attributes['IDENTIFIER'];
  373. break;
  374. case 'INLINECHOICEINTERACTION':
  375. $exercise_info['question'][$current_question_ident]['type'] = FIB;
  376. $exercise_info['question'][$current_question_ident]['subtype'] = 'LISTBOX_FILL';
  377. $current_answer_id = $attributes['RESPONSEIDENTIFIER'];
  378. break;
  379. case 'INLINECHOICE':
  380. $current_inlinechoice_id = $attributes['IDENTIFIER'];
  381. break;
  382. case 'TEXTENTRYINTERACTION':
  383. $exercise_info['question'][$current_question_ident]['type'] = FIB;
  384. $exercise_info['question'][$current_question_ident]['subtype'] = 'TEXTFIELD_FILL';
  385. $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
  386. //replace claroline tags
  387. break;
  388. case 'MATCHINTERACTION':
  389. $exercise_info['question'][$current_question_ident]['type'] = MATCHING;
  390. break;
  391. case 'SIMPLEMATCHSET':
  392. if (!isset($current_match_set)) {
  393. $current_match_set = 1;
  394. } else {
  395. $current_match_set++;
  396. }
  397. $exercise_info['question'][$current_question_ident]['answer'][$current_match_set] = array();
  398. break;
  399. case 'SIMPLEASSOCIABLECHOICE':
  400. $currentAssociableChoice = $attributes['IDENTIFIER'];
  401. break;
  402. //retrieve answers id for MCUA and MCMA questions
  403. case 'SIMPLECHOICE':
  404. $current_answer_id = $attributes['IDENTIFIER'];
  405. if (!isset($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id])) {
  406. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id] = array();
  407. }
  408. break;
  409. case 'MAPENTRY':
  410. if ($parent_element == "MAPPING") {
  411. $answer_id = $attributes['MAPKEY'];
  412. if (!isset ($exercise_info['question'][$current_question_ident]['weighting'])) {
  413. $exercise_info['question'][$current_question_ident]['weighting'] = array();
  414. }
  415. $exercise_info['question'][$current_question_ident]['weighting'][$answer_id] = $attributes['MAPPEDVALUE'];
  416. }
  417. break;
  418. case 'MAPPING':
  419. if (isset ($attributes['DEFAULTVALUE'])) {
  420. $exercise_info['question'][$current_question_ident]['default_weighting'] = $attributes['DEFAULTVALUE'];
  421. }
  422. case 'ITEMBODY':
  423. $record_item_body = true;
  424. $current_question_item_body = '';
  425. break;
  426. case 'IMG':
  427. $exercise_info['question'][$current_question_ident]['attached_file_url'] = $attributes['SRC'];
  428. break;
  429. }
  430. }
  431. /**
  432. * Function used by the SAX xml parser when the parser meets a closing tag
  433. *
  434. * @param $parser xml parser created with "xml_parser_create()"
  435. * @param $name name of the element
  436. */
  437. function endElementQti2($parser, $name)
  438. {
  439. global $element_pile;
  440. global $exercise_info;
  441. global $current_question_ident;
  442. global $record_item_body;
  443. global $current_question_item_body;
  444. global $non_HTML_tag_to_avoid;
  445. global $cardinality;
  446. $current_element = end($element_pile);
  447. //treat the record of the full content of itembody tag :
  448. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  449. $current_question_item_body .= "</" . $name . ">";
  450. }
  451. switch ($name) {
  452. case 'ITEMBODY':
  453. $record_item_body = false;
  454. if ($exercise_info['question'][$current_question_ident]['type'] == FIB) {
  455. $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
  456. } else {
  457. $exercise_info['question'][$current_question_ident]['statement'] = $current_question_item_body;
  458. }
  459. break;
  460. }
  461. array_pop($element_pile);
  462. }
  463. /**
  464. * @param $parser
  465. * @param $data
  466. */
  467. function elementDataQti2($parser, $data)
  468. {
  469. global $element_pile;
  470. global $exercise_info;
  471. global $current_question_ident;
  472. global $current_answer_id;
  473. global $current_match_set;
  474. global $currentAssociableChoice;
  475. global $current_question_item_body;
  476. global $record_item_body;
  477. global $non_HTML_tag_to_avoid;
  478. global $current_inlinechoice_id;
  479. global $cardinality;
  480. global $resourcesLinks;
  481. $current_element = end($element_pile);
  482. if (sizeof($element_pile) >= 2) {
  483. $parent_element = $element_pile[sizeof($element_pile) - 2];
  484. } else {
  485. $parent_element = "";
  486. }
  487. if (sizeof($element_pile) >= 3) {
  488. $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
  489. } else {
  490. $grant_parent_element = "";
  491. }
  492. //treat the record of the full content of itembody tag (needed for question statment and/or FIB text:
  493. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  494. $current_question_item_body .= $data;
  495. }
  496. switch ($current_element) {
  497. case 'SIMPLECHOICE':
  498. if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'])) {
  499. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] = trim($data);
  500. } else {
  501. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] .= '' . trim($data);
  502. }
  503. break;
  504. case 'FEEDBACKINLINE':
  505. if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'])) {
  506. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] = trim($data);
  507. } else {
  508. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] .= ' ' . trim($data);
  509. }
  510. break;
  511. case 'SIMPLEASSOCIABLECHOICE':
  512. $exercise_info['question'][$current_question_ident]['answer'][$current_match_set][$currentAssociableChoice] = trim($data);
  513. break;
  514. case 'VALUE':
  515. if ($parent_element == "CORRECTRESPONSE") {
  516. if ($cardinality == "single") {
  517. $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id] = $data;
  518. } else {
  519. $exercise_info['question'][$current_question_ident]['correct_answers'][] = $data;
  520. }
  521. }
  522. break;
  523. case 'ITEMBODY':
  524. // Replace relative links by links to the documents in the course
  525. // $resourcesLinks is only defined by qtiProcessManifest()
  526. if (isset($resourcesLinks) && isset($resourcesLinks['manifest']) && isset($resourcesLinks['web'])) {
  527. foreach ($resourcesLinks['manifest'] as $key => $value) {
  528. $data = preg_replace('|' . $value . '|', $resourcesLinks['web'][$key], $data);
  529. }
  530. }
  531. $current_question_item_body .= $data;
  532. break;
  533. case 'INLINECHOICE':
  534. // if this is the right answer, then we must replace the claroline tags in the FIB text bye the answer between "[" and "]" :
  535. $answer_identifier = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
  536. if ($current_inlinechoice_id == $answer_identifier) {
  537. $current_question_item_body = str_replace(
  538. "**claroline_start**" . $current_answer_id . "**claroline_end**",
  539. "[" . $data . "]",
  540. $current_question_item_body
  541. );
  542. } else {
  543. if (!isset ($exercise_info['question'][$current_question_ident]['wrong_answers'])) {
  544. $exercise_info['question'][$current_question_ident]['wrong_answers'] = array();
  545. }
  546. $exercise_info['question'][$current_question_ident]['wrong_answers'][] = $data;
  547. }
  548. break;
  549. }
  550. }
  551. /**
  552. * Function used by the SAX xml parser when the parser meets a opening tag for QTI1
  553. *
  554. * @param object $parser xml parser created with "xml_parser_create()"
  555. * @param string $name name of the element
  556. * @param array $attributes
  557. */
  558. function startElementQti1($parser, $name, $attributes)
  559. {
  560. global $element_pile;
  561. global $exercise_info;
  562. global $current_question_ident;
  563. global $current_answer_id;
  564. global $current_match_set;
  565. global $currentAssociableChoice;
  566. global $current_question_item_body;
  567. global $record_item_body;
  568. global $non_HTML_tag_to_avoid;
  569. global $current_inlinechoice_id;
  570. global $cardinality;
  571. global $questionTempDir;
  572. global $lastLabelFieldName;
  573. global $lastLabelFieldValue;
  574. array_push($element_pile, $name);
  575. $current_element = end($element_pile);
  576. if (sizeof($element_pile) >= 2) {
  577. $parent_element = $element_pile[sizeof($element_pile) - 2];
  578. } else {
  579. $parent_element = "";
  580. }
  581. if (sizeof($element_pile) >= 3) {
  582. $grand_parent_element = $element_pile[sizeof($element_pile) - 3];
  583. } else {
  584. $grand_parent_element = "";
  585. }
  586. if (sizeof($element_pile) >= 4) {
  587. $great_grand_parent_element = $element_pile[sizeof($element_pile) - 4];
  588. } else {
  589. $great_grand_parent_element = "";
  590. }
  591. if ($record_item_body) {
  592. if ((!in_array($current_element, $non_HTML_tag_to_avoid))) {
  593. $current_question_item_body .= "<" . $name;
  594. foreach ($attributes as $attribute_name => $attribute_value) {
  595. $current_question_item_body .= " " . $attribute_name . "=\"" . $attribute_value . "\"";
  596. }
  597. $current_question_item_body .= ">";
  598. } else {
  599. //in case of FIB question, we replace the IMS-QTI tag b y the correct answer between "[" "]",
  600. //we first save with claroline tags ,then when the answer will be parsed, the claroline tags will be replaced
  601. if ($current_element == 'INLINECHOICEINTERACTION') {
  602. $current_question_item_body .= "**claroline_start**" . $attributes['RESPONSEIDENTIFIER'] . "**claroline_end**";
  603. }
  604. if ($current_element == 'TEXTENTRYINTERACTION') {
  605. $correct_answer_value = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
  606. $current_question_item_body .= "[" . $correct_answer_value . "]";
  607. }
  608. if ($current_element == 'BR') {
  609. $current_question_item_body .= "<br />";
  610. }
  611. }
  612. }
  613. switch ($current_element) {
  614. case 'ASSESSMENT':
  615. // This is the assessment element: we don't care, we just want questions
  616. if (!empty($attributes['TITLE'])) {
  617. $exercise_info['name'] = $attributes['TITLE'];
  618. }
  619. break;
  620. case 'ITEM':
  621. //retrieve current question
  622. $current_question_ident = $attributes['IDENT'];
  623. $exercise_info['question'][$current_question_ident] = array();
  624. $exercise_info['question'][$current_question_ident]['answer'] = array();
  625. $exercise_info['question'][$current_question_ident]['correct_answers'] = array();
  626. $exercise_info['question'][$current_question_ident]['tempdir'] = $questionTempDir;
  627. break;
  628. case 'SECTION':
  629. break;
  630. case 'RESPONSE_LID':
  631. // Retrieve question type
  632. if ("multiple" == strtolower($attributes['RCARDINALITY'])) {
  633. $cardinality = 'multiple';
  634. }
  635. if ("single" == strtolower($attributes['RCARDINALITY'])) {
  636. $cardinality = 'single';
  637. }
  638. //needed for FIB
  639. $current_answer_id = $attributes['IDENT'];
  640. $current_question_item_body = '';
  641. break;
  642. case 'RENDER_CHOICE';
  643. break;
  644. case 'RESPONSE_LABEL':
  645. if (!empty($attributes['IDENT'])) {
  646. $current_answer_id = $attributes['IDENT'];
  647. //set the placeholder for the answer to come (in endElementQti1)
  648. $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id] = '';
  649. }
  650. break;
  651. case 'DECVAR':
  652. if ($parent_element == 'OUTCOMES' && $grand_parent_element == 'RESPROCESSING') {
  653. // The following attributes are available
  654. //$attributes['VARTYPE'];
  655. //$attributes['DEFAULTVAL'];
  656. //$attributes['MINVALUE'];
  657. //$attributes['MAXVALUE'];
  658. }
  659. break;
  660. case 'VAREQUAL':
  661. if ($parent_element == 'CONDITIONVAR' && $grand_parent_element == 'RESPCONDITION') {
  662. // The following attributes are available
  663. //$attributes['RESPIDENT']
  664. }
  665. break;
  666. case 'SETVAR':
  667. if ($parent_element == 'RESPCONDITION') {
  668. // The following attributes are available
  669. //$attributes['ACTION']
  670. }
  671. break;
  672. case 'IMG':
  673. break;
  674. case 'MATTEXT':
  675. if ($parent_element == 'MATERIAL') {
  676. if ($grand_parent_element == 'PRESENTATION') {
  677. $exercise_info['question'][$current_question_ident]['title'] = $current_question_item_body;
  678. }
  679. }
  680. }
  681. }
  682. /**
  683. * Function used by the SAX xml parser when the parser meets a closing tag for QTI1
  684. *
  685. * @param object $parser xml parser created with "xml_parser_create()"
  686. * @param string $name name of the element
  687. * @param array $attributes The element attributes
  688. */
  689. function endElementQti1($parser, $name, $attributes)
  690. {
  691. global $element_pile;
  692. global $exercise_info;
  693. global $current_question_ident;
  694. global $record_item_body;
  695. global $current_question_item_body;
  696. global $non_HTML_tag_to_avoid;
  697. global $cardinality;
  698. global $lastLabelFieldName;
  699. global $lastLabelFieldValue;
  700. global $resourcesLinks;
  701. $current_element = end($element_pile);
  702. if (sizeof($element_pile) >= 2) {
  703. $parent_element = $element_pile[sizeof($element_pile) - 2];
  704. } else {
  705. $parent_element = "";
  706. }
  707. if (sizeof($element_pile) >= 3) {
  708. $grand_parent_element = $element_pile[sizeof($element_pile) - 3];
  709. } else {
  710. $grand_parent_element = "";
  711. }
  712. if (sizeof($element_pile) >= 4) {
  713. $great_grand_parent_element = $element_pile[sizeof($element_pile) - 4];
  714. } else {
  715. $great_grand_parent_element = "";
  716. }
  717. //treat the record of the full content of itembody tag :
  718. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  719. $current_question_item_body .= "</" . $name . ">";
  720. }
  721. switch ($name) {
  722. case 'MATTEXT':
  723. if ($parent_element == 'MATERIAL') {
  724. // For some reason an item in a hierarchy <item><presentation><material><mattext> doesn't seem to
  725. // catch the grandfather 'presentation', so we check for 'item' as a patch (great-grand-father)
  726. if ($grand_parent_element == 'PRESENTATION' OR $grand_parent_element == 'ITEM') {
  727. $exercise_info['question'][$current_question_ident]['title'] = $current_question_item_body;
  728. $current_question_item_body = '';
  729. } elseif ($grand_parent_element == 'RESPONSE_LABEL') {
  730. $last = '';
  731. foreach ($exercise_info['question'][$current_question_ident]['answer'] as $key => $value) {
  732. $last = $key;
  733. }
  734. $exercise_info['question'][$current_question_ident]['answer'][$last]['value'] = $current_question_item_body;
  735. $current_question_item_body = '';
  736. }
  737. }
  738. case 'RESPONSE_LID':
  739. // Retrieve question type
  740. if (!isset($exercise_info['question'][$current_question_ident]['type'])) {
  741. if ("multiple" == strtolower($attributes['RCARDINALITY'])) {
  742. $exercise_info['question'][$current_question_ident]['type'] = MCMA;
  743. }
  744. if ("single" == strtolower($attributes['RCARDINALITY'])) {
  745. $exercise_info['question'][$current_question_ident]['type'] = MCUA;
  746. }
  747. }
  748. $current_question_item_body = '';
  749. //needed for FIB
  750. $current_answer_id = $attributes['IDENT'];
  751. break;
  752. case 'ITEMMETADATA':
  753. $current_question_item_body = '';
  754. break;
  755. }
  756. array_pop($element_pile);
  757. }
  758. /**
  759. * QTI1 element parser
  760. * @param $parser
  761. * @param $data
  762. */
  763. function elementDataQti1($parser, $data)
  764. {
  765. global $element_pile;
  766. global $exercise_info;
  767. global $current_question_ident;
  768. global $current_answer_id;
  769. global $current_match_set;
  770. global $currentAssociableChoice;
  771. global $current_question_item_body;
  772. global $record_item_body;
  773. global $non_HTML_tag_to_avoid;
  774. global $current_inlinechoice_id;
  775. global $cardinality;
  776. global $lastLabelFieldName;
  777. global $lastLabelFieldValue;
  778. global $resourcesLinks;
  779. $current_element = end($element_pile);
  780. if (sizeof($element_pile) >= 2) {
  781. $parent_element = $element_pile[sizeof($element_pile) - 2];
  782. } else {
  783. $parent_element = "";
  784. }
  785. //treat the record of the full content of itembody tag (needed for question statment and/or FIB text:
  786. if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
  787. $current_question_item_body .= $data;
  788. }
  789. switch ($current_element) {
  790. case 'FIELDLABEL':
  791. if (!empty($data)) {
  792. $lastLabelFieldName = $current_element;
  793. $lastLabelFieldValue = $data;
  794. }
  795. case 'FIELDENTRY':
  796. $current_question_item_body = $data;
  797. switch ($lastLabelFieldValue) {
  798. case 'cc_profile':
  799. // The following values might be proprietary in MATRIX software. No specific reference
  800. // in QTI doc: http://www.imsglobal.org/question/qtiv1p2/imsqti_asi_infov1p2.html#1415855
  801. switch ($data) {
  802. case 'cc.true_false.v0p1':
  803. //this is a true-false question (translated to multiple choice in Chamilo because true-false comes with "I don't know")
  804. $exercise_info['question'][$current_question_ident]['type'] = MCUA;
  805. break;
  806. case 'cc.multiple_choice.v0p1':
  807. //this is a multiple choice (unique answer) question
  808. $exercise_info['question'][$current_question_ident]['type'] = MCUA;
  809. break;
  810. case 'cc.multiple_response.v0p1':
  811. //this is a multiple choice (unique answer) question
  812. $exercise_info['question'][$current_question_ident]['type'] = MCMA;
  813. break;
  814. }
  815. break;
  816. case 'cc_weighting':
  817. //defines the total weight of the question
  818. $exercise_info['question'][$current_question_ident]['default_weighting'] = $lastLabelFieldValue;
  819. break;
  820. case 'assessment_question_identifierref':
  821. //placeholder - not used yet
  822. // Possible values are not defined by qti v1.2
  823. break;
  824. }
  825. break;
  826. case 'MATTEXT':
  827. // Replace relative links by links to the documents in the course
  828. // $resourcesLinks is only defined by qtiProcessManifest()
  829. if (isset($resourcesLinks) && isset($resourcesLinks['manifest']) && isset($resourcesLinks['web'])) {
  830. foreach ($resourcesLinks['manifest'] as $key=>$value) {
  831. $data = preg_replace('|' . $value . '|', $resourcesLinks['web'][$key], $data);
  832. }
  833. }
  834. if (!empty($current_question_item_body)) {
  835. $current_question_item_body .= $data;
  836. } else {
  837. $current_question_item_body = $data;
  838. }
  839. break;
  840. case 'VAREQUAL':
  841. $lastLabelFieldName = 'VAREQUAL';
  842. $lastLabelFieldValue = $data;
  843. break;
  844. case 'SETVAR':
  845. if ($parent_element == 'RESPCONDITION') {
  846. // The following attributes are available
  847. //$attributes['ACTION']
  848. $exercise_info['question'][$current_question_ident]['correct_answers'][] = $lastLabelFieldValue;
  849. $exercise_info['question'][$current_question_ident]['weighting'][$lastLabelFieldValue] = $data;
  850. }
  851. break;
  852. }
  853. }
  854. /**
  855. * Check if a given file is an IMS/QTI question bank file
  856. * @param string $filePath The absolute filepath
  857. * @return bool Whether it is an IMS/QTI question bank or not
  858. */
  859. function isQtiQuestionBank($filePath)
  860. {
  861. $data = file_get_contents($filePath);
  862. if (!empty($data)) {
  863. $match = preg_match('/ims_qtiasiv(\d)p(\d)/', $data);
  864. if ($match) {
  865. return true;
  866. }
  867. }
  868. return false;
  869. }
  870. /**
  871. * Check if a given file is an IMS/QTI manifest file (listing of extra files)
  872. * @param string $filePath The absolute filepath
  873. * @return bool Whether it is an IMS/QTI manifest file or not
  874. */
  875. function isQtiManifest($filePath)
  876. {
  877. $data = file_get_contents($filePath);
  878. if (!empty($data)) {
  879. $match = preg_match('/imsccv(\d)p(\d)/', $data);
  880. if ($match) {
  881. return true;
  882. }
  883. }
  884. return false;
  885. }
  886. /**
  887. * Processes an IMS/QTI manifest file: store links to new files to be able to transform them into the questions text
  888. * @param string $filePath The absolute filepath
  889. * @param array $links List of filepaths changes
  890. * @return bool
  891. */
  892. function qtiProcessManifest($filePath)
  893. {
  894. $xml = simplexml_load_file($filePath);
  895. $course = api_get_course_info();
  896. $sessionId = api_get_session_id();
  897. $courseDir = $course['path'];
  898. $sysPath = api_get_path(SYS_COURSE_PATH);
  899. $exercisesSysPath = $sysPath . $courseDir . '/document/';
  900. $webPath = api_get_path(WEB_CODE_PATH);
  901. $exercisesWebPath = $webPath . 'document/document.php?' . api_get_cidreq() . '&action=download&id=';
  902. $links = array(
  903. 'manifest' => array(),
  904. 'system' => array(),
  905. 'web' => array(),
  906. );
  907. $tableDocuments = Database::get_course_table(TABLE_DOCUMENT);
  908. $countResources = count($xml->resources->resource->file);
  909. for ($i=0; $i < $countResources; $i++) {
  910. $file = $xml->resources->resource->file[$i];
  911. $href = '';
  912. foreach ($file->attributes() as $key => $value) {
  913. if ($key == 'href') {
  914. if (substr($value, -3, 3) != 'xml') {
  915. $href = $value;
  916. }
  917. }
  918. }
  919. if (!empty($href)) {
  920. $links['manifest'][] = (string) $href;
  921. $links['system'][] = $exercisesSysPath . strtolower($href);
  922. $specialHref = Database::escape_string(preg_replace('/_/', '-', strtolower($href)));
  923. $specialHref = preg_replace('/(-){2,8}/', '-', $specialHref);
  924. $sql = "SELECT iid FROM " . $tableDocuments . " WHERE c_id = " . $course['real_id'] . " AND session_id = $sessionId AND path = '/" . $specialHref . "'";
  925. $result = Database::query($sql);
  926. $documentId = 0;
  927. while ($row = Database::fetch_assoc($result)) {
  928. $documentId = $row['iid'];
  929. }
  930. $links['web'][] = $exercisesWebPath . $documentId;
  931. }
  932. }
  933. return $links;
  934. }