unique_answer.class.php 17 KB

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