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