calculated_answer.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Webit\Util\EvalMath\EvalMath;
  4. /**
  5. * Class CalculatedAnswer
  6. * This class contains calculated answer form and answer processing functions.
  7. *
  8. * @author Imanol Losada
  9. *
  10. * @package chamilo.exercise
  11. */
  12. class CalculatedAnswer extends Question
  13. {
  14. public static $typePicture = 'calculated_answer.png';
  15. public static $explanationLangVar = 'CalculatedAnswer';
  16. /**
  17. * Constructor.
  18. */
  19. public function __construct()
  20. {
  21. parent::__construct();
  22. $this->type = CALCULATED_ANSWER;
  23. $this->isContent = $this->getIsContent();
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function createAnswersForm($form)
  29. {
  30. $defaults = [];
  31. $defaults['answer'] = get_lang('DefaultTextInBlanks');
  32. if (!empty($this->id)) {
  33. $objAnswer = new Answer($this->id);
  34. $preArray = explode('@@', $objAnswer->selectAnswer(1));
  35. $defaults['formula'] = array_pop($preArray);
  36. $defaults['answer'] = array_shift($preArray);
  37. $defaults['answer'] = preg_replace("/\[.*\]/", '', $defaults['answer']);
  38. $defaults['weighting'] = $this->weighting;
  39. }
  40. $lowestValue = '1.00';
  41. $highestValue = '20.00';
  42. // javascript //
  43. echo '<script>
  44. function parseTextNumber(textNumber, floatValue) {
  45. if (textNumber.indexOf(".") > -1) {
  46. textNumber = parseFloat(textNumber);
  47. floatValue.exists = "true";
  48. } else {
  49. textNumber = parseInt(textNumber);
  50. }
  51. return textNumber;
  52. }
  53. function updateRandomValue(element) {
  54. // "floatValue" helps to distinguish between an integer (10) and a float with all 0 decimals (10.00)
  55. var floatValue = { exists: "false" };
  56. var index = (element.name).match(/\[[^\]]*\]/g);
  57. var lowestValue = parseTextNumber(document.getElementById("lowestValue"+index).value, floatValue);
  58. var highestValue = parseTextNumber(document.getElementById("highestValue"+index).value, floatValue);
  59. var result = Math.random() * (highestValue - lowestValue) + lowestValue;
  60. if (floatValue.exists == "true") {
  61. result = parseFloat(result).toFixed(2);
  62. } else {
  63. result = parseInt(result);
  64. }
  65. document.getElementById("randomValue"+index).innerHTML = "'.get_lang("ExampleValue").': " + result;
  66. }
  67. CKEDITOR.on("instanceCreated", function(e) {
  68. if (e.editor.name === "answer") {
  69. e.editor.on("change", updateBlanks);
  70. }
  71. });
  72. var firstTime = true;
  73. function updateBlanks(e) {
  74. if (firstTime) {
  75. field = document.getElementById("answer");
  76. var answer = field.value;
  77. } else {
  78. var answer = e.editor.getData();
  79. }
  80. var blanks = answer.match(/\[[^\]]*\]/g);
  81. var fields = "<div class=\"form-group\"><label class=\"col-sm-2\">'.get_lang('VariableRanges').'</label><div class=\"col-sm-8\"><table>";
  82. if (blanks!=null) {
  83. if (typeof updateBlanks.randomValues === "undefined") {
  84. updateBlanks.randomValues = [];
  85. }
  86. for (i=0 ; i<blanks.length ; i++){
  87. if (document.getElementById("lowestValue["+i+"]") && document.getElementById("highestValue["+i+"]")) {
  88. lowestValue = document.getElementById("lowestValue["+i+"]").value;
  89. highestValue = document.getElementById("highestValue["+i+"]").value;
  90. } else {
  91. lowestValue = '.$lowestValue.'.toFixed(2);
  92. highestValue = '.$highestValue.'.toFixed(2);
  93. for (j=0; j<blanks.length; j++) {
  94. updateBlanks.randomValues[j] = parseFloat(Math.random() * (highestValue - lowestValue) + lowestValue).toFixed(2);
  95. }
  96. }
  97. fields += "<tr><td><label>"+blanks[i]+"</label></td><td><input class=\"span1\" style=\"margin-left: 0em;\" size=\"5\" value=\""+lowestValue+"\" type=\"text\" id=\"lowestValue["+i+"]\" name=\"lowestValue["+i+"]\" onblur=\"updateRandomValue(this)\"/></td><td><input class=\"span1\" style=\"margin-left: 0em; width:80px;\" size=\"5\" value=\""+highestValue+"\" type=\"text\" id=\"highestValue["+i+"]\" name=\"highestValue["+i+"]\" onblur=\"updateRandomValue(this)\"/></td><td><label class=\"span3\" id=\"randomValue["+i+"]\"/>'.get_lang('ExampleValue').': "+updateBlanks.randomValues[i]+"</label></td></tr>";
  98. }
  99. }
  100. document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>";
  101. if (firstTime) {
  102. firstTime = false;
  103. }
  104. }
  105. window.onload = updateBlanks;
  106. </script>';
  107. // answer
  108. $form->addElement('label', null, '<br /><br />'.get_lang('TypeTextBelow').', '.get_lang('And').' '.get_lang('UseTagForBlank'));
  109. $form->addElement(
  110. 'html_editor',
  111. 'answer',
  112. Display::return_icon('fill_field.png'),
  113. [
  114. 'id' => 'answer',
  115. 'onkeyup' => 'javascript: updateBlanks(this);',
  116. ],
  117. [
  118. 'ToolbarSet' => 'TestQuestionDescription',
  119. 'Width' => '100%',
  120. 'Height' => '350',
  121. ]
  122. );
  123. $form->addRule('answer', get_lang('GiveText'), 'required');
  124. $form->addRule('answer', get_lang('DefineBlanks'), 'regex', '/\[.*\]/');
  125. $form->addElement('label', null, get_lang('IfYouWantOnlyIntegerValuesWriteBothLimitsWithoutDecimals'));
  126. $form->addElement('html', '<div id="blanks_weighting"></div>');
  127. $notationListButton = Display::url(
  128. get_lang('NotationList'),
  129. api_get_path(WEB_CODE_PATH).'exercise/evalmathnotation.php',
  130. [
  131. 'class' => 'btn btn-info ajax',
  132. 'data-title' => get_lang('NotationList'),
  133. '_target' => '_blank',
  134. ]
  135. );
  136. $form->addElement(
  137. 'label',
  138. null,
  139. $notationListButton
  140. );
  141. $form->addElement('text', 'formula', [get_lang('Formula'), get_lang('FormulaExample')], ['id' => 'formula']);
  142. $form->addRule('formula', get_lang('GiveFormula'), 'required');
  143. $form->addElement('text', 'weighting', get_lang('Weighting'), ['id' => 'weighting']);
  144. $form->setDefaults(['weighting' => '10']);
  145. $form->addElement('text', 'answerVariations', get_lang('AnswerVariations'));
  146. $form->addRule(
  147. 'answerVariations',
  148. get_lang('GiveAnswerVariations'),
  149. 'required'
  150. );
  151. $form->setDefaults(['answerVariations' => '1']);
  152. global $text;
  153. // setting the save button here and not in the question class.php
  154. $form->addButtonSave($text, 'submitQuestion');
  155. if (!empty($this->id)) {
  156. $form->setDefaults($defaults);
  157. } else {
  158. if ($this->isContent == 1) {
  159. $form->setDefaults($defaults);
  160. }
  161. }
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. public function processAnswersCreation($form, $exercise)
  167. {
  168. if (!self::isAnswered()) {
  169. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  170. Database::delete(
  171. $table,
  172. [
  173. 'c_id = ? AND question_id = ?' => [
  174. $this->course['real_id'],
  175. $this->id,
  176. ],
  177. ]
  178. );
  179. $answer = $form->getSubmitValue('answer');
  180. $formula = $form->getSubmitValue('formula');
  181. $lowestValues = $form->getSubmitValue('lowestValue');
  182. $highestValues = $form->getSubmitValue('highestValue');
  183. $answerVariations = $form->getSubmitValue('answerVariations');
  184. $this->weighting = $form->getSubmitValue('weighting');
  185. // Create as many answers as $answerVariations
  186. for ($j = 0; $j < $answerVariations; $j++) {
  187. $auxAnswer = $answer;
  188. $auxFormula = $formula;
  189. $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
  190. if ($nb > 0) {
  191. for ($i = 0; $i < $nb; $i++) {
  192. $blankItem = $blanks[0][$i];
  193. // take random float values when one or both edge values have a decimal point
  194. $randomValue =
  195. (strpos($lowestValues[$i], '.') !== false ||
  196. strpos($highestValues[$i], '.') !== false) ?
  197. mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
  198. $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
  199. $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
  200. }
  201. $math = new EvalMath();
  202. $result = $math->evaluate($auxFormula);
  203. $result = number_format($result, 2, '.', '');
  204. // Remove decimal trailing zeros
  205. $result = rtrim($result, '0');
  206. // If it is an integer (ends in .00) remove the decimal point
  207. if (mb_substr($result, -1) === '.') {
  208. $result = str_replace('.', '', $result);
  209. }
  210. // Attach formula
  211. $auxAnswer .= " [".$result."]@@".$formula;
  212. }
  213. $this->save($exercise);
  214. $objAnswer = new Answer($this->id);
  215. $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
  216. $objAnswer->position = [];
  217. $objAnswer->save();
  218. }
  219. }
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function return_header(Exercise $exercise, $counter = null, $score = [])
  225. {
  226. $header = parent::return_header($exercise, $counter, $score);
  227. $header .= '<table class="'.$this->question_table_class.'"><tr>';
  228. $header .= '<th>'.get_lang('Answer').'</th>';
  229. if ($exercise->showExpectedChoice()) {
  230. $header .= '<th>'.get_lang('YourChoice').'</th>';
  231. if ($exercise->showExpectedChoiceColumn()) {
  232. $header .= '<th>'.get_lang('ExpectedChoice').'</th>';
  233. }
  234. $header .= '<th>'.get_lang('Status').'</th>';
  235. }
  236. $header .= '</tr>';
  237. return $header;
  238. }
  239. /**
  240. * Returns true if the current question has been attempted to be answered.
  241. *
  242. * @return bool
  243. */
  244. public function isAnswered()
  245. {
  246. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  247. $result = Database::select(
  248. 'question_id',
  249. $table,
  250. [
  251. 'where' => [
  252. 'question_id = ? AND c_id = ?' => [
  253. $this->id,
  254. $this->course['real_id'],
  255. ],
  256. ],
  257. ]
  258. );
  259. return empty($result) ? false : true;
  260. }
  261. }