calculated_answer.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '350'));
  118. $form->addRule('answer', get_lang('GiveText'),'required');
  119. $form->addRule('answer', get_lang('DefineBlanks'),'regex','/\[.*\]/');
  120. $form->addElement('label', null, get_lang('IfYouWantOnlyIntegerValuesWriteBothLimitsWithoutDecimals'));
  121. $form->addElement('html', '<div id="blanks_weighting"></div>');
  122. $notationListButton = Display::url(
  123. get_lang('NotationList'),
  124. api_get_path(WEB_CODE_PATH).'exercise/evalmathnotation.php',
  125. array(
  126. 'class' => 'btn btn-info ajax',
  127. 'data-title' => get_lang('NotationList'),
  128. '_target' => '_blank'
  129. )
  130. );
  131. $form->addElement(
  132. 'label',
  133. null,
  134. $notationListButton
  135. );
  136. $form->addElement('label', null, get_lang('FormulaExample'));
  137. $form->addElement('text', 'formula', get_lang('Formula'), array('id' => 'formula'));
  138. $form->addRule('formula', get_lang('GiveFormula'), 'required');
  139. $form->addElement('text', 'weighting', get_lang('Weighting'), array('id' => 'weighting'));
  140. $form->setDefaults(array('weighting' => '10'));
  141. $form->addElement('text', 'answerVariations', get_lang('AnswerVariations'));
  142. $form->addRule(
  143. 'answerVariations',
  144. get_lang('GiveAnswerVariations'),
  145. 'required'
  146. );
  147. $form->setDefaults(array('answerVariations' => '1'));
  148. global $text;
  149. // setting the save button here and not in the question class.php
  150. $form->addButtonSave($text, 'submitQuestion');
  151. if (!empty($this->id)) {
  152. $form -> setDefaults($defaults);
  153. } else {
  154. if ($this->isContent == 1) {
  155. $form->setDefaults($defaults);
  156. }
  157. }
  158. }
  159. /**
  160. * abstract function which creates the form to create / edit the answers of the question
  161. * @param FormValidator $form
  162. */
  163. public function processAnswersCreation($form)
  164. {
  165. if (!self::isAnswered()) {
  166. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  167. Database::delete(
  168. $table,
  169. array(
  170. 'c_id = ? AND question_id = ?' => array(
  171. $this->course['real_id'],
  172. $this->id
  173. )
  174. )
  175. );
  176. $answer = $form->getSubmitValue('answer');
  177. $formula = $form->getSubmitValue('formula');
  178. $lowestValues = $form->getSubmitValue('lowestValue');
  179. $highestValues = $form->getSubmitValue('highestValue');
  180. $answerVariations = $form->getSubmitValue('answerVariations');
  181. $this->weighting = $form->getSubmitValue('weighting');
  182. // Create as many answers as $answerVariations
  183. for ($j = 0; $j < $answerVariations; $j++) {
  184. $auxAnswer = $answer;
  185. $auxFormula = $formula;
  186. $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
  187. if ($nb > 0) {
  188. for ($i = 0; $i < $nb; ++$i) {
  189. $blankItem = $blanks[0][$i];
  190. $replace = array("[", "]");
  191. $newBlankItem = str_replace($replace, "", $blankItem);
  192. $newBlankItem = "[".trim($newBlankItem)."]";
  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 :
  198. mt_rand($lowestValues[$i],$highestValues[$i]);
  199. $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
  200. $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
  201. }
  202. $math = new EvalMath();
  203. $result = $math->evaluate($auxFormula);
  204. $result = number_format($result, 2, ".", "");
  205. // Remove decimal trailing zeros
  206. $result = rtrim($result, "0");
  207. // If it is an integer (ends in .00) remove the decimal point
  208. if (mb_substr($result, -1) === ".") {
  209. $result = str_replace(".", "", $result);
  210. }
  211. // Attach formula
  212. $auxAnswer .= " [".$result."]@@".$formula;
  213. }
  214. $this->save();
  215. $objAnswer = new Answer($this->id);
  216. $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
  217. $objAnswer->position = array();
  218. $objAnswer->save();
  219. }
  220. }
  221. }
  222. /**
  223. * @param null $feedback_type
  224. * @param null $counter
  225. * @param null $score
  226. * @return null|string
  227. */
  228. public function return_header($feedback_type = null, $counter = null, $score = null)
  229. {
  230. $header = parent::return_header($feedback_type, $counter, $score);
  231. $header .= '<table class="'.$this->question_table_class .'">
  232. <tr>
  233. <th>'.get_lang("Answer").'</th>
  234. </tr>';
  235. return $header;
  236. }
  237. /**
  238. * Returns true if the current question has been attempted to be answered
  239. * @return boolean
  240. */
  241. public function isAnswered()
  242. {
  243. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  244. $result = Database::select(
  245. 'question_id',
  246. $table,
  247. array(
  248. 'where' => array(
  249. 'question_id = ? AND c_id = ?' => array(
  250. $this->id,
  251. $this->course['real_id']
  252. )
  253. )
  254. )
  255. );
  256. return empty($result) ? false : true;
  257. }
  258. }