calculated_answer.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. * @package chamilo.exercise
  10. **/
  11. class CalculatedAnswer extends Question
  12. {
  13. public static $typePicture = 'calculated_answer.png';
  14. public static $explanationLangVar = 'CalculatedAnswer';
  15. /**
  16. * Constructor
  17. */
  18. public function __construct()
  19. {
  20. parent::__construct();
  21. $this->type = CALCULATED_ANSWER;
  22. $this->isContent = $this->getIsContent();
  23. }
  24. /**
  25. * @inheritdoc
  26. */
  27. public function createAnswersForm($form)
  28. {
  29. $defaults = array();
  30. if (!empty($this->id)) {
  31. $objAnswer = new Answer($this->id);
  32. $preArray = explode('@@', $objAnswer->selectAnswer(1));
  33. $defaults['formula'] = array_pop($preArray);
  34. $defaults['answer'] = array_shift($preArray);
  35. $defaults['answer'] = preg_replace("/\[.*\]/", "", $defaults['answer']);
  36. $defaults['weighting'] = $this->weighting;
  37. } else {
  38. $defaults['answer'] = get_lang('DefaultTextInBlanks');
  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. array(
  114. 'id' => 'answer',
  115. 'onkeyup' => 'javascript: updateBlanks(this);',
  116. ),
  117. array(
  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. array(
  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('label', null, get_lang('FormulaExample'));
  142. $form->addElement('text', 'formula', get_lang('Formula'), array('id' => 'formula'));
  143. $form->addRule('formula', get_lang('GiveFormula'), 'required');
  144. $form->addElement('text', 'weighting', get_lang('Weighting'), array('id' => 'weighting'));
  145. $form->setDefaults(array('weighting' => '10'));
  146. $form->addElement('text', 'answerVariations', get_lang('AnswerVariations'));
  147. $form->addRule(
  148. 'answerVariations',
  149. get_lang('GiveAnswerVariations'),
  150. 'required'
  151. );
  152. $form->setDefaults(array('answerVariations' => '1'));
  153. global $text;
  154. // setting the save button here and not in the question class.php
  155. $form->addButtonSave($text, 'submitQuestion');
  156. if (!empty($this->id)) {
  157. $form -> setDefaults($defaults);
  158. } else {
  159. if ($this->isContent == 1) {
  160. $form->setDefaults($defaults);
  161. }
  162. }
  163. }
  164. /**
  165. * @inheritdoc
  166. */
  167. public function processAnswersCreation($form, $exercise)
  168. {
  169. if (!self::isAnswered()) {
  170. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  171. Database::delete(
  172. $table,
  173. array(
  174. 'c_id = ? AND question_id = ?' => array(
  175. $this->course['real_id'],
  176. $this->id
  177. )
  178. )
  179. );
  180. $answer = $form->getSubmitValue('answer');
  181. $formula = $form->getSubmitValue('formula');
  182. $lowestValues = $form->getSubmitValue('lowestValue');
  183. $highestValues = $form->getSubmitValue('highestValue');
  184. $answerVariations = $form->getSubmitValue('answerVariations');
  185. $this->weighting = $form->getSubmitValue('weighting');
  186. // Create as many answers as $answerVariations
  187. for ($j = 0; $j < $answerVariations; $j++) {
  188. $auxAnswer = $answer;
  189. $auxFormula = $formula;
  190. $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
  191. if ($nb > 0) {
  192. for ($i = 0; $i < $nb; ++$i) {
  193. $blankItem = $blanks[0][$i];
  194. $replace = array("[", "]");
  195. $newBlankItem = str_replace($replace, "", $blankItem);
  196. $newBlankItem = "[".trim($newBlankItem)."]";
  197. // take random float values when one or both edge values have a decimal point
  198. $randomValue =
  199. (strpos($lowestValues[$i], '.') !== false ||
  200. strpos($highestValues[$i], '.') !== false) ?
  201. mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
  202. $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
  203. $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
  204. }
  205. $math = new EvalMath();
  206. $result = $math->evaluate($auxFormula);
  207. $result = number_format($result, 2, ".", "");
  208. // Remove decimal trailing zeros
  209. $result = rtrim($result, "0");
  210. // If it is an integer (ends in .00) remove the decimal point
  211. if (mb_substr($result, -1) === ".") {
  212. $result = str_replace(".", "", $result);
  213. }
  214. // Attach formula
  215. $auxAnswer .= " [".$result."]@@".$formula;
  216. }
  217. $this->save();
  218. $objAnswer = new Answer($this->id);
  219. $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
  220. $objAnswer->position = array();
  221. $objAnswer->save();
  222. }
  223. }
  224. }
  225. /**
  226. * @inheritdoc
  227. */
  228. public function return_header($exercise, $counter = null, $score = null)
  229. {
  230. $header = parent::return_header($exercise, $counter, $score);
  231. $header .= '<table class="'.$this->question_table_class.'">
  232. <tr>
  233. <th>'.get_lang('Answer').'</th>
  234. <th>'.get_lang('YourChoice').'</th>
  235. <th>'.get_lang('ExpectedChoice').'</th>
  236. <th>'.get_lang('Status').'</th>
  237. </tr>';
  238. return $header;
  239. }
  240. /**
  241. * Returns true if the current question has been attempted to be answered
  242. * @return boolean
  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. array(
  251. 'where' => array(
  252. 'question_id = ? AND c_id = ?' => array(
  253. $this->id,
  254. $this->course['real_id']
  255. )
  256. )
  257. )
  258. );
  259. return empty($result) ? false : true;
  260. }
  261. }