unique_answer.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * File containing the UNIQUE_ANSWER class.
  5. * @package chamilo.exercise
  6. * @author Eric Marguin
  7. */
  8. /**
  9. * Code
  10. */
  11. /**
  12. CLASS UNIQUE_ANSWER
  13. *
  14. * This class allows to instantiate an object of type UNIQUE_ANSWER (MULTIPLE CHOICE, UNIQUE ANSWER),
  15. * extending the class question
  16. *
  17. * @author Eric Marguin
  18. * @author Julio Montoya
  19. * @package chamilo.exercise
  20. **/
  21. class UniqueAnswer extends Question
  22. {
  23. static $typePicture = 'mcua.gif';
  24. static $explanationLangVar = 'UniqueSelect';
  25. /**
  26. * Constructor
  27. */
  28. public function UniqueAnswer($course_code = null)
  29. {
  30. //this is highly important
  31. parent::question($course_code);
  32. $this->type = UNIQUE_ANSWER;
  33. $this->isContent = $this->getIsContent();
  34. }
  35. /**
  36. * function which redifines Question::createAnswersForm
  37. * @param FormValidator instance
  38. */
  39. public function createAnswersForm($form)
  40. {
  41. // Getting the exercise list
  42. /** @var Exercise $obj_ex */
  43. $obj_ex = $this->exercise;
  44. $editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125');
  45. //this line define how many question by default appear when creating a choice question
  46. // The previous default value was 2. See task #1759.
  47. $nb_answers = isset($_POST['nb_answers']) ? (int)$_POST['nb_answers'] : 4;
  48. $nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
  49. $feedback_title = '';
  50. $comment_title = '';
  51. if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
  52. $comment_title = '<th>'.get_lang('Comment').'</th>';
  53. } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  54. //Scenario
  55. $editor_config['Width'] = '250';
  56. $editor_config['Height'] = '110';
  57. $comment_title = '<th width="500px" >'.get_lang('Comment').'</th>';
  58. $feedback_title = '<th width="350px" >'.get_lang('Scenario').'</th>';
  59. }
  60. $html = '<table class="data_table">
  61. <tr style="text-align: center;">
  62. <th width="10px">
  63. '.get_lang('Number').'
  64. </th>
  65. <th width="10px" >
  66. '.get_lang('True').'
  67. </th>
  68. <th width="50%">
  69. '.get_lang('Answer').'
  70. </th>
  71. '.$comment_title.'
  72. '.$feedback_title.'
  73. <th width="50px">
  74. '.get_lang('Weighting').'
  75. </th>
  76. </tr>';
  77. $form->addElement('label', get_lang('Answers').'<br />'.Display::return_icon('fill_field.png'), $html);
  78. $defaults = array();
  79. $correct = 0;
  80. if (!empty($this->id)) {
  81. $answer = new Answer($this->id);
  82. $answer->read();
  83. if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) {
  84. $nb_answers = $answer->nbrAnswers;
  85. }
  86. }
  87. $form->addElement('hidden', 'nb_answers');
  88. $list = new LearnpathList(api_get_user_id());
  89. $flat_list = $list->get_flat_list();
  90. $select_lp_id = array();
  91. $select_lp_id[0] = get_lang('SelectTargetLP');
  92. foreach ($flat_list as $id => $details) {
  93. $select_lp_id[$id] = Text::cut($details['lp_name'], 20);
  94. }
  95. $temp_scenario = array();
  96. if ($nb_answers < 1) {
  97. $nb_answers = 1;
  98. Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
  99. }
  100. for ($i = 1; $i <= $nb_answers; ++$i) {
  101. $form->addElement('html', '<tr>');
  102. if (isset($answer) && is_object($answer)) {
  103. $answer_id = $answer->getRealAnswerIdFromList($i);
  104. if ($answer->correct[$answer_id]) {
  105. $correct = $i;
  106. }
  107. $defaults['answer['.$i.']'] = $answer->answer[$answer_id];
  108. $defaults['comment['.$i.']'] = $answer->comment[$answer_id];
  109. $defaults['weighting['.$i.']'] = Text::float_format($answer->weighting[$answer_id], 1);
  110. if (!empty($answer->destination[$answer_id])) {
  111. $item_list = explode('@@', $answer->destination[$answer_id]);
  112. $try = $item_list[0];
  113. $lp = $item_list[1];
  114. $list_dest = $item_list[2];
  115. $url = $item_list[3];
  116. if ($try == 0) {
  117. $try_result = 0;
  118. } else {
  119. $try_result = 1;
  120. }
  121. if ($url == 0) {
  122. $url_result = '';
  123. } else {
  124. $url_result = $url;
  125. }
  126. $temp_scenario['url'.$i] = $url_result;
  127. $temp_scenario['try'.$i] = $try_result;
  128. $temp_scenario['lp'.$i] = $lp;
  129. $temp_scenario['destination'.$i] = $list_dest;
  130. }
  131. } else {
  132. $defaults['answer[1]'] = get_lang('DefaultUniqueAnswer1');
  133. $defaults['weighting[1]'] = 10;
  134. $defaults['answer[2]'] = get_lang('DefaultUniqueAnswer2');
  135. $defaults['weighting[2]'] = 0;
  136. $temp_scenario['destination'.$i] = array('0');
  137. $temp_scenario['lp'.$i] = array('0');
  138. }
  139. $defaults['scenario'] = $temp_scenario;
  140. $renderer = $form->defaultRenderer();
  141. $renderer->setElementTemplate(
  142. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  143. 'correct'
  144. );
  145. $renderer->setElementTemplate(
  146. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  147. 'counter['.$i.']'
  148. );
  149. $renderer->setElementTemplate(
  150. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  151. 'answer['.$i.']'
  152. );
  153. $renderer->setElementTemplate(
  154. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  155. 'comment['.$i.']'
  156. );
  157. $renderer->setElementTemplate(
  158. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
  159. 'weighting['.$i.']'
  160. );
  161. $answer_number = $form->addElement('text', 'counter['.$i.']', null, ' value = "'.$i.'"');
  162. $answer_number->freeze();
  163. $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
  164. if ($obj_ex->fastEdition) {
  165. $form->addElement('textarea', 'answer['.$i.']', null, $this->textareaSettings);
  166. } else {
  167. $form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
  168. }
  169. $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
  170. if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
  171. if ($obj_ex->fastEdition) {
  172. // feedback
  173. $form->addElement(
  174. 'textarea',
  175. 'comment['.$i.']',
  176. null,
  177. $this->textareaSettings
  178. );
  179. } else {
  180. // feedback
  181. $form->addElement(
  182. 'html_editor',
  183. 'comment['.$i.']',
  184. null,
  185. 'style="vertical-align:middle"',
  186. $editor_config
  187. );
  188. }
  189. } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  190. // Feedback SELECT
  191. $question_list = $obj_ex->selectQuestionList();
  192. $select_question = array();
  193. $select_question[0] = get_lang('SelectTargetQuestion');
  194. // @todo improve this loop if you have 5000 questions it will blow!
  195. if (is_array($question_list)) {
  196. foreach ($question_list as $key => $questionid) {
  197. //To avoid warning messages
  198. if (!is_numeric($questionid)) {
  199. continue;
  200. }
  201. $question = Question::read($questionid);
  202. if ($question) {
  203. $select_question[$questionid] = 'Q'.$key.' :'.Text::cut($question->selectTitle(), 20);
  204. }
  205. }
  206. }
  207. $select_question[-1] = get_lang('ExitTest');
  208. $form->addElement(
  209. 'html_editor',
  210. 'comment['.$i.']',
  211. null,
  212. 'style="vertical-align:middle"',
  213. $editor_config
  214. );
  215. // Direct feedback
  216. //Adding extra feedback fields
  217. $group = array();
  218. $group['try'.$i] = $form->createElement('checkbox', 'try'.$i, null, get_lang('TryAgain'));
  219. $group['lp'.$i] = $form->createElement(
  220. 'select',
  221. 'lp'.$i,
  222. get_lang('SeeTheory').': ',
  223. $select_lp_id
  224. );
  225. $group['destination'.$i] = $form->createElement(
  226. 'select',
  227. 'destination'.$i,
  228. get_lang('GoToQuestion').': ',
  229. $select_question
  230. );
  231. $group['url'.$i] = $form->createElement(
  232. 'text',
  233. 'url'.$i,
  234. get_lang('Other').': ',
  235. array('class' => 'span2', 'placeholder' => get_lang('Other'))
  236. );
  237. $form->addGroup($group, 'scenario');
  238. $renderer->setElementTemplate(
  239. '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}',
  240. 'scenario'
  241. );
  242. }
  243. $form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0'));
  244. $form->addElement('html', '</tr>');
  245. }
  246. $form->addElement('html', '</table>');
  247. $form->addElement('html', '<br />');
  248. $navigator_info = api_get_navigator();
  249. // ie6 fix.
  250. if ($form->isFrozen() == false) {
  251. if ($obj_ex->edit_exercise_in_lp == true) {
  252. if ($navigator_info['name'] == 'Internet Explorer' && $navigator_info['version'] == '6') {
  253. $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'), 'class="btn minus"');
  254. $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'), 'class="btn plus"');
  255. $form->addElement('submit', 'submitQuestion', $this->submitText, 'class="'.$this->submitClass.'"');
  256. } else {
  257. //setting the save button here and not in the question class.php
  258. $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'), 'class="btn minus"');
  259. $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'), 'class="btn plus"');
  260. $form->addElement('style_submit_button', 'submitQuestion', $this->submitText, 'class="'.$this->submitClass.'"');
  261. }
  262. }
  263. $renderer->setElementTemplate('{element}&nbsp;', 'submitQuestion');
  264. $renderer->setElementTemplate('{element}&nbsp;', 'lessAnswers');
  265. $renderer->setElementTemplate('{element}&nbsp;', 'moreAnswers');
  266. }
  267. $form->addElement('html', '</div></div>');
  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. // Auto fill question
  277. if ($this->isContent == 1) {
  278. $form->setDefaults($defaults);
  279. } else {
  280. // Default values
  281. $defaults = array();
  282. $defaults['weighting[1]'] = 1;
  283. $defaults['correct'] = 1;
  284. $form->setDefaults($defaults);
  285. }
  286. }
  287. $form->setConstants(array('nb_answers' => $nb_answers));
  288. }
  289. /**
  290. * abstract function which creates the form to create / edit the answers of the question
  291. * @param the formvalidator instance
  292. * @param the answers number to display
  293. */
  294. public function processAnswersCreation($form)
  295. {
  296. $questionWeighting = $nbrGoodAnswers = 0;
  297. $correct = $form->getSubmitValue('correct');
  298. $objAnswer = new Answer($this->id);
  299. $nb_answers = $form->getSubmitValue('nb_answers');
  300. for ($i = 1; $i <= $nb_answers; $i++) {
  301. $answer = trim($form->getSubmitValue('answer['.$i.']'));
  302. $comment = trim($form->getSubmitValue('comment['.$i.']'));
  303. $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
  304. $scenario = $form->getSubmitValue('scenario');
  305. //$list_destination = $form -> getSubmitValue('destination'.$i);
  306. //$destination_str = $form -> getSubmitValue('destination'.$i);
  307. $try = $scenario['try'.$i];
  308. $lp = $scenario['lp'.$i];
  309. $destination = $scenario['destination'.$i];
  310. $url = trim($scenario['url'.$i]);
  311. /*
  312. How we are going to parse the destination value
  313. here we parse the destination value which is a string
  314. 1@@3@@2;4;4;@@http://www.chamilo.org
  315. where: try_again@@lp_id@@selected_questions@@url
  316. try_again = is 1 || 0
  317. lp_id = id of a learning path (0 if dont select)
  318. selected_questions= ids of questions
  319. url= an url
  320. $destination_str='';
  321. foreach ($list_destination as $destination_id) {
  322. $destination_str.=$destination_id.';';
  323. }*/
  324. $goodAnswer = ($correct == $i) ? true : false;
  325. if ($goodAnswer) {
  326. $nbrGoodAnswers++;
  327. $weighting = abs($weighting);
  328. if ($weighting > 0) {
  329. $questionWeighting += $weighting;
  330. }
  331. }
  332. if (empty($try)) {
  333. $try = 0;
  334. }
  335. if (empty($lp)) {
  336. $lp = 0;
  337. }
  338. if (empty($destination)) {
  339. $destination = 0;
  340. }
  341. if ($url == '') {
  342. $url = 0;
  343. }
  344. //1@@1;2;@@2;4;4;@@http://www.chamilo.org
  345. $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
  346. $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i, null, null, $dest);
  347. }
  348. // saves the answers into the data base
  349. $objAnswer->save();
  350. // sets the total weighting of the question
  351. $this->updateWeighting($questionWeighting);
  352. $this->save();
  353. }
  354. /**
  355. * {@inheritdoc}
  356. */
  357. public function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false, $hideTitle = 0)
  358. {
  359. $header = parent::return_header($feedback_type, $counter, $score, $show_media, $hideTitle);
  360. $header .= '<table class="'.$this->question_table_class.'">
  361. <tr>
  362. <th>'.get_lang("Choice").'</th>
  363. <th>'.get_lang("ExpectedChoice").'</th>
  364. <th>'.get_lang("Answer").'</th>';
  365. if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
  366. $header .= '<th>'.get_lang("Comment").'</th>';
  367. } else {
  368. $header .= '<th>&nbsp;</th>';
  369. }
  370. $header .= '</tr>';
  371. return $header;
  372. }
  373. /**
  374. * Create database record for the given answer
  375. * @param int The answer ID (technically 1 is OK if you don't know)
  376. * @param int The question this answer is attached to
  377. * @param string The answer itself
  378. * @param string The answer comment (shown as feedback if enabled)
  379. * @param float Score given by this answer if selected (can be negative)
  380. * @param int Whether this answer is considered correct (1) or not (0)
  381. * @param int The course ID - if not provided, will be guessed from the context
  382. * @return void
  383. * @assert (1,null,'a','',1,1,null) === false
  384. * @assert (1,1,'','',1,1,null) === false
  385. */
  386. public function create_answer(
  387. $id = 1,
  388. $question_id,
  389. $answer_title,
  390. $comment = '',
  391. $score = 0,
  392. $correct = 0,
  393. $course_id = null
  394. ) {
  395. if (empty($question_id) or empty($answer_title)) {
  396. return false;
  397. }
  398. $tbl_quiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
  399. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  400. if (empty($course_id)) {
  401. $course_id = api_get_course_int_id();
  402. }
  403. $question_id = filter_var($question_id, FILTER_SANITIZE_NUMBER_INT);
  404. $score = filter_var($score, FILTER_SANITIZE_NUMBER_FLOAT);
  405. $correct = filter_var($correct, FILTER_SANITIZE_NUMBER_INT);
  406. if (empty($question_id) or empty($score) or empty($correct)) {
  407. return false;
  408. }
  409. // Get the max position
  410. $sql = "SELECT max(position) as max_position FROM $tbl_quiz_answer WHERE 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. $sql = "INSERT INTO $tbl_quiz_answer (question_id,answer,correct,comment,ponderation,position,destination)"
  416. ."VALUES ($question_id, '".Database::escape_string($answer_title)."',"
  417. ."$correct,'".Database::escape_string($comment)."',$score,$position, "
  418. ." '0@@0@@0@@0')";
  419. Database::query($sql);
  420. if ($correct) {
  421. $sql = "UPDATE $tbl_quiz_question SET ponderation = (ponderation + $score) WHERE iid = ".$question_id;
  422. $rs = Database::query($sql);
  423. return $rs;
  424. }
  425. }
  426. }