unique_answer.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. $questionTitle = strip_tags($question->selectTitle());
  96. $select_question[$questionid] = "Q$key: $questionTitle";
  97. }
  98. }
  99. $select_question[-1] = get_lang('ExitTest');
  100. $list = new LearnpathList(api_get_user_id());
  101. $flat_list = $list->get_flat_list();
  102. $select_lp_id = [];
  103. $select_lp_id[0] = get_lang('SelectTargetLP');
  104. foreach ($flat_list as $id => $details) {
  105. $select_lp_id[$id] = cut($details['lp_name'], 20);
  106. }
  107. $temp_scenario = [];
  108. if ($nb_answers < 1) {
  109. $nb_answers = 1;
  110. echo Display::return_message(
  111. get_lang('YouHaveToCreateAtLeastOneAnswer')
  112. );
  113. }
  114. for ($i = 1; $i <= $nb_answers; $i++) {
  115. $form->addHtml('<tr>');
  116. if (isset($answer) && is_object($answer)) {
  117. if (isset($answer->correct[$i]) && $answer->correct[$i]) {
  118. $correct = $i;
  119. }
  120. $defaults['answer['.$i.']'] = isset($answer->answer[$i]) ? $answer->answer[$i] : '';
  121. $defaults['comment['.$i.']'] = isset($answer->comment[$i]) ? $answer->comment[$i] : '';
  122. $defaults['weighting['.$i.']'] = isset($answer->weighting[$i]) ? float_format($answer->weighting[$i], 1) : 0;
  123. $item_list = [];
  124. if (isset($answer->destination[$i])) {
  125. $item_list = explode('@@', $answer->destination[$i]);
  126. }
  127. $try = isset($item_list[0]) ? $item_list[0] : '';
  128. $lp = isset($item_list[1]) ? $item_list[1] : '';
  129. $list_dest = isset($item_list[2]) ? $item_list[2] : '';
  130. $url = isset($item_list[3]) ? $item_list[3] : '';
  131. if ($try == 0) {
  132. $try_result = 0;
  133. } else {
  134. $try_result = 1;
  135. }
  136. if ($url == 0) {
  137. $url_result = '';
  138. } else {
  139. $url_result = $url;
  140. }
  141. $temp_scenario['url'.$i] = $url_result;
  142. $temp_scenario['try'.$i] = $try_result;
  143. $temp_scenario['lp'.$i] = $lp;
  144. $temp_scenario['destination'.$i] = $list_dest;
  145. } else {
  146. $defaults['answer[1]'] = get_lang('DefaultUniqueAnswer1');
  147. $defaults['weighting[1]'] = 10;
  148. $defaults['answer[2]'] = get_lang('DefaultUniqueAnswer2');
  149. $defaults['weighting[2]'] = 0;
  150. $temp_scenario['destination'.$i] = ['0'];
  151. $temp_scenario['lp'.$i] = ['0'];
  152. }
  153. $defaults['scenario'] = $temp_scenario;
  154. $renderer = $form->defaultRenderer();
  155. $renderer->setElementTemplate(
  156. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  157. 'correct'
  158. );
  159. $renderer->setElementTemplate(
  160. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  161. 'counter['.$i.']'
  162. );
  163. $renderer->setElementTemplate(
  164. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  165. 'answer['.$i.']'
  166. );
  167. $renderer->setElementTemplate(
  168. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  169. 'comment['.$i.']'
  170. );
  171. $renderer->setElementTemplate(
  172. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  173. 'weighting['.$i.']'
  174. );
  175. $answer_number = $form->addElement(
  176. 'text',
  177. 'counter['.$i.']',
  178. null,
  179. ' value = "'.$i.'"'
  180. );
  181. $answer_number->freeze();
  182. $form->addElement(
  183. 'radio',
  184. 'correct',
  185. null,
  186. null,
  187. $i,
  188. 'class="checkbox"'
  189. );
  190. $form->addHtmlEditor('answer['.$i.']', null, null, false, $editor_config);
  191. $form->addRule(
  192. 'answer['.$i.']',
  193. get_lang('ThisFieldIsRequired'),
  194. 'required'
  195. );
  196. if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  197. $form->addHtmlEditor(
  198. 'comment['.$i.']',
  199. null,
  200. null,
  201. false,
  202. $editor_config
  203. );
  204. // Direct feedback
  205. //Adding extra feedback fields
  206. $group = [];
  207. $group['try'.$i] = $form->createElement(
  208. 'checkbox',
  209. 'try'.$i,
  210. null,
  211. get_lang('TryAgain')
  212. );
  213. $group['lp'.$i] = $form->createElement(
  214. 'select',
  215. 'lp'.$i,
  216. get_lang('SeeTheory').': ',
  217. $select_lp_id
  218. );
  219. $group['destination'.$i] = $form->createElement(
  220. 'select',
  221. 'destination'.$i,
  222. get_lang('GoToQuestion').': ',
  223. $select_question
  224. );
  225. $group['url'.$i] = $form->createElement(
  226. 'text',
  227. 'url'.$i,
  228. get_lang('Other').': ',
  229. [
  230. 'class' => 'col-md-2',
  231. 'placeholder' => get_lang('Other'),
  232. ]
  233. );
  234. $form->addGroup($group, 'scenario');
  235. $renderer->setElementTemplate(
  236. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}',
  237. 'scenario'
  238. );
  239. } else {
  240. $form->addHtmlEditor('comment['.$i.']', null, null, false, $editor_config);
  241. }
  242. $form->addText('weighting['.$i.']', null, null, ['value' => '0']);
  243. $form->addHtml('</tr>');
  244. }
  245. $form->addHtml('</tbody>');
  246. $form->addHtml('</table>');
  247. global $text;
  248. $buttonGroup = [];
  249. if ($obj_ex->edit_exercise_in_lp == true ||
  250. (empty($this->exerciseList) && empty($obj_ex->id))
  251. ) {
  252. //setting the save button here and not in the question class.php
  253. $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true);
  254. $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true);
  255. $buttonGroup[] = $form->addButton(
  256. 'submitQuestion',
  257. $text,
  258. 'check',
  259. 'primary',
  260. 'default',
  261. null,
  262. ['id' => 'submit-question'],
  263. true
  264. );
  265. $form->addGroup($buttonGroup);
  266. }
  267. // We check the first radio button to be sure a radio button will be check
  268. if ($correct == 0) {
  269. $correct = 1;
  270. }
  271. $defaults['correct'] = $correct;
  272. if (!empty($this->id)) {
  273. $form->setDefaults($defaults);
  274. } else {
  275. if ($this->isContent == 1) {
  276. // Default sample content.
  277. $form->setDefaults($defaults);
  278. } else {
  279. $form->setDefaults(['correct' => 1]);
  280. }
  281. }
  282. $form->setConstants(['nb_answers' => $nb_answers]);
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function processAnswersCreation($form, $exercise)
  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 = !empty($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($exercise);
  356. }
  357. /**
  358. * {@inheritdoc}
  359. */
  360. public function return_header(
  361. $exercise,
  362. $counter = null,
  363. $score = null
  364. ) {
  365. $header = parent::return_header($exercise, $counter, $score);
  366. $header .= '<table class="'.$this->question_table_class.'"><tr>';
  367. if ($exercise->results_disabled != RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER) {
  368. $header .= '<th>'.get_lang('Choice').'</th>';
  369. $header .= '<th>'.get_lang('ExpectedChoice').'</th>';
  370. }
  371. $header .= '<th>'.get_lang('Answer').'</th>';
  372. if ($exercise->showExpectedChoice()) {
  373. $header .= '<th>'.get_lang('Status').'</th>';
  374. }
  375. $header .= '<th>'.get_lang('Comment').'</th>';
  376. $header .= '</tr>';
  377. return $header;
  378. }
  379. /**
  380. * Saves one answer to the database.
  381. *
  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 float $score The score you get when picking this answer
  387. * @param int $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 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. }