calculated_answer.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class CalculatedAnswer
  5. * This class contains calculated answer form and answer processing functions
  6. *
  7. * @author Imanol Losada
  8. * @package chamilo.exercise
  9. **/
  10. class CalculatedAnswer extends Question
  11. {
  12. static $typePicture = 'calculated_answer.png';
  13. static $explanationLangVar = 'CalculatedAnswer';
  14. /**
  15. * Constructor
  16. */
  17. public function __construct()
  18. {
  19. parent::__construct();
  20. $this -> type = CALCULATED_ANSWER;
  21. $this -> isContent = $this-> getIsContent();
  22. }
  23. /**
  24. * function which redefines Question::createAnswersForm
  25. * @param FormValidator $form
  26. */
  27. 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. '<img src="../img/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_PATH).'main/exercice/evalmathnotation.php',
  125. array(
  126. 'class' => 'btn ajax',
  127. 'data-title' => get_lang('NotationList'),
  128. '_target' => '_blank'
  129. )
  130. );
  131. $form->addElement(
  132. 'label', null,
  133. $notationListButton);
  134. $form->addElement('label', null, get_lang('FormulaExample'));
  135. $form->addElement('text', 'formula', get_lang('Formula'), array('id' => 'formula', 'class' => 'span4'));
  136. $form->addRule('formula', get_lang('GiveFormula'), 'required');
  137. $form->addElement('text', 'weighting', get_lang('Weighting'), array('id' => 'weighting', 'class' => 'span1'));
  138. $form->setDefaults(array('weighting' => '10'));
  139. $form->addElement('text', 'answerVariations', get_lang('AnswerVariations'), array('class' => 'span1'));
  140. $form->addRule('answerVariations', get_lang('GiveAnswerVariations'),'required');
  141. $form->setDefaults(array('answerVariations' => '1'));
  142. global $text;
  143. // setting the save button here and not in the question class.php
  144. $form->addButtonSave($text, 'submitQuestion');
  145. if (!empty($this->id)) {
  146. $form -> setDefaults($defaults);
  147. } else {
  148. if ($this->isContent == 1) {
  149. $form->setDefaults($defaults);
  150. }
  151. }
  152. }
  153. /**
  154. * abstract function which creates the form to create / edit the answers of the question
  155. * @param FormValidator $form
  156. */
  157. function processAnswersCreation($form)
  158. {
  159. if (!self::isAnswered()) {
  160. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  161. Database::delete(
  162. $table,
  163. array(
  164. 'c_id = ? AND question_id = ?' => array(
  165. $this->course['real_id'],
  166. $this->id
  167. )
  168. )
  169. );
  170. $answer = $form->getSubmitValue('answer');
  171. $formula = $form->getSubmitValue('formula');
  172. $lowestValues = $form->getSubmitValue('lowestValue');
  173. $highestValues = $form->getSubmitValue('highestValue');
  174. $answerVariations = $form->getSubmitValue('answerVariations');
  175. $this->weighting = $form->getSubmitValue('weighting');
  176. // Create as many answers as $answerVariations
  177. for ($j=0 ; $j < $answerVariations; $j++) {
  178. $auxAnswer = $answer;
  179. $auxFormula = $formula;
  180. $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
  181. if ($nb > 0) {
  182. for ($i=0 ; $i < $nb; ++$i) {
  183. $blankItem = $blanks[0][$i];
  184. $replace = array("[", "]");
  185. $newBlankItem = str_replace($replace, "", $blankItem);
  186. $newBlankItem = "[".trim($newBlankItem)."]";
  187. // take random float values when one or both edge values have a decimal point
  188. $randomValue =
  189. (strpos($lowestValues[$i],'.') !== false ||
  190. strpos($highestValues[$i],'.') !== false) ?
  191. mt_rand($lowestValues[$i]*100,$highestValues[$i]*100)/100 :
  192. mt_rand($lowestValues[$i],$highestValues[$i]);
  193. $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
  194. $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
  195. }
  196. $math = new EvalMath();
  197. $result = $math->evaluate($auxFormula);
  198. $result = number_format($result, 2, ".", "");
  199. // Remove decimal trailing zeros
  200. $result = rtrim($result, "0");
  201. // If it is an integer (ends in .00) remove the decimal point
  202. if (mb_substr($result, -1) === ".") {
  203. $result = str_replace(".", "", $result);
  204. }
  205. // Attach formula
  206. $auxAnswer .= " [".$result."]@@".$formula;
  207. }
  208. $this->save();
  209. $objAnswer = new Answer($this->id);
  210. $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, null);
  211. $objAnswer->position = array();
  212. $objAnswer->save();
  213. }
  214. }
  215. }
  216. /**
  217. * @param null $feedback_type
  218. * @param null $counter
  219. * @param null $score
  220. * @return null|string
  221. */
  222. function return_header($feedback_type = null, $counter = null, $score = null)
  223. {
  224. $header = parent::return_header($feedback_type, $counter, $score);
  225. $header .= '<table class="'.$this->question_table_class .'">
  226. <tr>
  227. <th>'.get_lang("Answer").'</th>
  228. </tr>';
  229. return $header;
  230. }
  231. /**
  232. * Returns true if the current question has been attempted to be answered
  233. * @return boolean
  234. */
  235. public function isAnswered()
  236. {
  237. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  238. $result = Database::select(
  239. 'question_id',
  240. $table,
  241. array(
  242. 'where' => array(
  243. 'question_id = ? AND c_id = ?' => array(
  244. $this->id,
  245. $this->course['real_id']
  246. )
  247. )
  248. )
  249. );
  250. return empty($result) ? false : true;
  251. }
  252. }