upload_exercise.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. global $debug;
  106. $_course = api_get_course_info();
  107. $courseId = $_course['real_id'];
  108. if (!isset($_POST['submit_upload_quiz'])) {
  109. return;
  110. }
  111. // Get the extension of the document.
  112. $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
  113. // Check if the document is an Excel document
  114. if ($path_info['extension'] != 'xls') {
  115. return;
  116. }
  117. // Variables
  118. $numberQuestions = 0;
  119. $question = [];
  120. $scoreList = [];
  121. $feedbackTrueList = [];
  122. $feedbackFalseList = [];
  123. $questionDescriptionList = [];
  124. $noNegativeScoreList = [];
  125. $questionTypeList = [];
  126. $answerList = [];
  127. $quizTitle = '';
  128. $objPHPExcel = PHPExcel_IOFactory::load($_FILES['user_upload_quiz']['tmp_name']);
  129. $objPHPExcel->setActiveSheetIndex(0);
  130. $worksheet = $objPHPExcel->getActiveSheet();
  131. $highestRow = $worksheet->getHighestRow(); // e.g. 10
  132. $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  133. $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
  134. $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
  135. $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
  136. for ($row = 1; $row <= $highestRow; $row++) {
  137. $cellTitleInfo = $worksheet->getCellByColumnAndRow(0, $row);
  138. $cellDataInfo = $worksheet->getCellByColumnAndRow(1, $row);
  139. $cellScoreInfo = $worksheet->getCellByColumnAndRow(2, $row);
  140. $title = $cellTitleInfo->getValue();
  141. switch ($title) {
  142. case 'Quiz':
  143. $quizTitle = $cellDataInfo->getValue();
  144. break;
  145. case 'Question':
  146. $question[] = $cellDataInfo->getValue();
  147. // Search cell with Answer title
  148. $answerRow = $row;
  149. $continue = true;
  150. $answerIndex = 0;
  151. while ($continue) {
  152. $answerRow++;
  153. $answerInfoTitle = $worksheet->getCellByColumnAndRow(0, $answerRow);
  154. $answerInfoData = $worksheet->getCellByColumnAndRow(1, $answerRow);
  155. $answerInfoExtra = $worksheet->getCellByColumnAndRow(2, $answerRow);
  156. $answerInfoTitle = $answerInfoTitle->getValue();
  157. if (strpos($answerInfoTitle, 'Answer') !== false) {
  158. $answerList[$numberQuestions][$answerIndex]['data'] = $answerInfoData->getValue();
  159. $answerList[$numberQuestions][$answerIndex]['extra'] = $answerInfoExtra->getValue();
  160. } else {
  161. $continue = false;
  162. }
  163. $answerIndex++;
  164. // To avoid loops
  165. if ($answerIndex > 60) {
  166. $continue = false;
  167. }
  168. }
  169. // Search cell with question type
  170. $answerRow = $row;
  171. $continue = true;
  172. $questionTypeIndex = 0;
  173. while ($continue) {
  174. $answerRow++;
  175. $questionTypeTitle = $worksheet->getCellByColumnAndRow(0, $answerRow);
  176. $questionTypeExtra = $worksheet->getCellByColumnAndRow(2, $answerRow);
  177. $title = $questionTypeTitle->getValue();
  178. if ($title == 'QuestionType') {
  179. $questionTypeList[$numberQuestions] = $questionTypeExtra->getValue();
  180. $continue = false;
  181. }
  182. if ($title == 'Question') {
  183. $continue = false;
  184. }
  185. // To avoid loops
  186. if ($questionTypeIndex > 60) {
  187. $continue = false;
  188. }
  189. $questionTypeIndex++;
  190. }
  191. // Detect answers
  192. $numberQuestions++;
  193. break;
  194. case 'Score':
  195. $scoreList[] = $cellScoreInfo->getValue();
  196. break;
  197. case 'NoNegativeScore':
  198. $noNegativeScoreList[] = $cellDataInfo->getValue();
  199. break;
  200. case 'Category':
  201. $categoryList[] = $cellDataInfo->getValue();
  202. break;
  203. case 'FeedbackTrue':
  204. $feedbackTrueList[] = $cellDataInfo->getValue();
  205. break;
  206. case 'FeedbackFalse':
  207. $feedbackFalseList[] = $cellDataInfo->getValue();
  208. break;
  209. case 'EnrichQuestion':
  210. $questionDescriptionList[] = $cellDataInfo->getValue();
  211. break;
  212. }
  213. }
  214. $propagateNegative = 0;
  215. if ($useCustomScore && !empty($incorrectScore)) {
  216. if ($incorrectScore < 0) {
  217. $propagateNegative = 1;
  218. }
  219. }
  220. if ($quizTitle != '') {
  221. // Variables
  222. $type = 2;
  223. $random = $active = $results = $max_attempt = $expired_time = 0;
  224. // Make sure feedback is enabled (3 to disable), otherwise the fields
  225. // added to the XLS are not shown, which is confusing
  226. $feedback = 0;
  227. // Quiz object
  228. $exercise = new Exercise();
  229. $quiz_id = $exercise->createExercise(
  230. $quizTitle,
  231. $expired_time,
  232. $type,
  233. $random,
  234. $active,
  235. $results,
  236. $max_attempt,
  237. $feedback,
  238. $propagateNegative
  239. );
  240. if ($quiz_id) {
  241. // insert into the item_property table
  242. api_item_property_update(
  243. $_course,
  244. TOOL_QUIZ,
  245. $quiz_id,
  246. 'QuizAdded',
  247. api_get_user_id()
  248. );
  249. // Import questions.
  250. for ($i = 0; $i < $numberQuestions; $i++) {
  251. // Question name
  252. $questionTitle = $question[$i];
  253. $myAnswerList = isset($answerList[$i]) ? $answerList[$i] : [];
  254. $description = isset($questionDescriptionList[$i]) ? $questionDescriptionList[$i] : '';
  255. $categoryId = null;
  256. if (isset($categoryList[$i]) && !empty($categoryList[$i])) {
  257. $categoryName = $categoryList[$i];
  258. $categoryId = TestCategory::get_category_id_for_title($categoryName, $courseId);
  259. if (empty($categoryId)) {
  260. $category = new TestCategory();
  261. $category->name = $categoryName;
  262. $categoryId = $category->save();
  263. }
  264. }
  265. $question_description_text = '<p></p>';
  266. if (!empty($description)) {
  267. // Question description.
  268. $question_description_text = "<p>$description</p>";
  269. }
  270. // Unique answers are the only question types available for now
  271. // through xls-format import
  272. $question_id = null;
  273. if (isset($questionTypeList[$i]) && $questionTypeList[$i] != '') {
  274. $detectQuestionType = (int) $questionTypeList[$i];
  275. } else {
  276. $detectQuestionType = detectQuestionType($myAnswerList);
  277. }
  278. /** @var Question $answer */
  279. switch ($detectQuestionType) {
  280. case FREE_ANSWER:
  281. $answer = new FreeAnswer();
  282. break;
  283. case GLOBAL_MULTIPLE_ANSWER:
  284. $answer = new GlobalMultipleAnswer();
  285. break;
  286. case MULTIPLE_ANSWER:
  287. $answer = new MultipleAnswer();
  288. break;
  289. case FILL_IN_BLANKS:
  290. $answer = new FillBlanks();
  291. $question_description_text = '';
  292. break;
  293. case MATCHING:
  294. $answer = new Matching();
  295. break;
  296. case UNIQUE_ANSWER:
  297. default:
  298. $answer = new UniqueAnswer();
  299. break;
  300. }
  301. if ($questionTitle != '') {
  302. $question_id = $answer->create_question(
  303. $quiz_id,
  304. $questionTitle,
  305. $question_description_text,
  306. 0, // max score
  307. $answer->type
  308. );
  309. if (!empty($categoryId)) {
  310. TestCategory::add_category_for_question_id(
  311. $categoryId,
  312. $question_id,
  313. $courseId
  314. );
  315. }
  316. }
  317. switch ($detectQuestionType) {
  318. case GLOBAL_MULTIPLE_ANSWER:
  319. case MULTIPLE_ANSWER:
  320. case UNIQUE_ANSWER:
  321. $total = 0;
  322. if (is_array($myAnswerList) && !empty($myAnswerList) && !empty($question_id)) {
  323. $id = 1;
  324. $objAnswer = new Answer($question_id, $courseId);
  325. $globalScore = $scoreList[$i];
  326. // Calculate the number of correct answers to divide the
  327. // score between them when importing from CSV
  328. $numberRightAnswers = 0;
  329. foreach ($myAnswerList as $answer_data) {
  330. if (strtolower($answer_data['extra']) == 'x') {
  331. $numberRightAnswers++;
  332. }
  333. }
  334. foreach ($myAnswerList as $answer_data) {
  335. $answerValue = $answer_data['data'];
  336. $correct = 0;
  337. $score = 0;
  338. if (strtolower($answer_data['extra']) == 'x') {
  339. $correct = 1;
  340. $score = $scoreList[$i];
  341. $comment = isset($feedbackTrueList[$i]) ? $feedbackTrueList[$i] : '';
  342. } else {
  343. $comment = isset($feedbackFalseList[$i]) ? $feedbackFalseList[$i] : '';
  344. $floatVal = (float)$answer_data['extra'];
  345. if (is_numeric($floatVal)) {
  346. $score = $answer_data['extra'];
  347. }
  348. }
  349. if ($useCustomScore) {
  350. if ($correct) {
  351. $score = $correctScore;
  352. } else {
  353. $score = $incorrectScore;
  354. }
  355. }
  356. // Fixing scores:
  357. switch ($detectQuestionType) {
  358. case GLOBAL_MULTIPLE_ANSWER:
  359. if (isset($noNegativeScoreList[$i][3])) {
  360. if (!(strtolower($noNegativeScoreList[$i]) == 'x') &&
  361. !$correct
  362. ) {
  363. $score = $scoreList[$i] * -1;
  364. }
  365. } else {
  366. $score = $scoreList[$i] * -1;
  367. }
  368. $score /= $numberRightAnswers;
  369. break;
  370. case UNIQUE_ANSWER:
  371. break;
  372. case MULTIPLE_ANSWER:
  373. if (!$correct) {
  374. //$total = $total - $score;
  375. }
  376. break;
  377. }
  378. $objAnswer->createAnswer(
  379. $answerValue,
  380. $correct,
  381. $comment,
  382. $score,
  383. $id
  384. );
  385. $total += $score;
  386. $id++;
  387. }
  388. $objAnswer->save();
  389. $questionObj = Question::read(
  390. $question_id,
  391. $courseId
  392. );
  393. if ($questionObj) {
  394. switch ($detectQuestionType) {
  395. case GLOBAL_MULTIPLE_ANSWER:
  396. $questionObj->updateWeighting($globalScore);
  397. break;
  398. case UNIQUE_ANSWER:
  399. case MULTIPLE_ANSWER:
  400. default:
  401. $questionObj->updateWeighting($total);
  402. break;
  403. }
  404. $questionObj->save();
  405. }
  406. }
  407. break;
  408. case FREE_ANSWER:
  409. $globalScore = $scoreList[$i];
  410. $questionObj = Question::read($question_id, $courseId);
  411. if ($questionObj) {
  412. $questionObj->updateWeighting($globalScore);
  413. $questionObj->save();
  414. }
  415. break;
  416. case FILL_IN_BLANKS:
  417. $scoreList = [];
  418. $size = [];
  419. $globalScore = 0;
  420. foreach ($myAnswerList as $data) {
  421. $score = isset($data['extra']) ? $data['extra'] : 0;
  422. $globalScore += $score;
  423. $scoreList[] = $score;
  424. $size[] = 200;
  425. }
  426. $scoreToString = implode(',', $scoreList);
  427. $sizeToString = implode(',', $size);
  428. //<p>Texte long avec les [mots] à [remplir] mis entre [crochets]</p>::10,10,10:200.36363999999998,200,200:0@'
  429. $answerValue = $description.'::'.$scoreToString.':'.$sizeToString.':0@';
  430. $objAnswer = new Answer($question_id, $courseId);
  431. $objAnswer->createAnswer(
  432. $answerValue,
  433. '', //$correct,
  434. '', //$comment,
  435. $globalScore,
  436. 1
  437. );
  438. $objAnswer->save();
  439. $questionObj = Question::read($question_id, $courseId);
  440. if ($questionObj) {
  441. $questionObj->updateWeighting($globalScore);
  442. $questionObj->save();
  443. }
  444. break;
  445. case MATCHING:
  446. $globalScore = $scoreList[$i];
  447. $position = 1;
  448. $objAnswer = new Answer($question_id, $courseId);
  449. foreach ($myAnswerList as $data) {
  450. $option = isset($data['extra']) ? $data['extra'] : '';
  451. $objAnswer->createAnswer($option, 0, '', 0, $position);
  452. $position++;
  453. }
  454. $counter = 1;
  455. foreach ($myAnswerList as $data) {
  456. $value = isset($data['data']) ? $data['data'] : '';
  457. $position++;
  458. $objAnswer->createAnswer(
  459. $value,
  460. $counter,
  461. ' ',
  462. $globalScore,
  463. $position
  464. );
  465. $counter++;
  466. }
  467. $objAnswer->save();
  468. $questionObj = Question::read($question_id, $courseId);
  469. if ($questionObj) {
  470. $questionObj->updateWeighting($globalScore);
  471. $questionObj->save();
  472. }
  473. break;
  474. }
  475. }
  476. }
  477. if (isset($_SESSION['lpobject'])) {
  478. if ($debug > 0) {
  479. error_log('New LP - SESSION[lpobject] is defined', 0);
  480. }
  481. $oLP = unserialize($_SESSION['lpobject']);
  482. if (is_object($oLP)) {
  483. if ($debug > 0) {
  484. error_log('New LP - oLP is object', 0);
  485. }
  486. if ((empty($oLP->cc)) || $oLP->cc != api_get_course_id()) {
  487. if ($debug > 0) {
  488. error_log('New LP - Course has changed, discard lp object', 0);
  489. }
  490. $oLP = null;
  491. Session::erase('oLP');
  492. Session::erase('lpobject');
  493. } else {
  494. $_SESSION['oLP'] = $oLP;
  495. }
  496. }
  497. }
  498. if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
  499. $previous = $_SESSION['oLP']->select_previous_item_id();
  500. $parent = 0;
  501. // Add a Quiz as Lp Item
  502. $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quizTitle, '');
  503. // Redirect to home page for add more content
  504. header('location: ../lp/lp_controller.php?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.intval($_GET['lp_id']));
  505. exit;
  506. } else {
  507. // header('location: exercise.php?' . api_get_cidreq());
  508. 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>';
  509. }
  510. }
  511. }
  512. /**
  513. * @param array $answers_data
  514. * @return int
  515. */
  516. function detectQuestionType($answers_data)
  517. {
  518. $correct = 0;
  519. $isNumeric = false;
  520. if (empty($answers_data)) {
  521. return FREE_ANSWER;
  522. }
  523. foreach ($answers_data as $answer_data) {
  524. if (strtolower($answer_data['extra']) == 'x') {
  525. $correct++;
  526. } else {
  527. if (is_numeric($answer_data['extra'])) {
  528. $isNumeric = true;
  529. }
  530. }
  531. }
  532. if ($correct == 1) {
  533. $type = UNIQUE_ANSWER;
  534. } else {
  535. if ($correct > 1) {
  536. $type = MULTIPLE_ANSWER;
  537. } else {
  538. $type = FREE_ANSWER;
  539. }
  540. }
  541. if ($type == MULTIPLE_ANSWER) {
  542. if ($isNumeric) {
  543. $type = MULTIPLE_ANSWER;
  544. } else {
  545. $type = GLOBAL_MULTIPLE_ANSWER;
  546. }
  547. }
  548. return $type;
  549. }
  550. if ($origin != 'learnpath') {
  551. //so we are not in learnpath tool
  552. Display :: display_footer();
  553. }