calculated_answer.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. * abstract function which creates the form to create / edit the answers of the question
  166. * @param FormValidator $form
  167. */
  168. public function processAnswersCreation($form)
  169. {
  170. if (!self::isAnswered()) {
  171. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  172. Database::delete(
  173. $table,
  174. array(
  175. 'c_id = ? AND question_id = ?' => array(
  176. $this->course['real_id'],
  177. $this->id
  178. )
  179. )
  180. );
  181. $answer = $form->getSubmitValue('answer');
  182. $formula = $form->getSubmitValue('formula');
  183. $lowestValues = $form->getSubmitValue('lowestValue');
  184. $highestValues = $form->getSubmitValue('highestValue');
  185. $answerVariations = $form->getSubmitValue('answerVariations');
  186. $this->weighting = $form->getSubmitValue('weighting');
  187. // Create as many answers as $answerVariations
  188. for ($j = 0; $j < $answerVariations; $j++) {
  189. $auxAnswer = $answer;
  190. $auxFormula = $formula;
  191. $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
  192. if ($nb > 0) {
  193. for ($i = 0; $i < $nb; ++$i) {
  194. $blankItem = $blanks[0][$i];
  195. $replace = array("[", "]");
  196. $newBlankItem = str_replace($replace, "", $blankItem);
  197. $newBlankItem = "[".trim($newBlankItem)."]";
  198. // take random float values when one or both edge values have a decimal point
  199. $randomValue =
  200. (strpos($lowestValues[$i], '.') !== false ||
  201. strpos($highestValues[$i], '.') !== false) ?
  202. mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
  203. $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
  204. $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
  205. }
  206. $math = new EvalMath();
  207. $result = $math->evaluate($auxFormula);
  208. $result = number_format($result, 2, ".", "");
  209. // Remove decimal trailing zeros
  210. $result = rtrim($result, "0");
  211. // If it is an integer (ends in .00) remove the decimal point
  212. if (mb_substr($result, -1) === ".") {
  213. $result = str_replace(".", "", $result);
  214. }
  215. // Attach formula
  216. $auxAnswer .= " [".$result."]@@".$formula;
  217. }
  218. $this->save();
  219. $objAnswer = new Answer($this->id);
  220. $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
  221. $objAnswer->position = array();
  222. $objAnswer->save();
  223. }
  224. }
  225. }
  226. /**
  227. * @param null $feedback_type
  228. * @param null $counter
  229. * @param null $score
  230. * @return null|string
  231. */
  232. public function return_header($feedback_type = null, $counter = null, $score = null)
  233. {
  234. $header = parent::return_header($feedback_type, $counter, $score);
  235. $header .= '<table class="'.$this->question_table_class.'">
  236. <tr>
  237. <th>'.get_lang('Answer').'</th>
  238. <th>'.get_lang('YourChoice').'</th>
  239. <th>'.get_lang('ExpectedChoice').'</th>
  240. <th>'.get_lang('Status').'</th>
  241. </tr>';
  242. return $header;
  243. }
  244. /**
  245. * Returns true if the current question has been attempted to be answered
  246. * @return boolean
  247. */
  248. public function isAnswered()
  249. {
  250. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  251. $result = Database::select(
  252. 'question_id',
  253. $table,
  254. array(
  255. 'where' => array(
  256. 'question_id = ? AND c_id = ?' => array(
  257. $this->id,
  258. $this->course['real_id']
  259. )
  260. )
  261. )
  262. );
  263. return empty($result) ? false : true;
  264. }
  265. }