exercise_import.inc.php 42 KB

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