unique_answer.class.php 17 KB

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