MoodleImport.php 41 KB

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