calculated_answer.class.php 12 KB

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