upload_exercise.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Upload quiz: This script shows the upload quiz feature
  6. * @package chamilo.exercise
  7. */
  8. // setting the help
  9. $help_content = 'exercise_upload';
  10. require_once __DIR__.'/../inc/global.inc.php';
  11. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  12. $origin = api_get_origin();
  13. if (!$is_allowed_to_edit) {
  14. api_not_allowed(true);
  15. }
  16. $this_section = SECTION_COURSES;
  17. $htmlHeadXtra[] = "<script>
  18. $(document).ready( function(){
  19. $('#user_custom_score').click(function() {
  20. $('#options').toggle();
  21. });
  22. });
  23. </script>";
  24. // Action handling
  25. lp_upload_quiz_action_handling();
  26. $interbreadcrumb[] = array(
  27. "url" => "exercise.php?".api_get_cidreq(),
  28. "name" => get_lang('Exercises')
  29. );
  30. // Display the header
  31. Display :: display_header(get_lang('ImportExcelQuiz'), 'Exercises');
  32. // display the actions
  33. echo '<div class="actions">';
  34. echo lp_upload_quiz_actions();
  35. echo '</div>';
  36. // the main content
  37. lp_upload_quiz_main();
  38. function lp_upload_quiz_actions()
  39. {
  40. $return = '<a href="exercise.php?'.api_get_cidreq().'">'.
  41. Display::return_icon(
  42. 'back.png',
  43. get_lang('BackToExercisesList'),
  44. '',
  45. ICON_SIZE_MEDIUM
  46. ).'</a>';
  47. return $return;
  48. }
  49. function lp_upload_quiz_main()
  50. {
  51. $lp_id = isset($_GET['lp_id']) ? intval($_GET['lp_id']) : null;
  52. $form = new FormValidator(
  53. 'upload',
  54. 'POST',
  55. api_get_self().'?'.api_get_cidreq().'&lp_id='.$lp_id,
  56. '',
  57. array('enctype' => 'multipart/form-data')
  58. );
  59. $form->addElement('header', get_lang('ImportExcelQuiz'));
  60. $form->addElement('file', 'user_upload_quiz', get_lang('FileUpload'));
  61. $link = '<a href="../exercise/quiz_template.xls">'.
  62. Display::return_icon('export_excel.png', get_lang('DownloadExcelTemplate')).get_lang('DownloadExcelTemplate').'</a>';
  63. $form->addElement('label', '', $link);
  64. $table = new HTML_Table(array('class' => 'table'));
  65. $tableList = array(
  66. UNIQUE_ANSWER => get_lang('UniqueSelect'),
  67. MULTIPLE_ANSWER => get_lang('MultipleSelect'),
  68. FILL_IN_BLANKS => get_lang('FillBlanks'),
  69. MATCHING => get_lang('Matching'),
  70. FREE_ANSWER => get_lang('FreeAnswer'),
  71. GLOBAL_MULTIPLE_ANSWER => get_lang('GlobalMultipleAnswer')
  72. );
  73. $table->setHeaderContents(0, 0, get_lang('QuestionType'));
  74. $table->setHeaderContents(0, 1, '#');
  75. $row = 1;
  76. foreach ($tableList as $key => $label) {
  77. $table->setCellContents($row, 0, $label);
  78. $table->setCellContents($row, 1, $key);
  79. $row++;
  80. }
  81. $table = $table->toHtml();
  82. $form->addElement('label', get_lang('QuestionType'), $table);
  83. $form->addElement(
  84. 'checkbox',
  85. 'user_custom_score',
  86. null,
  87. get_lang('UseCustomScoreForAllQuestions'),
  88. array('id' => 'user_custom_score')
  89. );
  90. $form->addElement('html', '<div id="options" style="display:none">');
  91. $form->addElement('text', 'correct_score', get_lang('CorrectScore'));
  92. $form->addElement('text', 'incorrect_score', get_lang('IncorrectScore'));
  93. $form->addElement('html', '</div>');
  94. $form->addRule('user_upload_quiz', get_lang('ThisFieldIsRequired'), 'required');
  95. $form->addProgress();
  96. $form->addButtonUpload(get_lang('Upload'), 'submit_upload_quiz');
  97. // Display the upload field
  98. $form->display();
  99. }
  100. /**
  101. * Handles a given Excel spreadsheets as in the template provided
  102. */
  103. function lp_upload_quiz_action_handling()
  104. {
  105. $_course = api_get_course_info();
  106. $courseId = $_course['real_id'];
  107. if (!isset($_POST['submit_upload_quiz'])) {
  108. return;
  109. }
  110. // Get the extension of the document.
  111. $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
  112. // Check if the document is an Excel document
  113. if ($path_info['extension'] != 'xls') {
  114. return;
  115. }
  116. // Variables
  117. $numberQuestions = 0;
  118. $question = [];
  119. $scoreList = [];
  120. $feedbackTrueList = [];
  121. $feedbackFalseList = [];
  122. $questionDescriptionList = [];
  123. $noNegativeScoreList = [];
  124. $questionTypeList = [];
  125. $answerList = [];
  126. $quizTitle = '';
  127. $objPHPExcel = PHPExcel_IOFactory::load($_FILES['user_upload_quiz']['tmp_name']);
  128. $objPHPExcel->setActiveSheetIndex(0);
  129. $worksheet = $objPHPExcel->getActiveSheet();
  130. $highestRow = $worksheet->getHighestRow(); // e.g. 10
  131. $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  132. $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
  133. $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
  134. $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
  135. for ($row = 1; $row <= $highestRow; $row++) {
  136. $cellTitleInfo = $worksheet->getCellByColumnAndRow(0, $row);
  137. $cellDataInfo = $worksheet->getCellByColumnAndRow(1, $row);
  138. $cellScoreInfo = $worksheet->getCellByColumnAndRow(2, $row);
  139. $title = $cellTitleInfo->getValue();
  140. switch ($title) {
  141. case 'Quiz':
  142. $quizTitle = $cellDataInfo->getValue();
  143. break;
  144. case 'Question':
  145. $question[] = $cellDataInfo->getValue();
  146. // Search cell with Answer title
  147. $answerRow = $row;
  148. $continue = true;
  149. $answerIndex = 0;
  150. while ($continue) {
  151. $answerRow++;
  152. $answerInfoTitle = $worksheet->getCellByColumnAndRow(0, $answerRow);
  153. $answerInfoData = $worksheet->getCellByColumnAndRow(1, $answerRow);
  154. $answerInfoExtra = $worksheet->getCellByColumnAndRow(2, $answerRow);
  155. $answerInfoTitle = $answerInfoTitle->getValue();
  156. if (strpos($answerInfoTitle, 'Answer') !== false) {
  157. $answerList[$numberQuestions][$answerIndex]['data'] = $answerInfoData->getValue();
  158. $answerList[$numberQuestions][$answerIndex]['extra'] = $answerInfoExtra->getValue();
  159. } else {
  160. $continue = false;
  161. }
  162. $answerIndex++;
  163. // To avoid loops
  164. if ($answerIndex > 60) {
  165. $continue = false;
  166. }
  167. }
  168. // Search cell with question type
  169. $answerRow = $row;
  170. $continue = true;
  171. $questionTypeIndex = 0;
  172. while ($continue) {
  173. $answerRow++;
  174. $questionTypeTitle = $worksheet->getCellByColumnAndRow(0, $answerRow);
  175. $questionTypeExtra = $worksheet->getCellByColumnAndRow(2, $answerRow);
  176. $title = $questionTypeTitle->getValue();
  177. if ($title == 'QuestionType') {
  178. $questionTypeList[$numberQuestions] = $questionTypeExtra->getValue();
  179. $continue = false;
  180. }
  181. if ($title == 'Question') {
  182. $continue = false;
  183. }
  184. // To avoid loops
  185. if ($questionTypeIndex > 60) {
  186. $continue = false;
  187. }
  188. $questionTypeIndex++;
  189. }
  190. // Detect answers
  191. $numberQuestions++;
  192. break;
  193. case 'Score':
  194. $scoreList[] = $cellScoreInfo->getValue();
  195. break;
  196. case 'NoNegativeScore':
  197. $noNegativeScoreList[] = $cellDataInfo->getValue();
  198. break;
  199. case 'Category':
  200. $categoryList[] = $cellDataInfo->getValue();
  201. break;
  202. case 'FeedbackTrue':
  203. $feedbackTrueList[] = $cellDataInfo->getValue();
  204. break;
  205. case 'FeedbackFalse':
  206. $feedbackFalseList[] = $cellDataInfo->getValue();
  207. break;
  208. case 'EnrichQuestion':
  209. $questionDescriptionList[] = $cellDataInfo->getValue();
  210. break;
  211. }
  212. }
  213. $propagateNegative = 0;
  214. if ($useCustomScore && !empty($incorrectScore)) {
  215. if ($incorrectScore < 0) {
  216. $propagateNegative = 1;
  217. }
  218. }
  219. if ($quizTitle != '') {
  220. // Variables
  221. $type = 2;
  222. $random = $active = $results = $max_attempt = $expired_time = 0;
  223. // Make sure feedback is enabled (3 to disable), otherwise the fields
  224. // added to the XLS are not shown, which is confusing
  225. $feedback = 0;
  226. // Quiz object
  227. $exercise = new Exercise();
  228. $quiz_id = $exercise->createExercise(
  229. $quizTitle,
  230. $expired_time,
  231. $type,
  232. $random,
  233. $active,
  234. $results,
  235. $max_attempt,
  236. $feedback,
  237. $propagateNegative
  238. );
  239. if ($quiz_id) {
  240. // insert into the item_property table
  241. api_item_property_update(
  242. $_course,
  243. TOOL_QUIZ,
  244. $quiz_id,
  245. 'QuizAdded',
  246. api_get_user_id()
  247. );
  248. // Import questions.
  249. for ($i = 0; $i < $numberQuestions; $i++) {
  250. // Question name
  251. $questionTitle = $question[$i];
  252. $myAnswerList = isset($answerList[$i]) ? $answerList[$i] : [];
  253. $description = isset($questionDescriptionList[$i]) ? $questionDescriptionList[$i] : '';
  254. $categoryId = null;
  255. if (isset($categoryList[$i]) && !empty($categoryList[$i])) {
  256. $categoryName = $categoryList[$i];
  257. $categoryId = TestCategory::get_category_id_for_title($categoryName, $courseId);
  258. if (empty($categoryId)) {
  259. $category = new TestCategory();
  260. $category->name = $categoryName;
  261. $categoryId = $category->save();
  262. }
  263. }
  264. $question_description_text = '<p></p>';
  265. if (!empty($description)) {
  266. // Question description.
  267. $question_description_text = "<p>$description</p>";
  268. }
  269. // Unique answers are the only question types available for now
  270. // through xls-format import
  271. $question_id = null;
  272. if (isset($questionTypeList[$i]) && $questionTypeList[$i] != '') {
  273. $detectQuestionType = (int) $questionTypeList[$i];
  274. } else {
  275. $detectQuestionType = detectQuestionType($myAnswerList);
  276. }
  277. /** @var Question $answer */
  278. switch ($detectQuestionType) {
  279. case FREE_ANSWER:
  280. $answer = new FreeAnswer();
  281. break;
  282. case GLOBAL_MULTIPLE_ANSWER:
  283. $answer = new GlobalMultipleAnswer();
  284. break;
  285. case MULTIPLE_ANSWER:
  286. $answer = new MultipleAnswer();
  287. break;
  288. case FILL_IN_BLANKS:
  289. $answer = new FillBlanks();
  290. $question_description_text = '';
  291. break;
  292. case MATCHING:
  293. $answer = new Matching();
  294. break;
  295. case UNIQUE_ANSWER:
  296. default:
  297. $answer = new UniqueAnswer();
  298. break;
  299. }
  300. if ($questionTitle != '') {
  301. $question_id = $answer->create_question(
  302. $quiz_id,
  303. $questionTitle,
  304. $question_description_text,
  305. 0, // max score
  306. $answer->type
  307. );
  308. if (!empty($categoryId)) {
  309. TestCategory::addCategoryToQuestion(
  310. $categoryId,
  311. $question_id,
  312. $courseId
  313. );
  314. }
  315. }
  316. switch ($detectQuestionType) {
  317. case GLOBAL_MULTIPLE_ANSWER:
  318. case MULTIPLE_ANSWER:
  319. case UNIQUE_ANSWER:
  320. $total = 0;
  321. if (is_array($myAnswerList) && !empty($myAnswerList) && !empty($question_id)) {
  322. $id = 1;
  323. $objAnswer = new Answer($question_id, $courseId);
  324. $globalScore = isset($scoreList[$i]) ? $scoreList[$i] : null;
  325. // Calculate the number of correct answers to divide the
  326. // score between them when importing from CSV
  327. $numberRightAnswers = 0;
  328. foreach ($myAnswerList as $answer_data) {
  329. if (strtolower($answer_data['extra']) == 'x') {
  330. $numberRightAnswers++;
  331. }
  332. }
  333. foreach ($myAnswerList as $answer_data) {
  334. $answerValue = $answer_data['data'];
  335. $correct = 0;
  336. $score = 0;
  337. if (strtolower($answer_data['extra']) == 'x') {
  338. $correct = 1;
  339. $score = isset($scoreList[$i]) ? $scoreList[$i] : null;
  340. $comment = isset($feedbackTrueList[$i]) ? $feedbackTrueList[$i] : '';
  341. } else {
  342. $comment = isset($feedbackFalseList[$i]) ? $feedbackFalseList[$i] : '';
  343. $floatVal = (float) $answer_data['extra'];
  344. if (is_numeric($floatVal)) {
  345. $score = $answer_data['extra'];
  346. }
  347. }
  348. if ($useCustomScore) {
  349. if ($correct) {
  350. $score = $correctScore;
  351. } else {
  352. $score = $incorrectScore;
  353. }
  354. }
  355. // Fixing scores:
  356. switch ($detectQuestionType) {
  357. case GLOBAL_MULTIPLE_ANSWER:
  358. if (!$correct) {
  359. if (isset($noNegativeScoreList[$i])) {
  360. if (strtolower($noNegativeScoreList[$i]) == 'x') {
  361. $score = 0;
  362. } else {
  363. $score = $scoreList[$i] * -1;
  364. }
  365. }
  366. } else {
  367. $score = $scoreList[$i];
  368. }
  369. $score /= $numberRightAnswers;
  370. break;
  371. case UNIQUE_ANSWER:
  372. break;
  373. case MULTIPLE_ANSWER:
  374. if (!$correct) {
  375. //$total = $total - $score;
  376. }
  377. break;
  378. }
  379. $objAnswer->createAnswer(
  380. $answerValue,
  381. $correct,
  382. $comment,
  383. $score,
  384. $id
  385. );
  386. $total += $score;
  387. $id++;
  388. }
  389. $objAnswer->save();
  390. $questionObj = Question::read(
  391. $question_id,
  392. $courseId
  393. );
  394. if ($questionObj) {
  395. switch ($detectQuestionType) {
  396. case GLOBAL_MULTIPLE_ANSWER:
  397. $questionObj->updateWeighting($globalScore);
  398. break;
  399. case UNIQUE_ANSWER:
  400. case MULTIPLE_ANSWER:
  401. default:
  402. $questionObj->updateWeighting($total);
  403. break;
  404. }
  405. $questionObj->save();
  406. }
  407. }
  408. break;
  409. case FREE_ANSWER:
  410. $globalScore = isset($scoreList[$i]) ? $scoreList[$i] : null;
  411. $questionObj = Question::read($question_id, $courseId);
  412. if ($questionObj) {
  413. $questionObj->updateWeighting($globalScore);
  414. $questionObj->save();
  415. }
  416. break;
  417. case FILL_IN_BLANKS:
  418. $fillInScoreList = [];
  419. $size = [];
  420. $globalScore = 0;
  421. foreach ($myAnswerList as $data) {
  422. $score = isset($data['extra']) ? $data['extra'] : 0;
  423. $globalScore += $score;
  424. $fillInScoreList[] = $score;
  425. $size[] = 200;
  426. }
  427. $scoreToString = implode(',', $fillInScoreList);
  428. $sizeToString = implode(',', $size);
  429. //<p>Texte long avec les [mots] à [remplir] mis entre [crochets]</p>::10,10,10:200.36363999999998,200,200:0@'
  430. $answerValue = $description.'::'.$scoreToString.':'.$sizeToString.':0@';
  431. $objAnswer = new Answer($question_id, $courseId);
  432. $objAnswer->createAnswer(
  433. $answerValue,
  434. '', //$correct,
  435. '', //$comment,
  436. $globalScore,
  437. 1
  438. );
  439. $objAnswer->save();
  440. $questionObj = Question::read($question_id, $courseId);
  441. if ($questionObj) {
  442. $questionObj->updateWeighting($globalScore);
  443. $questionObj->save();
  444. }
  445. break;
  446. case MATCHING:
  447. $globalScore = isset($scoreList[$i]) ? $scoreList[$i] : null;
  448. $position = 1;
  449. $objAnswer = new Answer($question_id, $courseId);
  450. foreach ($myAnswerList as $data) {
  451. $option = isset($data['extra']) ? $data['extra'] : '';
  452. $objAnswer->createAnswer($option, 0, '', 0, $position);
  453. $position++;
  454. }
  455. $counter = 1;
  456. foreach ($myAnswerList as $data) {
  457. $value = isset($data['data']) ? $data['data'] : '';
  458. $position++;
  459. $objAnswer->createAnswer(
  460. $value,
  461. $counter,
  462. ' ',
  463. $globalScore,
  464. $position
  465. );
  466. $counter++;
  467. }
  468. $objAnswer->save();
  469. $questionObj = Question::read($question_id, $courseId);
  470. if ($questionObj) {
  471. $questionObj->updateWeighting($globalScore);
  472. $questionObj->save();
  473. }
  474. break;
  475. }
  476. }
  477. }
  478. if (isset($_SESSION['lpobject'])) {
  479. if ($debug > 0) {
  480. error_log('New LP - SESSION[lpobject] is defined', 0);
  481. }
  482. $oLP = unserialize($_SESSION['lpobject']);
  483. if (is_object($oLP)) {
  484. if ($debug > 0) {
  485. error_log('New LP - oLP is object', 0);
  486. }
  487. if ((empty($oLP->cc)) || $oLP->cc != api_get_course_id()) {
  488. if ($debug > 0) {
  489. error_log('New LP - Course has changed, discard lp object', 0);
  490. }
  491. $oLP = null;
  492. Session::erase('oLP');
  493. Session::erase('lpobject');
  494. } else {
  495. $_SESSION['oLP'] = $oLP;
  496. }
  497. }
  498. }
  499. if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
  500. $previous = $_SESSION['oLP']->select_previous_item_id();
  501. $parent = 0;
  502. // Add a Quiz as Lp Item
  503. $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quizTitle, '');
  504. // Redirect to home page for add more content
  505. header('location: ../lp/lp_controller.php?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.intval($_GET['lp_id']));
  506. exit;
  507. } else {
  508. // header('location: exercise.php?' . api_get_cidreq());
  509. echo '<script>window.location.href = "'.api_get_path(WEB_CODE_PATH).'exercise/admin.php?'.api_get_cidreq().'&exerciseId='.$quiz_id.'&session_id='.api_get_session_id().'"</script>';
  510. }
  511. }
  512. }
  513. /**
  514. * @param array $answers_data
  515. * @return int
  516. */
  517. function detectQuestionType($answers_data)
  518. {
  519. $correct = 0;
  520. $isNumeric = false;
  521. if (empty($answers_data)) {
  522. return FREE_ANSWER;
  523. }
  524. foreach ($answers_data as $answer_data) {
  525. if (strtolower($answer_data['extra']) == 'x') {
  526. $correct++;
  527. } else {
  528. if (is_numeric($answer_data['extra'])) {
  529. $isNumeric = true;
  530. }
  531. }
  532. }
  533. if ($correct == 1) {
  534. $type = UNIQUE_ANSWER;
  535. } else {
  536. if ($correct > 1) {
  537. $type = MULTIPLE_ANSWER;
  538. } else {
  539. $type = FREE_ANSWER;
  540. }
  541. }
  542. if ($type == MULTIPLE_ANSWER) {
  543. if ($isNumeric) {
  544. $type = MULTIPLE_ANSWER;
  545. } else {
  546. $type = GLOBAL_MULTIPLE_ANSWER;
  547. }
  548. }
  549. return $type;
  550. }
  551. if ($origin != 'learnpath') {
  552. //so we are not in learnpath tool
  553. Display :: display_footer();
  554. }