unique_answer.class.php 17 KB

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