MoodleImport.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class MoodleImport
  5. *
  6. * @author José Loguercio <jose.loguercio@beeznest.com>,
  7. * @author Julio Montoya <gugli100@gmail.com>
  8. *
  9. * @package chamilo.library
  10. */
  11. class MoodleImport
  12. {
  13. /**
  14. * Import moodle file
  15. *
  16. * @param resource $uploadedFile *.* mbz file moodle course backup
  17. * @return bool
  18. */
  19. public function import($uploadedFile)
  20. {
  21. $file = $uploadedFile['tmp_name'];
  22. if (is_file($file) && is_readable($file)) {
  23. $package = new PclZip($file);
  24. $mainFileKey = 0;
  25. $packageContent = $package->listContent();
  26. if (!empty($packageContent)) {
  27. foreach ($packageContent as $index => $value) {
  28. if ($value['filename'] == 'moodle_backup.xml') {
  29. $mainFileKey = $index;
  30. break;
  31. }
  32. }
  33. }
  34. if (!$mainFileKey) {
  35. Display::addFlash(
  36. Display::return_message(
  37. get_lang('FailedToImportThisIsNotAMoodleFile'),
  38. 'error'
  39. )
  40. );
  41. }
  42. $folder = api_get_unique_id();
  43. $destinationDir = api_get_path(SYS_ARCHIVE_PATH).$folder;
  44. $coursePath = api_get_course_path();
  45. $sessionId = api_get_session_id();
  46. $groupId = api_get_group_id();
  47. $documentPath = api_get_path(SYS_COURSE_PATH).$coursePath.'/document';
  48. $courseInfo = api_get_course_info();
  49. mkdir($destinationDir, api_get_permissions_for_new_directories(), true);
  50. create_unexisting_directory(
  51. $courseInfo,
  52. api_get_user_id(),
  53. $sessionId,
  54. $groupId,
  55. null,
  56. $documentPath,
  57. '/moodle',
  58. 'Moodle Docs',
  59. 0
  60. );
  61. $package->extract(
  62. PCLZIP_OPT_PATH,
  63. $destinationDir
  64. );
  65. // This process will upload all question resource files
  66. $filesXml = @file_get_contents($destinationDir.'/files.xml');
  67. $mainFileModuleValues = $this->getAllQuestionFiles($filesXml);
  68. $currentResourceFilePath = $destinationDir.'/files/';
  69. $importedFiles = [];
  70. foreach ($mainFileModuleValues as $fileInfo) {
  71. $dirs = new RecursiveDirectoryIterator($currentResourceFilePath);
  72. foreach (new RecursiveIteratorIterator($dirs) as $file) {
  73. if (is_file($file) && strpos($file, $fileInfo['contenthash']) !== false) {
  74. $files = [];
  75. $files['file']['name'] = $fileInfo['filename'];
  76. $files['file']['tmp_name'] = $file->getPathname();
  77. $files['file']['type'] = $fileInfo['mimetype'];
  78. $files['file']['error'] = 0;
  79. $files['file']['size'] = $fileInfo['filesize'];
  80. $files['file']['from_file'] = true;
  81. $files['file']['move_file'] = true;
  82. $_POST['language'] = $courseInfo['language'];
  83. $_POST['moodle_import'] = true;
  84. $data = DocumentManager::upload_document(
  85. $files,
  86. '/moodle',
  87. isset($fileInfo['title']) ? $fileInfo['title'] : pathinfo($fileInfo['filename'], PATHINFO_FILENAME),
  88. '',
  89. null,
  90. null,
  91. true,
  92. true,
  93. 'file',
  94. // This is to validate spaces as hyphens
  95. false
  96. );
  97. if ($data) {
  98. $importedFiles[$fileInfo['filename']] = basename($data['path']);
  99. }
  100. }
  101. }
  102. }
  103. $xml = @file_get_contents($destinationDir.'/moodle_backup.xml');
  104. $doc = new DOMDocument();
  105. $res = @$doc->loadXML($xml);
  106. if ($res) {
  107. $activities = $doc->getElementsByTagName('activity');
  108. foreach ($activities as $activity) {
  109. if ($activity->childNodes->length) {
  110. $currentItem = [];
  111. foreach ($activity->childNodes as $item) {
  112. $currentItem[$item->nodeName] = $item->nodeValue;
  113. }
  114. $moduleName = isset($currentItem['modulename']) ? $currentItem['modulename'] : false;
  115. switch ($moduleName) {
  116. case 'forum':
  117. require_once '../forum/forumfunction.inc.php';
  118. $catForumValues = [];
  119. // Read the current forum module xml.
  120. $moduleDir = $currentItem['directory'];
  121. $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml');
  122. $moduleValues = $this->readForumModule($moduleXml);
  123. // Create a Forum category based on Moodle forum type.
  124. $catForumValues['forum_category_title'] = $moduleValues['type'];
  125. $catForumValues['forum_category_comment'] = '';
  126. $catId = store_forumcategory(
  127. $catForumValues,
  128. $courseInfo,
  129. false
  130. );
  131. $forumValues = [];
  132. $forumValues['forum_title'] = $moduleValues['name'];
  133. $forumValues['forum_image'] = '';
  134. $forumValues['forum_comment'] = $moduleValues['intro'];
  135. $forumValues['forum_category'] = $catId;
  136. $forumValues['moderated'] = 0;
  137. store_forum($forumValues, $courseInfo);
  138. break;
  139. case 'quiz':
  140. // Read the current quiz module xml.
  141. // The quiz case is the very complicate process of all the import.
  142. // Please if you want to review the script, try to see the readingXML functions.
  143. // The readingXML functions in this clases do all the mayor work here.
  144. $moduleDir = $currentItem['directory'];
  145. $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml');
  146. $questionsXml = @file_get_contents($destinationDir.'/questions.xml');
  147. $moduleValues = $this->readQuizModule($moduleXml);
  148. // At this point we got all the prepared resources from Moodle file
  149. // $moduleValues variable contains all the necesary info to the quiz import
  150. // var_dump($moduleValues); // <-- uncomment this to see the final array
  151. $exercise = new Exercise($courseInfo['real_id']);
  152. $title = Exercise::format_title_variable($moduleValues['name']);
  153. $exercise->updateTitle($title);
  154. $exercise->updateDescription($moduleValues['intro']);
  155. $exercise->updateAttempts($moduleValues['attempts_number']);
  156. $exercise->updateFeedbackType(0);
  157. // Match shuffle question with chamilo
  158. switch ($moduleValues['shufflequestions']) {
  159. case '0':
  160. $exercise->setRandom(0);
  161. break;
  162. case '1':
  163. $exercise->setRandom(-1);
  164. break;
  165. default:
  166. $exercise->setRandom(0);
  167. }
  168. $exercise->updateRandomAnswers($moduleValues['shuffleanswers']);
  169. // @todo divide to minutes
  170. $exercise->updateExpiredTime($moduleValues['timelimit']);
  171. if ($moduleValues['questionsperpage'] == 1) {
  172. $exercise->updateType(2);
  173. } else {
  174. $exercise->updateType(1);
  175. }
  176. // Create the new Quiz
  177. $exercise->save();
  178. // Ok, we got the Quiz and create it, now its time to add the Questions
  179. foreach ($moduleValues['question_instances'] as $index => $question) {
  180. $questionsValues = $this->readMainQuestionsXml(
  181. $questionsXml,
  182. $question['questionid']
  183. );
  184. $moduleValues['question_instances'][$index] = $questionsValues;
  185. // Set Question Type from Moodle XML element <qtype>
  186. $qType = $moduleValues['question_instances'][$index]['qtype'];
  187. // Add the matched chamilo question type to the array
  188. $moduleValues['question_instances'][$index]['chamilo_qtype'] = $this->matchMoodleChamiloQuestionTypes($qType);
  189. $questionInstance = Question::getInstance(
  190. $moduleValues['question_instances'][$index]['chamilo_qtype']
  191. );
  192. if ($questionInstance) {
  193. $questionInstance->updateTitle(
  194. $moduleValues['question_instances'][$index]['name']
  195. );
  196. $questionText = $moduleValues['question_instances'][$index]['questiontext'];
  197. // Replace the path from @@PLUGINFILE@@ to a correct chamilo path
  198. $questionText = str_replace(
  199. '@@PLUGINFILE@@',
  200. '/courses/'.$coursePath.'/document/moodle',
  201. $questionText
  202. );
  203. if ($importedFiles) {
  204. $this->fixPathInText($importedFiles, $questionText);
  205. }
  206. $questionInstance->updateDescription($questionText);
  207. $questionInstance->updateLevel(1);
  208. $questionInstance->updateCategory(0);
  209. //Save normal question if NOT media
  210. if ($questionInstance->type != MEDIA_QUESTION) {
  211. $questionInstance->save($exercise);
  212. // modify the exercise
  213. $exercise->addToList($questionInstance->id);
  214. $exercise->update_question_positions();
  215. }
  216. $questionList = $moduleValues['question_instances'][$index]['plugin_qtype_'.$qType.'_question'];
  217. $currentQuestion = $moduleValues['question_instances'][$index];
  218. $this->processAnswers(
  219. $exercise,
  220. $questionList,
  221. $qType,
  222. $questionInstance,
  223. $currentQuestion,
  224. $importedFiles
  225. );
  226. }
  227. }
  228. break;
  229. case 'resource':
  230. // Read the current resource module xml.
  231. $moduleDir = $currentItem['directory'];
  232. $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml');
  233. $filesXml = @file_get_contents($destinationDir.'/files.xml');
  234. $moduleValues = $this->readResourceModule($moduleXml);
  235. $mainFileModuleValues = $this->readMainFilesXml(
  236. $filesXml,
  237. $moduleValues['contextid']
  238. );
  239. $fileInfo = array_merge($moduleValues, $mainFileModuleValues, $currentItem);
  240. $currentResourceFilePath = $destinationDir.'/files/';
  241. $dirs = new RecursiveDirectoryIterator($currentResourceFilePath);
  242. foreach (new RecursiveIteratorIterator($dirs) as $file) {
  243. if (is_file($file) && strpos($file, $fileInfo['contenthash']) !== false) {
  244. $files = [];
  245. $files['file']['name'] = $fileInfo['filename'];
  246. $files['file']['tmp_name'] = $file->getPathname();
  247. $files['file']['type'] = $fileInfo['mimetype'];
  248. $files['file']['error'] = 0;
  249. $files['file']['size'] = $fileInfo['filesize'];
  250. $files['file']['from_file'] = true;
  251. $files['file']['move_file'] = true;
  252. $_POST['language'] = $courseInfo['language'];
  253. $_POST['moodle_import'] = true;
  254. DocumentManager::upload_document(
  255. $files,
  256. '/moodle',
  257. $fileInfo['title'],
  258. '',
  259. null,
  260. null,
  261. true,
  262. true
  263. );
  264. }
  265. }
  266. break;
  267. case 'url':
  268. // Read the current url module xml.
  269. $moduleDir = $currentItem['directory'];
  270. $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml');
  271. $moduleValues = $this->readUrlModule($moduleXml);
  272. $_POST['title'] = $moduleValues['name'];
  273. $_POST['url'] = $moduleValues['externalurl'];
  274. $_POST['description'] = $moduleValues['intro'];
  275. $_POST['category_id'] = 0;
  276. $_POST['target'] = '_blank';
  277. Link::addlinkcategory("link");
  278. break;
  279. }
  280. }
  281. }
  282. } else {
  283. removeDir($destinationDir);
  284. return false;
  285. }
  286. } else {
  287. return false;
  288. }
  289. removeDir($destinationDir);
  290. return $packageContent[$mainFileKey];
  291. }
  292. /**
  293. * Read and validate the forum module XML
  294. *
  295. * @param resource $moduleXml XML file
  296. * @return mixed | array if is a valid xml file, false otherwise
  297. */
  298. public function readForumModule($moduleXml)
  299. {
  300. $moduleDoc = new DOMDocument();
  301. $moduleRes = @$moduleDoc->loadXML($moduleXml);
  302. if ($moduleRes) {
  303. $activities = $moduleDoc->getElementsByTagName('forum');
  304. $currentItem = [];
  305. foreach ($activities as $activity) {
  306. if ($activity->childNodes->length) {
  307. foreach ($activity->childNodes as $item) {
  308. $currentItem[$item->nodeName] = $item->nodeValue;
  309. }
  310. }
  311. }
  312. return $currentItem;
  313. }
  314. return false;
  315. }
  316. /**
  317. * Read and validate the resource module XML
  318. *
  319. * @param resource $moduleXml XML file
  320. * @return mixed | array if is a valid xml file, false otherwise
  321. */
  322. public function readResourceModule($moduleXml)
  323. {
  324. $moduleDoc = new DOMDocument();
  325. $moduleRes = @$moduleDoc->loadXML($moduleXml);
  326. if ($moduleRes) {
  327. $activities = $moduleDoc->getElementsByTagName('resource');
  328. $mainActivity = $moduleDoc->getElementsByTagName('activity');
  329. $contextId = $mainActivity->item(0)->getAttribute('contextid');
  330. $currentItem = [];
  331. foreach ($activities as $activity) {
  332. if ($activity->childNodes->length) {
  333. foreach ($activity->childNodes as $item) {
  334. $currentItem[$item->nodeName] = $item->nodeValue;
  335. }
  336. }
  337. }
  338. $currentItem['contextid'] = $contextId;
  339. return $currentItem;
  340. }
  341. return false;
  342. }
  343. /**
  344. * Read and validate the url module XML
  345. *
  346. * @param resource $moduleXml XML file
  347. * @return mixed | array if is a valid xml file, false otherwise
  348. */
  349. public function readUrlModule($moduleXml)
  350. {
  351. $moduleDoc = new DOMDocument();
  352. $moduleRes = @$moduleDoc->loadXML($moduleXml);
  353. if ($moduleRes) {
  354. $activities = $moduleDoc->getElementsByTagName('url');
  355. $currentItem = [];
  356. foreach ($activities as $activity) {
  357. if ($activity->childNodes->length) {
  358. foreach ($activity->childNodes as $item) {
  359. $currentItem[$item->nodeName] = $item->nodeValue;
  360. }
  361. }
  362. }
  363. return $currentItem;
  364. }
  365. return false;
  366. }
  367. /**
  368. * Read and validate the quiz module XML
  369. *
  370. * @param resource $moduleXml XML file
  371. * @return mixed | array if is a valid xml file, false otherwise
  372. */
  373. public function readQuizModule($moduleXml)
  374. {
  375. $moduleDoc = new DOMDocument();
  376. $moduleRes = @$moduleDoc->loadXML($moduleXml);
  377. if ($moduleRes) {
  378. $activities = $moduleDoc->getElementsByTagName('quiz');
  379. $currentItem = [];
  380. foreach ($activities as $activity) {
  381. if ($activity->childNodes->length) {
  382. foreach ($activity->childNodes as $item) {
  383. $currentItem[$item->nodeName] = $item->nodeValue;
  384. }
  385. }
  386. }
  387. $questions = $moduleDoc->getElementsByTagName('question_instance');
  388. $questionList = [];
  389. $counter = 0;
  390. foreach ($questions as $question) {
  391. if ($question->childNodes->length) {
  392. foreach ($question->childNodes as $item) {
  393. $questionList[$counter][$item->nodeName] = $item->nodeValue;
  394. }
  395. $counter++;
  396. }
  397. }
  398. $currentItem['question_instances'] = $questionList;
  399. return $currentItem;
  400. }
  401. return false;
  402. }
  403. /**
  404. * Search the current file resource in main Files XML
  405. *
  406. * @param resource $filesXml XML file
  407. * @param int $contextId
  408. * @return mixed | array if is a valid xml file, false otherwise
  409. */
  410. public function readMainFilesXml($filesXml, $contextId)
  411. {
  412. $moduleDoc = new DOMDocument();
  413. $moduleRes = @$moduleDoc->loadXML($filesXml);
  414. if ($moduleRes) {
  415. $activities = $moduleDoc->getElementsByTagName('file');
  416. $currentItem = [];
  417. foreach ($activities as $activity) {
  418. if ($activity->childNodes->length) {
  419. $isThisItemThatIWant = false;
  420. foreach ($activity->childNodes as $item) {
  421. if (!$isThisItemThatIWant && $item->nodeName == 'contenthash') {
  422. $currentItem['contenthash'] = $item->nodeValue;
  423. }
  424. if ($item->nodeName == 'contextid' &&
  425. intval($item->nodeValue) == intval($contextId) && !$isThisItemThatIWant
  426. ) {
  427. $isThisItemThatIWant = true;
  428. continue;
  429. }
  430. if ($isThisItemThatIWant && $item->nodeName == 'filename') {
  431. $currentItem['filename'] = $item->nodeValue;
  432. }
  433. if ($isThisItemThatIWant && $item->nodeName == 'filesize') {
  434. $currentItem['filesize'] = $item->nodeValue;
  435. }
  436. if ($isThisItemThatIWant && $item->nodeName == 'mimetype' &&
  437. $item->nodeValue == 'document/unknown'
  438. ) {
  439. break;
  440. }
  441. if ($isThisItemThatIWant && $item->nodeName == 'mimetype' &&
  442. $item->nodeValue !== 'document/unknown'
  443. ) {
  444. $currentItem['mimetype'] = $item->nodeValue;
  445. break 2;
  446. }
  447. }
  448. }
  449. }
  450. return $currentItem;
  451. }
  452. return false;
  453. }
  454. /**
  455. * Search the current question resource in main Questions XML
  456. *
  457. * @param resource $questionsXml XML file
  458. * @param int $questionId
  459. * @return mixed | array if is a valid xml file, false otherwise
  460. */
  461. public function readMainQuestionsXml($questionsXml, $questionId)
  462. {
  463. $moduleDoc = new DOMDocument();
  464. $moduleRes = @$moduleDoc->loadXML($questionsXml);
  465. if ($moduleRes) {
  466. $questions = $moduleDoc->getElementsByTagName('question');
  467. $currentItem = [];
  468. foreach ($questions as $question) {
  469. if (intval($question->getAttribute('id')) == $questionId) {
  470. if ($question->childNodes->length) {
  471. $currentItem['questionid'] = $questionId;
  472. $questionType = '';
  473. foreach ($question->childNodes as $item) {
  474. $currentItem[$item->nodeName] = $item->nodeValue;
  475. if ($item->nodeName == 'qtype') {
  476. $questionType = $item->nodeValue;
  477. }
  478. if ($item->nodeName == 'plugin_qtype_'.$questionType.'_question') {
  479. $answer = $item->getElementsByTagName($this->getQuestionTypeAnswersTag($questionType));
  480. $currentItem['plugin_qtype_'.$questionType.'_question'] = [];
  481. for ($i = 0; $i <= $answer->length - 1; $i++) {
  482. $currentItem['plugin_qtype_'.$questionType.'_question'][$i]['answerid'] = $answer->item($i)->getAttribute('id');
  483. foreach ($answer->item($i)->childNodes as $properties) {
  484. $currentItem['plugin_qtype_'.$questionType.'_question'][$i][$properties->nodeName] = $properties->nodeValue;
  485. }
  486. }
  487. $typeValues = $item->getElementsByTagName($this->getQuestionTypeOptionsTag($questionType));
  488. for ($i = 0; $i <= $typeValues->length - 1; $i++) {
  489. foreach ($typeValues->item($i)->childNodes as $properties) {
  490. $currentItem[$questionType.'_values'][$properties->nodeName] = $properties->nodeValue;
  491. if ($properties->nodeName == 'sequence') {
  492. $sequence = $properties->nodeValue;
  493. $sequenceIds = explode(',', $sequence);
  494. foreach ($sequenceIds as $qId) {
  495. $questionMatch = $this->readMainQuestionsXml($questionsXml, $qId);
  496. $currentItem['plugin_qtype_'.$questionType.'_question'][] = $questionMatch;
  497. }
  498. }
  499. }
  500. }
  501. }
  502. }
  503. }
  504. }
  505. }
  506. $this->traverseArray($currentItem, ['#text', 'question_hints', 'tags']);
  507. return $currentItem;
  508. }
  509. return false;
  510. }
  511. /**
  512. * return the correct question type options tag
  513. *
  514. * @param string $questionType name
  515. * @return string question type tag
  516. */
  517. public function getQuestionTypeOptionsTag($questionType)
  518. {
  519. switch ($questionType) {
  520. case 'match':
  521. case 'ddmatch':
  522. return 'matchoptions';
  523. break;
  524. default:
  525. return $questionType;
  526. break;
  527. }
  528. }
  529. /**
  530. * return the correct question type answers tag
  531. *
  532. * @param string $questionType name
  533. * @return string question type tag
  534. */
  535. public function getQuestionTypeAnswersTag($questionType)
  536. {
  537. switch ($questionType) {
  538. case 'match':
  539. case 'ddmatch':
  540. return 'match';
  541. break;
  542. default:
  543. return 'answer';
  544. break;
  545. }
  546. }
  547. /**
  548. *
  549. * @param string $moodleQuestionType
  550. * @return integer Chamilo question type
  551. */
  552. public function matchMoodleChamiloQuestionTypes($moodleQuestionType)
  553. {
  554. switch ($moodleQuestionType) {
  555. case 'multichoice':
  556. return UNIQUE_ANSWER;
  557. break;
  558. case 'multianswer':
  559. case 'shortanswer':
  560. case 'match':
  561. return FILL_IN_BLANKS;
  562. break;
  563. case 'essay':
  564. return FREE_ANSWER;
  565. break;
  566. case 'truefalse':
  567. return UNIQUE_ANSWER_NO_OPTION;
  568. break;
  569. }
  570. }
  571. /**
  572. * Fix moodle files that contains spaces
  573. * @param array $importedFiles
  574. * @param string $text
  575. * @return mixed
  576. */
  577. public function fixPathInText($importedFiles, &$text)
  578. {
  579. if ($importedFiles) {
  580. foreach ($importedFiles as $old => $new) {
  581. // Ofaj fix moodle file names
  582. // In some questions moodle text contains file with name like:
  583. // Bild%20Check-In-Formular%20Ausfu%CC%88llen.jpg"
  584. // rawurlencode function transforms '' (whitespace) to %20 and so on
  585. $text = str_replace(rawurlencode($old), $new, $text);
  586. }
  587. }
  588. return $text;
  589. }
  590. /**
  591. * Process Moodle Answers to Chamilo
  592. *
  593. * @param Exercise $exercise
  594. * @param array $questionList
  595. * @param string $questionType
  596. * @param Question $questionInstance Question/Answer instance
  597. * @param array $currentQuestion
  598. * @param array $importedFiles
  599. * @return integer db response
  600. */
  601. public function processAnswers(
  602. $exercise,
  603. $questionList,
  604. $questionType,
  605. $questionInstance,
  606. $currentQuestion,
  607. $importedFiles
  608. ) {
  609. switch ($questionType) {
  610. case 'multichoice':
  611. $objAnswer = new Answer($questionInstance->id);
  612. $questionWeighting = 0;
  613. foreach ($questionList as $slot => $answer) {
  614. $this->processUniqueAnswer(
  615. $objAnswer,
  616. $answer,
  617. $slot + 1,
  618. $questionWeighting,
  619. $importedFiles
  620. );
  621. }
  622. // saves the answers into the data base
  623. $objAnswer->save();
  624. // sets the total weighting of the question
  625. $questionInstance->updateWeighting($questionWeighting);
  626. $questionInstance->save($exercise);
  627. return true;
  628. break;
  629. case 'multianswer':
  630. $objAnswer = new Answer($questionInstance->id);
  631. $coursePath = api_get_course_path();
  632. $placeholder = str_replace(
  633. '@@PLUGINFILE@@',
  634. '/courses/'.$coursePath.'/document/moodle',
  635. $currentQuestion['questiontext']
  636. );
  637. $optionsValues = [];
  638. foreach ($questionList as $slot => $subQuestion) {
  639. $qtype = $subQuestion['qtype'];
  640. $optionsValues[] = $this->processFillBlanks(
  641. $objAnswer,
  642. $qtype,
  643. $subQuestion['plugin_qtype_'.$qtype.'_question'],
  644. $placeholder,
  645. $slot + 1,
  646. $importedFiles
  647. );
  648. }
  649. $answerOptionsWeight = '::';
  650. $answerOptionsSize = '';
  651. $questionWeighting = 0;
  652. foreach ($optionsValues as $index => $value) {
  653. $questionWeighting += $value['weight'];
  654. $answerOptionsWeight .= $value['weight'].',';
  655. $answerOptionsSize .= $value['size'].',';
  656. }
  657. $answerOptionsWeight = substr($answerOptionsWeight, 0, -1);
  658. $answerOptionsSize = substr($answerOptionsSize, 0, -1);
  659. $answerOptions = $answerOptionsWeight.':'.$answerOptionsSize.':0@';
  660. $placeholder = $placeholder.PHP_EOL.$answerOptions;
  661. // This is a minor trick to clean the question description that in a multianswer is the main placeholder
  662. $questionInstance->updateDescription('');
  663. // sets the total weighting of the question
  664. $questionInstance->updateWeighting($questionWeighting);
  665. $questionInstance->save($exercise);
  666. $this->fixPathInText($importedFiles, $placeholder);
  667. // saves the answers into the data base
  668. $objAnswer->createAnswer($placeholder, 0, '', 0, 1);
  669. $objAnswer->save();
  670. return true;
  671. case 'match':
  672. $objAnswer = new Answer($questionInstance->id);
  673. $placeholder = '';
  674. $optionsValues = $this->processFillBlanks(
  675. $objAnswer,
  676. 'match',
  677. $questionList,
  678. $placeholder,
  679. 0,
  680. $importedFiles
  681. );
  682. $answerOptionsWeight = '::';
  683. $answerOptionsSize = '';
  684. $questionWeighting = 0;
  685. foreach ($optionsValues as $index => $value) {
  686. $questionWeighting += $value['weight'];
  687. $answerOptionsWeight .= $value['weight'].',';
  688. $answerOptionsSize .= $value['size'].',';
  689. }
  690. $answerOptionsWeight = substr($answerOptionsWeight, 0, -1);
  691. $answerOptionsSize = substr($answerOptionsSize, 0, -1);
  692. $answerOptions = $answerOptionsWeight.':'.$answerOptionsSize.':0@';
  693. $placeholder = $placeholder.PHP_EOL.$answerOptions;
  694. // sets the total weighting of the question
  695. $questionInstance->updateWeighting($questionWeighting);
  696. $questionInstance->save($exercise);
  697. // saves the answers into the database
  698. $this->fixPathInText($importedFiles, $placeholder);
  699. $objAnswer->createAnswer($placeholder, 0, '', 0, 1);
  700. $objAnswer->save();
  701. return true;
  702. break;
  703. case 'shortanswer':
  704. case 'ddmatch':
  705. $questionWeighting = $currentQuestion['defaultmark'];
  706. $questionInstance->updateWeighting($questionWeighting);
  707. $questionInstance->updateDescription(get_lang('ThisQuestionIsNotSupportedYet'));
  708. $questionInstance->save($exercise);
  709. return false;
  710. break;
  711. case 'essay':
  712. $questionWeighting = $currentQuestion['defaultmark'];
  713. $questionInstance->updateWeighting($questionWeighting);
  714. $questionInstance->save($exercise);
  715. return true;
  716. break;
  717. case 'truefalse':
  718. $objAnswer = new Answer($questionInstance->id);
  719. $questionWeighting = 0;
  720. foreach ($questionList as $slot => $answer) {
  721. $this->processTrueFalse(
  722. $objAnswer,
  723. $answer,
  724. $slot + 1,
  725. $questionWeighting,
  726. $importedFiles
  727. );
  728. }
  729. // saves the answers into the data base
  730. $objAnswer->save();
  731. // sets the total weighting of the question
  732. $questionInstance->updateWeighting($questionWeighting);
  733. $questionInstance->save($exercise);
  734. return false;
  735. break;
  736. default:
  737. return false;
  738. break;
  739. }
  740. }
  741. /**
  742. * Process Chamilo Unique Answer
  743. *
  744. * @param object $objAnswer
  745. * @param array $answerValues
  746. * @param integer $position
  747. * @param integer $questionWeighting
  748. * @param array $importedFiles
  749. * @return integer db response
  750. */
  751. public function processUniqueAnswer(
  752. $objAnswer,
  753. $answerValues,
  754. $position,
  755. &$questionWeighting,
  756. $importedFiles
  757. ) {
  758. $correct = intval($answerValues['fraction']) ? intval($answerValues['fraction']) : 0;
  759. $answer = $answerValues['answertext'];
  760. $comment = $answerValues['feedback'];
  761. $weighting = $answerValues['fraction'];
  762. $weighting = abs($weighting);
  763. if ($weighting > 0) {
  764. $questionWeighting += $weighting;
  765. }
  766. $goodAnswer = $correct ? true : false;
  767. $this->fixPathInText($importedFiles, $answer);
  768. $objAnswer->createAnswer(
  769. $answer,
  770. $goodAnswer,
  771. $comment,
  772. $weighting,
  773. $position,
  774. null,
  775. null,
  776. ''
  777. );
  778. }
  779. /**
  780. * Process Chamilo True False
  781. *
  782. * @param object $objAnswer
  783. * @param array $answerValues
  784. * @param integer $position
  785. * @param integer $questionWeighting
  786. * @param array $importedFiles
  787. *
  788. * @return integer db response
  789. */
  790. public function processTrueFalse(
  791. $objAnswer,
  792. $answerValues,
  793. $position,
  794. &$questionWeighting,
  795. $importedFiles
  796. ) {
  797. $correct = intval($answerValues['fraction']) ? intval($answerValues['fraction']) : 0;
  798. $answer = $answerValues['answertext'];
  799. $comment = $answerValues['feedback'];
  800. $weighting = $answerValues['fraction'];
  801. $weighting = abs($weighting);
  802. if ($weighting > 0) {
  803. $questionWeighting += $weighting;
  804. }
  805. $goodAnswer = $correct ? true : false;
  806. $this->fixPathInText($importedFiles, $answer);
  807. $objAnswer->createAnswer(
  808. $answer,
  809. $goodAnswer,
  810. $comment,
  811. $weighting,
  812. $position,
  813. null,
  814. null,
  815. ''
  816. );
  817. }
  818. /**
  819. * Process Chamilo FillBlanks
  820. *
  821. * @param object $objAnswer
  822. * @param array $questionType
  823. * @param array $answerValues
  824. * @param string $placeholder
  825. * @param integer $position
  826. * @param array $importedFiles
  827. * @return integer db response
  828. *
  829. */
  830. public function processFillBlanks(
  831. $objAnswer,
  832. $questionType,
  833. $answerValues,
  834. &$placeholder,
  835. $position,
  836. $importedFiles
  837. ) {
  838. $coursePath = api_get_course_path();
  839. switch ($questionType) {
  840. case 'multichoice':
  841. $optionsValues = [];
  842. $correctAnswer = '';
  843. $othersAnswer = '';
  844. foreach ($answerValues as $answer) {
  845. $correct = intval($answer['fraction']);
  846. if ($correct) {
  847. $correctAnswer .= $answer['answertext'].'|';
  848. $optionsValues['weight'] = $answer['fraction'];
  849. $optionsValues['size'] = '200';
  850. } else {
  851. $othersAnswer .= $answer['answertext'].'|';
  852. }
  853. }
  854. $currentAnswers = $correctAnswer.$othersAnswer;
  855. $currentAnswers = '['.substr($currentAnswers, 0, -1).']';
  856. $placeholder = str_replace("{#$position}", $currentAnswers, $placeholder);
  857. return $optionsValues;
  858. break;
  859. case 'shortanswer':
  860. $optionsValues = [];
  861. $correctAnswer = '';
  862. foreach ($answerValues as $answer) {
  863. $correct = intval($answer['fraction']);
  864. if ($correct) {
  865. $correctAnswer .= $answer['answertext'];
  866. $optionsValues['weight'] = $answer['fraction'];
  867. $optionsValues['size'] = '200';
  868. }
  869. }
  870. $currentAnswers = '['.$correctAnswer.']';
  871. $placeholder = str_replace("{#$position}", $currentAnswers, $placeholder);
  872. return $optionsValues;
  873. break;
  874. case 'match':
  875. $answers = [];
  876. // Here first we need to extract all the possible answers
  877. foreach ($answerValues as $slot => $answer) {
  878. $answers[$slot] = $answer['answertext'];
  879. }
  880. // Now we set the order of the values matching the correct answer and set it to the first element
  881. $optionsValues = [];
  882. foreach ($answerValues as $slot => $answer) {
  883. $correctAnswer = '';
  884. $othersAnswers = '';
  885. $correctAnswer .= $answer['answertext'].'|';
  886. foreach ($answers as $other) {
  887. if ($other !== $answer['answertext']) {
  888. $othersAnswers .= $other.'|';
  889. }
  890. }
  891. $optionsValues[$slot]['weight'] = 1;
  892. $optionsValues[$slot]['size'] = '200';
  893. $currentAnswers = htmlentities($correctAnswer.$othersAnswers);
  894. $currentAnswers = '['.substr($currentAnswers, 0, -1).'] ';
  895. $answer['questiontext'] = str_replace(
  896. '@@PLUGINFILE@@',
  897. '/courses/'.$coursePath.'/document/moodle',
  898. $answer['questiontext']
  899. );
  900. $placeholder .= '<p> '.strip_tags($answer['questiontext']).' '.$currentAnswers.' </p>';
  901. }
  902. return $optionsValues;
  903. break;
  904. default:
  905. return false;
  906. break;
  907. }
  908. }
  909. /**
  910. * get All files associated with a question
  911. *
  912. * @param $filesXml
  913. * @return array
  914. */
  915. public function getAllQuestionFiles($filesXml)
  916. {
  917. $moduleDoc = new DOMDocument();
  918. $moduleRes = @$moduleDoc->loadXML($filesXml);
  919. $allFiles = [];
  920. if ($moduleRes) {
  921. $activities = $moduleDoc->getElementsByTagName('file');
  922. foreach ($activities as $activity) {
  923. $currentItem = [];
  924. $thisIsAnInvalidItem = false;
  925. if ($activity->childNodes->length) {
  926. foreach ($activity->childNodes as $item) {
  927. if ($item->nodeName == 'component' && $item->nodeValue == 'mod_resource') {
  928. $thisIsAnInvalidItem = true;
  929. }
  930. if ($item->nodeName == 'contenthash') {
  931. $currentItem['contenthash'] = $item->nodeValue;
  932. }
  933. if ($item->nodeName == 'filename') {
  934. $currentItem['filename'] = $item->nodeValue;
  935. }
  936. if ($item->nodeName == 'filesize') {
  937. $currentItem['filesize'] = $item->nodeValue;
  938. }
  939. if ($item->nodeName == 'mimetype' && $item->nodeValue == 'document/unknown') {
  940. $thisIsAnInvalidItem = true;
  941. }
  942. if ($item->nodeName == 'mimetype' && $item->nodeValue !== 'document/unknown') {
  943. $currentItem['mimetype'] = $item->nodeValue;
  944. }
  945. }
  946. }
  947. if (!$thisIsAnInvalidItem) {
  948. $allFiles[] = $currentItem;
  949. }
  950. }
  951. }
  952. return $allFiles;
  953. }
  954. /**
  955. * Litle utility to delete the unuseful tags
  956. *
  957. * @param $array
  958. * @param $keys
  959. */
  960. public function traverseArray(&$array, $keys)
  961. {
  962. foreach ($array as $key => &$value) {
  963. if (is_array($value)) {
  964. $this->traverseArray($value, $keys);
  965. } else {
  966. if (in_array($key, $keys)) {
  967. unset($array[$key]);
  968. }
  969. }
  970. }
  971. }
  972. }