unique_answer.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Class UniqueAnswer
  6. *
  7. * This class allows to instantiate an object of type UNIQUE_ANSWER
  8. * (MULTIPLE CHOICE, UNIQUE ANSWER),
  9. * extending the class question
  10. *
  11. * @author Eric Marguin
  12. * @author Julio Montoya
  13. * @package chamilo.exercise
  14. **/
  15. class UniqueAnswer extends Question
  16. {
  17. public static $typePicture = 'mcua.png';
  18. public static $explanationLangVar = 'UniqueSelect';
  19. /**
  20. * Constructor
  21. */
  22. public function __construct()
  23. {
  24. parent::__construct();
  25. $this->type = UNIQUE_ANSWER;
  26. $this->isContent = $this->getIsContent();
  27. }
  28. /**
  29. * @inheritdoc
  30. */
  31. public function createAnswersForm($form)
  32. {
  33. // Getting the exercise list
  34. $obj_ex = Session::read('objExercise');
  35. $editor_config = array(
  36. 'ToolbarSet' => 'TestProposedAnswer',
  37. 'Width' => '100%',
  38. 'Height' => '125'
  39. );
  40. //this line defines how many questions by default appear when creating a choice question
  41. // The previous default value was 2. See task #1759.
  42. $nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 4;
  43. $nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
  44. /*
  45. Types of Feedback
  46. $feedback_option[0]=get_lang('Feedback');
  47. $feedback_option[1]=get_lang('DirectFeedback');
  48. $feedback_option[2]=get_lang('NoFeedback');
  49. */
  50. $feedback_title = '';
  51. if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  52. //Scenario
  53. $comment_title = '<th width="20%">'.get_lang('Comment').'</th>';
  54. $feedback_title = '<th width="20%">'.get_lang('Scenario').'</th>';
  55. } else {
  56. $comment_title = '<th width="40%">'.get_lang('Comment').'</th>';
  57. }
  58. $html = '<table class="table table-striped table-hover">
  59. <thead>
  60. <tr style="text-align: center;">
  61. <th width="5%">' . get_lang('Number').'</th>
  62. <th width="5%"> ' . get_lang('True').'</th>
  63. <th width="40%">' . get_lang('Answer').'</th>
  64. ' . $comment_title.'
  65. ' . $feedback_title.'
  66. <th width="10%">' . get_lang('Weighting').'</th>
  67. </tr>
  68. </thead>
  69. <tbody>';
  70. $form->addHeader(get_lang('Answers'));
  71. $form->addHtml($html);
  72. $defaults = array();
  73. $correct = 0;
  74. if (!empty($this->id)) {
  75. $answer = new Answer($this->id);
  76. $answer->read();
  77. if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) {
  78. $nb_answers = $answer->nbrAnswers;
  79. }
  80. }
  81. $form->addElement('hidden', 'nb_answers');
  82. //Feedback SELECT
  83. $question_list = $obj_ex->selectQuestionList();
  84. $select_question = array();
  85. $select_question[0] = get_lang('SelectTargetQuestion');
  86. if (is_array($question_list)) {
  87. foreach ($question_list as $key => $questionid) {
  88. //To avoid warning messages
  89. if (!is_numeric($questionid)) {
  90. continue;
  91. }
  92. $question = Question::read($questionid);
  93. $select_question[$questionid] = 'Q'.$key.' :'.cut(
  94. $question->selectTitle(), 20
  95. );
  96. }
  97. }
  98. $select_question[-1] = get_lang('ExitTest');
  99. $list = new LearnpathList(api_get_user_id());
  100. $flat_list = $list->get_flat_list();
  101. $select_lp_id = array();
  102. $select_lp_id[0] = get_lang('SelectTargetLP');
  103. foreach ($flat_list as $id => $details) {
  104. $select_lp_id[$id] = cut($details['lp_name'], 20);
  105. }
  106. $temp_scenario = array();
  107. if ($nb_answers < 1) {
  108. $nb_answers = 1;
  109. echo Display::return_message(
  110. get_lang('YouHaveToCreateAtLeastOneAnswer')
  111. );
  112. }
  113. for ($i = 1; $i <= $nb_answers; ++$i) {
  114. $form->addHtml('<tr>');
  115. if (isset($answer) && is_object($answer)) {
  116. if ($answer->correct[$i]) {
  117. $correct = $i;
  118. }
  119. $defaults['answer['.$i.']'] = $answer->answer[$i];
  120. $defaults['comment['.$i.']'] = $answer->comment[$i];
  121. $defaults['weighting['.$i.']'] = float_format(
  122. $answer->weighting[$i],
  123. 1
  124. );
  125. $item_list = explode('@@', $answer->destination[$i]);
  126. $try = isset($item_list[0]) ? $item_list[0] : '';
  127. $lp = isset($item_list[1]) ? $item_list[1] : '';
  128. $list_dest = isset($item_list[2]) ? $item_list[2] : '';
  129. $url = isset($item_list[3]) ? $item_list[3] : '';
  130. if ($try == 0) {
  131. $try_result = 0;
  132. } else {
  133. $try_result = 1;
  134. }
  135. if ($url == 0) {
  136. $url_result = '';
  137. } else {
  138. $url_result = $url;
  139. }
  140. $temp_scenario['url'.$i] = $url_result;
  141. $temp_scenario['try'.$i] = $try_result;
  142. $temp_scenario['lp'.$i] = $lp;
  143. $temp_scenario['destination'.$i] = $list_dest;
  144. } else {
  145. $defaults['answer[1]'] = get_lang('DefaultUniqueAnswer1');
  146. $defaults['weighting[1]'] = 10;
  147. $defaults['answer[2]'] = get_lang('DefaultUniqueAnswer2');
  148. $defaults['weighting[2]'] = 0;
  149. $temp_scenario['destination'.$i] = array('0');
  150. $temp_scenario['lp'.$i] = array('0');
  151. }
  152. $defaults['scenario'] = $temp_scenario;
  153. $renderer = $form->defaultRenderer();
  154. $renderer->setElementTemplate(
  155. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  156. 'correct'
  157. );
  158. $renderer->setElementTemplate(
  159. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  160. 'counter['.$i.']'
  161. );
  162. $renderer->setElementTemplate(
  163. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  164. 'answer['.$i.']'
  165. );
  166. $renderer->setElementTemplate(
  167. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  168. 'comment['.$i.']'
  169. );
  170. $renderer->setElementTemplate(
  171. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  172. 'weighting['.$i.']'
  173. );
  174. $answer_number = $form->addElement(
  175. 'text',
  176. 'counter['.$i.']',
  177. null,
  178. ' value = "'.$i.'"'
  179. );
  180. $answer_number->freeze();
  181. $form->addElement(
  182. 'radio',
  183. 'correct',
  184. null,
  185. null,
  186. $i,
  187. 'class="checkbox"'
  188. );
  189. $form->addHtmlEditor('answer['.$i.']', null, null, true, $editor_config);
  190. $form->addRule(
  191. 'answer['.$i.']',
  192. get_lang('ThisFieldIsRequired'),
  193. 'required'
  194. );
  195. if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  196. $form->addHtmlEditor(
  197. 'comment['.$i.']',
  198. null,
  199. null,
  200. false,
  201. $editor_config
  202. );
  203. // Direct feedback
  204. //Adding extra feedback fields
  205. $group = array();
  206. $group['try'.$i] = $form->createElement(
  207. 'checkbox',
  208. 'try'.$i,
  209. null,
  210. get_lang('TryAgain')
  211. );
  212. $group['lp'.$i] = $form->createElement(
  213. 'select',
  214. 'lp'.$i,
  215. get_lang('SeeTheory').': ',
  216. $select_lp_id
  217. );
  218. $group['destination'.$i] = $form->createElement(
  219. 'select',
  220. 'destination'.$i,
  221. get_lang('GoToQuestion').': ',
  222. $select_question
  223. );
  224. $group['url'.$i] = $form->createElement(
  225. 'text',
  226. 'url'.$i,
  227. get_lang('Other').': ',
  228. array(
  229. 'class' => 'col-md-2',
  230. 'placeholder' => get_lang('Other')
  231. )
  232. );
  233. $form->addGroup($group, 'scenario');
  234. $renderer->setElementTemplate(
  235. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}',
  236. 'scenario'
  237. );
  238. } else {
  239. $form->addHtmlEditor('comment['.$i.']', null, null, false, $editor_config);
  240. }
  241. $form->addText('weighting['.$i.']', null, null, array('value' => '0'));
  242. $form->addHtml('</tr>');
  243. }
  244. $form->addHtml('</tbody>');
  245. $form->addHtml('</table>');
  246. global $text;
  247. $buttonGroup = [];
  248. //ie6 fix
  249. if ($obj_ex->edit_exercise_in_lp == true) {
  250. //setting the save button here and not in the question class.php
  251. $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true);
  252. $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true);
  253. $buttonGroup[] = $form->addButton(
  254. 'submitQuestion',
  255. $text,
  256. 'check',
  257. 'primary',
  258. 'default',
  259. null,
  260. ['id' => 'submit-question'],
  261. true
  262. );
  263. $form->addGroup($buttonGroup);
  264. }
  265. // We check the first radio button to be sure a radio button will be check
  266. if ($correct == 0) {
  267. $correct = 1;
  268. }
  269. $defaults['correct'] = $correct;
  270. if (!empty($this->id)) {
  271. $form->setDefaults($defaults);
  272. } else {
  273. if ($this->isContent == 1) {
  274. // Default sample content.
  275. $form->setDefaults($defaults);
  276. } else {
  277. $form->setDefaults(array('correct' => 1));
  278. }
  279. }
  280. $form->setConstants(array('nb_answers' => $nb_answers));
  281. }
  282. /**
  283. * Receives the unique answer question type creation form data and creates
  284. * or updates the answers from that question
  285. * @param FormValidator $form
  286. */
  287. public function processAnswersCreation($form)
  288. {
  289. $questionWeighting = $nbrGoodAnswers = 0;
  290. $correct = $form->getSubmitValue('correct');
  291. $objAnswer = new Answer($this->id);
  292. $nb_answers = $form->getSubmitValue('nb_answers');
  293. for ($i = 1; $i <= $nb_answers; $i++) {
  294. $answer = trim($form->getSubmitValue('answer['.$i.']'));
  295. $comment = trim($form->getSubmitValue('comment['.$i.']'));
  296. $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
  297. $scenario = $form->getSubmitValue('scenario');
  298. //$list_destination = $form -> getSubmitValue('destination'.$i);
  299. //$destination_str = $form -> getSubmitValue('destination'.$i);
  300. $try = $scenario['try'.$i];
  301. $lp = $scenario['lp'.$i];
  302. $destination = $scenario['destination'.$i];
  303. $url = trim($scenario['url'.$i]);
  304. /*
  305. How we are going to parse the destination value
  306. here we parse the destination value which is a string
  307. 1@@3@@2;4;4;@@http://www.chamilo.org
  308. where: try_again@@lp_id@@selected_questions@@url
  309. try_again = is 1 || 0
  310. lp_id = id of a learning path (0 if dont select)
  311. selected_questions= ids of questions
  312. url= an url
  313. $destination_str='';
  314. foreach ($list_destination as $destination_id)
  315. {
  316. $destination_str.=$destination_id.';';
  317. }*/
  318. $goodAnswer = $correct == $i ? true : false;
  319. if ($goodAnswer) {
  320. $nbrGoodAnswers++;
  321. $weighting = abs($weighting);
  322. if ($weighting > 0) {
  323. $questionWeighting += $weighting;
  324. }
  325. }
  326. if (empty($try)) {
  327. $try = 0;
  328. }
  329. if (empty($lp)) {
  330. $lp = 0;
  331. }
  332. if (empty($destination)) {
  333. $destination = 0;
  334. }
  335. if ($url == '') {
  336. $url = 0;
  337. }
  338. //1@@1;2;@@2;4;4;@@http://www.chamilo.org
  339. $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
  340. $objAnswer->createAnswer(
  341. $answer,
  342. $goodAnswer,
  343. $comment,
  344. $weighting,
  345. $i,
  346. null,
  347. null,
  348. $dest
  349. );
  350. }
  351. // saves the answers into the data base
  352. $objAnswer->save();
  353. // sets the total weighting of the question
  354. $this->updateWeighting($questionWeighting);
  355. $this->save();
  356. }
  357. /**
  358. * Helper function to print the column titles in the answers edition form
  359. * @param null $feedback_type The type of feedback influences what columns are shown to the editor
  360. * @param null $counter The number of answers to show, in case there should be pagination
  361. * @param null $score The maximum score for the question
  362. * @return string HTML string for a table header + a wrapper before it
  363. */
  364. public function return_header(
  365. $feedback_type = null,
  366. $counter = null,
  367. $score = null
  368. ) {
  369. $header = parent::return_header($feedback_type, $counter, $score);
  370. $header .= '<table class="'.$this->question_table_class.'">
  371. <tr>
  372. <th>' . get_lang("Choice") . '</th>
  373. <th>' . get_lang("ExpectedChoice") . '</th>
  374. <th>' . get_lang("Answer") . '</th>';
  375. $header .= '<th>' . get_lang("Status") . '</th>';
  376. $header .= '<th>'.get_lang('Comment').'</th>';
  377. $header .= '</tr>';
  378. return $header;
  379. }
  380. /**
  381. * Saves one answer to the database
  382. * @param int $id The ID of the answer (has to be calculated for this course)
  383. * @param int $question_id The question ID (to which the answer is attached)
  384. * @param string $title The text of the answer
  385. * @param string $comment The feedback for the answer
  386. * @param double $score The score you get when picking this answer
  387. * @param integer $correct Whether this answer is considered *the* correct one (this is the unique answer type)
  388. */
  389. public function addAnswer(
  390. $id,
  391. $question_id,
  392. $title,
  393. $comment,
  394. $score = 0.0,
  395. $correct = 0
  396. ) {
  397. $em = Database::getManager();
  398. $tbl_quiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
  399. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  400. $course_id = api_get_course_int_id();
  401. $question_id = intval($question_id);
  402. $score = floatval($score);
  403. $correct = intval($correct);
  404. $title = Database::escape_string($title);
  405. $comment = Database::escape_string($comment);
  406. // Get the max position.
  407. $sql = "SELECT max(position) as max_position
  408. FROM $tbl_quiz_answer
  409. WHERE
  410. c_id = $course_id AND
  411. question_id = $question_id";
  412. $rs_max = Database::query($sql);
  413. $row_max = Database::fetch_object($rs_max);
  414. $position = $row_max->max_position + 1;
  415. // Insert a new answer
  416. $quizAnswer = new \Chamilo\CourseBundle\Entity\CQuizAnswer();
  417. $quizAnswer
  418. ->setCId($course_id)
  419. ->setId($id)
  420. ->setQuestionId($question_id)
  421. ->setAnswer($title)
  422. ->setCorrect($correct)
  423. ->setComment($comment)
  424. ->setPonderation($score)
  425. ->setPosition($position)
  426. ->setDestination('0@@0@@0@@0');
  427. $em->persist($quizAnswer);
  428. $em->flush();
  429. $id = $quizAnswer->getIid();
  430. if ($id) {
  431. $quizAnswer
  432. ->setId($id);
  433. $em->merge($quizAnswer);
  434. $em->flush();
  435. }
  436. if ($correct) {
  437. $sql = "UPDATE $tbl_quiz_question
  438. SET ponderation = (ponderation + $score)
  439. WHERE c_id = $course_id AND id = ".$question_id;
  440. Database::query($sql);
  441. }
  442. }
  443. }