unique_answer.class.php 17 KB

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