fill_blanks.class.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class FillBlanks
  5. *
  6. * @author Eric Marguin
  7. * @author Julio Montoya multiple fill in blank option added
  8. * @package chamilo.exercise
  9. **/
  10. class FillBlanks extends Question
  11. {
  12. public static $typePicture = 'fill_in_blanks.png';
  13. public static $explanationLangVar = 'FillBlanks';
  14. const FILL_THE_BLANK_STANDARD = 0;
  15. const FILL_THE_BLANK_MENU = 1;
  16. const FILL_THE_BLANK_SEVERAL_ANSWER = 2;
  17. /**
  18. * Constructor
  19. */
  20. public function __construct()
  21. {
  22. parent::__construct();
  23. $this->type = FILL_IN_BLANKS;
  24. $this->isContent = $this->getIsContent();
  25. }
  26. /**
  27. * @inheritdoc
  28. */
  29. public function createAnswersForm($form)
  30. {
  31. $defaults = array();
  32. if (!empty($this->id)) {
  33. $objectAnswer = new Answer($this->id);
  34. $answer = $objectAnswer->selectAnswer(1);
  35. $listAnswersInfo = self::getAnswerInfo($answer);
  36. if ($listAnswersInfo['switchable']) {
  37. $defaults['multiple_answer'] = 1;
  38. } else {
  39. $defaults['multiple_answer'] = 0;
  40. }
  41. //take the complete string except after the last '::'
  42. $defaults['answer'] = $listAnswersInfo['text'];
  43. $defaults['select_separator'] = $listAnswersInfo['blankseparatornumber'];
  44. $blankSeparatorNumber = $listAnswersInfo['blankseparatornumber'];
  45. } else {
  46. $defaults['answer'] = get_lang('DefaultTextInBlanks');
  47. $defaults['select_separator'] = 0;
  48. $blankSeparatorNumber = 0;
  49. }
  50. $blankSeparatorStart = self::getStartSeparator($blankSeparatorNumber);
  51. $blankSeparatorEnd = self::getEndSeparator($blankSeparatorNumber);
  52. $setWeightAndSize = '';
  53. if (isset($listAnswersInfo) && count($listAnswersInfo['tabweighting']) > 0) {
  54. foreach ($listAnswersInfo['tabweighting'] as $i => $weighting) {
  55. $setWeightAndSize .= 'document.getElementById("weighting['.$i.']").value = "'.$weighting.'";';
  56. }
  57. foreach ($listAnswersInfo['tabinputsize'] as $i => $sizeOfInput) {
  58. $setWeightAndSize .= 'document.getElementById("sizeofinput['.$i.']").value = "'.$sizeOfInput.'";';
  59. $setWeightAndSize .= 'document.getElementById("samplesize['.$i.']").style.width = "'.$sizeOfInput.'px";';
  60. }
  61. }
  62. echo '<script>
  63. var firstTime = true;
  64. var originalOrder = new Array();
  65. var blankSeparatorStart = "'.$blankSeparatorStart.'";
  66. var blankSeparatorEnd = "'.$blankSeparatorEnd.'";
  67. var blankSeparatorStartRegexp = getBlankSeparatorRegexp(blankSeparatorStart);
  68. var blankSeparatorEndRegexp = getBlankSeparatorRegexp(blankSeparatorEnd);
  69. var blanksRegexp = "/"+blankSeparatorStartRegexp+"[^"+blankSeparatorStartRegexp+"]*"+blankSeparatorEndRegexp+"/g";
  70. CKEDITOR.on("instanceCreated", function(e) {
  71. if (e.editor.name === "answer") {
  72. //e.editor.on("change", updateBlanks);
  73. e.editor.on("change", function(){
  74. updateBlanks();
  75. });
  76. }
  77. });
  78. function updateBlanks()
  79. {
  80. var answer;
  81. if (firstTime) {
  82. var field = document.getElementById("answer");
  83. answer = field.value;
  84. } else {
  85. answer = CKEDITOR.instances["answer"].getData();
  86. }
  87. // disable the save button, if not blanks have been created
  88. $("button").attr("disabled", "disabled");
  89. $("#defineoneblank").show();
  90. var blanks = answer.match(eval(blanksRegexp));
  91. var fields = "<div class=\"form-group \">";
  92. fields += "<label class=\"col-sm-2 control-label\">'.get_lang('Weighting').'</label>";
  93. fields += "<div class=\"col-sm-8\">";
  94. fields += "<table>";
  95. fields += "<tr><th style=\"padding:0 20px\">'.get_lang("WordTofind").'</th><th style=\"padding:0 20px\">'.get_lang("QuestionWeighting").'</th><th style=\"padding:0 20px\">'.get_lang("BlankInputSize").'</th></tr>";
  96. if (blanks != null) {
  97. for (var i=0; i < blanks.length; i++) {
  98. // remove forbidden characters that causes bugs
  99. blanks[i] = removeForbiddenChars(blanks[i]);
  100. // trim blanks between brackets
  101. blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatorStart, blankSeparatorEnd);
  102. // if the word is empty []
  103. if (blanks[i] == blankSeparatorStartRegexp+blankSeparatorEndRegexp) {
  104. break;
  105. }
  106. // get input size
  107. var inputSize = 100;
  108. var textValue = blanks[i].substr(1, blanks[i].length - 2);
  109. var btoaValue = textValue.hashCode();
  110. if (firstTime == false) {
  111. var element = document.getElementById("samplesize["+i+"]");
  112. if (element) {
  113. inputSize = document.getElementById("sizeofinput["+i+"]").value;
  114. }
  115. }
  116. if (document.getElementById("weighting["+i+"]")) {
  117. var value = document.getElementById("weighting["+i+"]").value;
  118. } else {
  119. var value = "1";
  120. }
  121. fields += "<tr>";
  122. fields += "<td>"+blanks[i]+"</td>";
  123. fields += "<td><input style=\"width:35px\" value=\""+value+"\" type=\"text\" id=\"weighting["+i+"]\" name=\"weighting["+i+"]\" /></td>";
  124. fields += "<td>";
  125. fields += "<input class=\"btn btn-default\" type=\"button\" value=\"-\" onclick=\"changeInputSize(-1, "+i+")\">&nbsp;";
  126. fields += "<input class=\"btn btn-default\" type=\"button\" value=\"+\" onclick=\"changeInputSize(1, "+i+")\">&nbsp;";
  127. fields += "<input class=\"sample\" id=\"samplesize["+i+"]\" data-btoa=\""+btoaValue+"\" type=\"text\" value=\""+textValue+"\" style=\"width:"+inputSize+"px\" disabled=disabled />";
  128. fields += "<input id=\"sizeofinput["+i+"]\" type=\"hidden\" value=\""+inputSize+"\" name=\"sizeofinput["+i+"]\" />";
  129. fields += "</td>";
  130. fields += "</tr>";
  131. // enable the save button
  132. $("button").removeAttr("disabled");
  133. $("#defineoneblank").hide();
  134. }
  135. }
  136. document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>";
  137. $(originalOrder).each(function(i, data) {
  138. if (firstTime == false) {
  139. value = data.value;
  140. var d = $("input.sample[data-btoa=\'"+value+"\']");
  141. var id = d.attr("id");
  142. if (id) {
  143. var sizeInputId = id.replace("samplesize", "sizeofinput");
  144. var sizeInputId = sizeInputId.replace("[", "\\\[");
  145. var sizeInputId = sizeInputId.replace("]", "\\\]");
  146. $("#"+sizeInputId).val(data.width);
  147. d.outerWidth(data.width+"px");
  148. }
  149. }
  150. });
  151. updateOrder(blanks);
  152. if (firstTime) {
  153. firstTime = false;
  154. '.$setWeightAndSize.'
  155. }
  156. }
  157. window.onload = updateBlanks;
  158. String.prototype.hashCode = function() {
  159. var hash = 0, i, chr, len;
  160. if (this.length === 0) return hash;
  161. for (i = 0, len = this.length; i < len; i++) {
  162. chr = this.charCodeAt(i);
  163. hash = ((hash << 5) - hash) + chr;
  164. hash |= 0; // Convert to 32bit integer
  165. }
  166. return hash;
  167. };
  168. function updateOrder(blanks)
  169. {
  170. originalOrder = new Array();
  171. if (blanks != null) {
  172. for (var i=0; i < blanks.length; i++) {
  173. // remove forbidden characters that causes bugs
  174. blanks[i] = removeForbiddenChars(blanks[i]);
  175. // trim blanks between brackets
  176. blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatorStart, blankSeparatorEnd);
  177. // if the word is empty []
  178. if (blanks[i] == blankSeparatorStartRegexp+blankSeparatorEndRegexp) {
  179. break;
  180. }
  181. var textValue = blanks[i].substr(1, blanks[i].length - 2);
  182. var btoaValue = textValue.hashCode();
  183. if (firstTime == false) {
  184. var element = document.getElementById("samplesize["+i+"]");
  185. if (element) {
  186. inputSize = document.getElementById("sizeofinput["+i+"]").value;
  187. originalOrder.push({ "width" : inputSize, "value": btoaValue });
  188. }
  189. }
  190. }
  191. }
  192. }
  193. function changeInputSize(coef, inIdNum)
  194. {
  195. if (firstTime) {
  196. var field = document.getElementById("answer");
  197. answer = field.value;
  198. } else {
  199. answer = CKEDITOR.instances["answer"].getData();
  200. }
  201. var blanks = answer.match(eval(blanksRegexp));
  202. var currentWidth = $("#samplesize\\\["+inIdNum+"\\\]").width();
  203. var newWidth = currentWidth + coef * 20;
  204. newWidth = Math.max(20, newWidth);
  205. newWidth = Math.min(newWidth, 600);
  206. $("#samplesize\\\["+inIdNum+"\\\]").outerWidth(newWidth);
  207. $("#sizeofinput\\\["+inIdNum+"\\\]").attr("value", newWidth);
  208. updateOrder(blanks);
  209. }
  210. function removeForbiddenChars(inTxt)
  211. {
  212. outTxt = inTxt;
  213. outTxt = outTxt.replace(/&quot;/g, ""); // remove the char
  214. outTxt = outTxt.replace(/\x22/g, ""); // remove the char
  215. outTxt = outTxt.replace(/"/g, ""); // remove the char
  216. outTxt = outTxt.replace(/\\\\/g, ""); // remove the \ char
  217. outTxt = outTxt.replace(/&nbsp;/g, " ");
  218. outTxt = outTxt.replace(/^ +/, "");
  219. outTxt = outTxt.replace(/ +$/, "");
  220. return outTxt;
  221. }
  222. function changeBlankSeparator()
  223. {
  224. var separatorNumber = $("#select_separator").val();
  225. var tabSeparator = getSeparatorFromNumber(separatorNumber);
  226. blankSeparatorStart = tabSeparator[0];
  227. blankSeparatorEnd = tabSeparator[1];
  228. blankSeparatorStartRegexp = getBlankSeparatorRegexp(blankSeparatorStart);
  229. blankSeparatorEndRegexp = getBlankSeparatorRegexp(blankSeparatorEnd);
  230. blanksRegexp = "/"+blankSeparatorStartRegexp+"[^"+blankSeparatorStartRegexp+"]*"+blankSeparatorEndRegexp+"/g";
  231. updateBlanks();
  232. }
  233. // this function is the same than the PHP one
  234. // if modify it modify the php one escapeForRegexp
  235. function getBlankSeparatorRegexp(inTxt)
  236. {
  237. var tabSpecialChar = new Array(".", "+", "*", "?", "[", "^", "]", "$", "(", ")",
  238. "{", "}", "=", "!", "<", ">", "|", ":", "-", ")");
  239. for (var i=0; i < tabSpecialChar.length; i++) {
  240. if (inTxt == tabSpecialChar[i]) {
  241. return "\\\"+inTxt;
  242. }
  243. }
  244. return inTxt;
  245. }
  246. // this function is the same than the PHP one
  247. // if modify it modify the php one getAllowedSeparator
  248. function getSeparatorFromNumber(innumber)
  249. {
  250. tabSeparator = new Array();
  251. tabSeparator[0] = new Array("[", "]");
  252. tabSeparator[1] = new Array("{", "}");
  253. tabSeparator[2] = new Array("(", ")");
  254. tabSeparator[3] = new Array("*", "*");
  255. tabSeparator[4] = new Array("#", "#");
  256. tabSeparator[5] = new Array("%", "%");
  257. tabSeparator[6] = new Array("$", "$");
  258. return tabSeparator[innumber];
  259. }
  260. function trimBlanksBetweenSeparator(inTxt, inSeparatorStart, inSeparatorEnd)
  261. {
  262. var result = inTxt
  263. result = result.replace(inSeparatorStart, "");
  264. result = result.replace(inSeparatorEnd, "");
  265. result = result.trim();
  266. return inSeparatorStart+result+inSeparatorEnd;
  267. }
  268. </script>';
  269. // answer
  270. $form->addLabel(
  271. null,
  272. get_lang('TypeTextBelow').', '.get_lang('And').' '.get_lang('UseTagForBlank')
  273. );
  274. $form->addElement(
  275. 'html_editor',
  276. 'answer',
  277. Display::return_icon('fill_field.png'),
  278. ['id' => 'answer'],
  279. array('ToolbarSet' => 'TestQuestionDescription')
  280. );
  281. $form->addRule('answer', get_lang('GiveText'), 'required');
  282. //added multiple answers
  283. $form->addElement('checkbox', 'multiple_answer', '', get_lang('FillInBlankSwitchable'));
  284. $form->addElement(
  285. 'select',
  286. 'select_separator',
  287. get_lang("SelectFillTheBlankSeparator"),
  288. self::getAllowedSeparatorForSelect(),
  289. ' id="select_separator" style="width:150px" onchange="changeBlankSeparator()" '
  290. );
  291. $form->addLabel(
  292. null,
  293. '<input type="button" onclick="updateBlanks()" value="'.get_lang('RefreshBlanks').'" class="btn btn-default" />'
  294. );
  295. $form->addHtml('<div id="blanks_weighting"></div>');
  296. global $text;
  297. // setting the save button here and not in the question class.php
  298. $form->addHtml('<div id="defineoneblank" style="color:#D04A66; margin-left:160px">'.get_lang('DefineBlanks').'</div>');
  299. $form->addButtonSave($text, 'submitQuestion');
  300. if (!empty($this->id)) {
  301. $form->setDefaults($defaults);
  302. } else {
  303. if ($this->isContent == 1) {
  304. $form->setDefaults($defaults);
  305. }
  306. }
  307. }
  308. /**
  309. * Function which creates the form to create/edit the answers of the question
  310. * @param FormValidator $form
  311. */
  312. public function processAnswersCreation($form)
  313. {
  314. $answer = $form->getSubmitValue('answer');
  315. // Due the ckeditor transform the elements to their HTML value
  316. //$answer = api_html_entity_decode($answer, ENT_QUOTES, $charset);
  317. //$answer = htmlentities(api_utf8_encode($answer));
  318. // remove the "::" eventually written by the user
  319. $answer = str_replace('::', '', $answer);
  320. // remove starting and ending space and &nbsp;
  321. $answer = api_preg_replace("/\xc2\xa0/", " ", $answer);
  322. // start and end separator
  323. $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
  324. $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
  325. $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
  326. $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
  327. // remove spaces at the beginning and the end of text in square brackets
  328. $answer = preg_replace_callback(
  329. "/".$blankStartSeparatorRegexp."[^]]+".$blankEndSeparatorRegexp."/",
  330. function ($matches) use ($blankStartSeparator, $blankEndSeparator) {
  331. $matchingResult = $matches[0];
  332. $matchingResult = trim($matchingResult, $blankStartSeparator);
  333. $matchingResult = trim($matchingResult, $blankEndSeparator);
  334. $matchingResult = trim($matchingResult);
  335. // remove forbidden chars
  336. $matchingResult = str_replace("/\\/", "", $matchingResult);
  337. $matchingResult = str_replace('/"/', "", $matchingResult);
  338. return $blankStartSeparator.$matchingResult.$blankEndSeparator;
  339. },
  340. $answer
  341. );
  342. // get the blanks weightings
  343. $nb = preg_match_all(
  344. '/'.$blankStartSeparatorRegexp.'[^'.$blankStartSeparatorRegexp.']*'.$blankEndSeparatorRegexp.'/',
  345. $answer,
  346. $blanks
  347. );
  348. if (isset($_GET['editQuestion'])) {
  349. $this->weighting = 0;
  350. }
  351. /* if we have some [tobefound] in the text
  352. build the string to save the following in the answers table
  353. <p>I use a [computer] and a [pen].</p>
  354. becomes
  355. <p>I use a [computer] and a [pen].</p>::100,50:100,50@1
  356. ++++++++-------**
  357. --- -- --- -- -
  358. A B (C) (D)(E)
  359. +++++++ : required, weighting of each words
  360. ------- : optional, input width to display, 200 if not present
  361. ** : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  362. A : weighting for the word [computer]
  363. B : weighting for the word [pen]
  364. C : input width for the word [computer]
  365. D : input width for the word [pen]
  366. E : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  367. */
  368. if ($nb > 0) {
  369. $answer .= '::';
  370. // weighting
  371. for ($i=0; $i < $nb; ++$i) {
  372. // enter the weighting of word $i
  373. $answer .= $form->getSubmitValue('weighting['.$i.']');
  374. // not the last word, add ","
  375. if ($i != $nb - 1) {
  376. $answer .= ",";
  377. }
  378. // calculate the global weighting for the question
  379. $this -> weighting += $form->getSubmitValue('weighting['.$i.']');
  380. }
  381. // input width
  382. $answer .= ":";
  383. for ($i = 0; $i < $nb; ++$i) {
  384. // enter the width of input for word $i
  385. $answer .= $form->getSubmitValue('sizeofinput['.$i.']');
  386. // not the last word, add ","
  387. if ($i != $nb - 1) {
  388. $answer .= ",";
  389. }
  390. }
  391. }
  392. // write the blank separator code number
  393. // see function getAllowedSeparator
  394. /*
  395. 0 [...]
  396. 1 {...}
  397. 2 (...)
  398. 3 *...*
  399. 4 #...#
  400. 5 %...%
  401. 6 $...$
  402. */
  403. $answer .= ":".$form->getSubmitValue('select_separator');
  404. // Allow answers order switches
  405. $is_multiple = $form -> getSubmitValue('multiple_answer');
  406. $answer.= '@'.$is_multiple;
  407. $this->save();
  408. $objAnswer = new Answer($this->id);
  409. $objAnswer->createAnswer($answer, 0, '', 0, 1);
  410. $objAnswer->save();
  411. }
  412. /**
  413. * @param null $feedback_type
  414. * @param null $counter
  415. * @param null $score
  416. * @return string
  417. */
  418. public function return_header($feedback_type = null, $counter = null, $score = null)
  419. {
  420. $header = parent::return_header($feedback_type, $counter, $score);
  421. $header .= '<table class="'.$this->question_table_class .'">
  422. <tr>
  423. <th>'.get_lang("Answer").'</th>
  424. </tr>';
  425. return $header;
  426. }
  427. /**
  428. * @param int $currentQuestion
  429. * @param int $questionId
  430. * @param string $correctItem
  431. * @param array $attributes
  432. * @param string $answer
  433. * @param array $listAnswersInfo
  434. * @param boolean $displayForStudent
  435. * @param int $inBlankNumber
  436. * @return string
  437. */
  438. public static function getFillTheBlankHtml(
  439. $currentQuestion,
  440. $questionId,
  441. $correctItem,
  442. $attributes,
  443. $answer,
  444. $listAnswersInfo,
  445. $displayForStudent,
  446. $inBlankNumber
  447. ) {
  448. $result = '';
  449. $inTabTeacherSolution = $listAnswersInfo['tabwords'];
  450. $inTeacherSolution = $inTabTeacherSolution[$inBlankNumber];
  451. switch (self::getFillTheBlankAnswerType($inTeacherSolution)) {
  452. case self::FILL_THE_BLANK_MENU:
  453. $selected = '';
  454. // the blank menu
  455. $optionMenu = '';
  456. // display a menu from answer separated with |
  457. // if display for student, shuffle the correct answer menu
  458. $listMenu = self::getFillTheBlankMenuAnswers($inTeacherSolution, $displayForStudent);
  459. $result .= '<select id="choice_id_'.$currentQuestion.'_'.$inBlankNumber.'" name="choice['.$questionId.'][]">';
  460. for ($k=0; $k < count($listMenu); $k++) {
  461. $selected = '';
  462. if ($correctItem == $listMenu[$k]) {
  463. $selected = " selected=selected ";
  464. }
  465. // if in teacher view, display the first item by default, which is the right answer
  466. if ($k==0 && !$displayForStudent) {
  467. $selected = " selected=selected ";
  468. }
  469. $optionMenu .= '<option '.$selected.' value="'.$listMenu[$k].'">'.$listMenu[$k].'</option>';
  470. }
  471. if ($selected == '') {
  472. // no good answer have been found...
  473. $selected = " selected=selected ";
  474. }
  475. $result .= "<option $selected value=''>--</option>";
  476. $result .= $optionMenu;
  477. $result .= '</select>';
  478. break;
  479. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  480. //no break
  481. case self::FILL_THE_BLANK_STANDARD:
  482. default:
  483. $attributes['id'] = 'choice_id_'.$currentQuestion.'_'.$inBlankNumber;
  484. $result = Display::input(
  485. 'text',
  486. "choice[$questionId][]",
  487. $correctItem,
  488. $attributes
  489. );
  490. break;
  491. }
  492. return $result;
  493. }
  494. /**
  495. * Return an array with the different choices available
  496. * when the answers between bracket show as a menu
  497. * @param string $correctAnswer
  498. * @param bool $displayForStudent true if we want to shuffle the choices of the menu for students
  499. *
  500. * @return array
  501. */
  502. public static function getFillTheBlankMenuAnswers($correctAnswer, $displayForStudent)
  503. {
  504. $list = api_preg_split("/\|/", $correctAnswer);
  505. if ($displayForStudent) {
  506. shuffle($list);
  507. }
  508. return $list;
  509. }
  510. /**
  511. * Return the array index of the student answer
  512. * @param string $correctAnswer the menu Choice1|Choice2|Choice3
  513. * @param string $studentAnswer the student answer must be Choice1 or Choice2 or Choice3
  514. *
  515. * @return int in the example 0 1 or 2 depending of the choice of the student
  516. */
  517. public static function getFillTheBlankMenuAnswerNum($correctAnswer, $studentAnswer)
  518. {
  519. $listChoices = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  520. foreach ($listChoices as $num => $value) {
  521. if ($value == $studentAnswer) {
  522. return $num;
  523. }
  524. }
  525. // should not happened, because student choose the answer in a menu of possible answers
  526. return -1;
  527. }
  528. /**
  529. * Return the possible answer if the answer between brackets is a multiple choice menu
  530. * @param string $correctAnswer
  531. *
  532. * @return array
  533. */
  534. public static function getFillTheBlankSeveralAnswers($correctAnswer)
  535. {
  536. // is answer||Answer||response||Response , mean answer or Answer ...
  537. $listSeveral = api_preg_split("/\|\|/", $correctAnswer);
  538. return $listSeveral;
  539. }
  540. /**
  541. * Return true if student answer is right according to the correctAnswer
  542. * it is not as simple as equality, because of the type of Fill The Blank question
  543. * eg : studentAnswer = 'Un' and correctAnswer = 'Un||1||un'
  544. * @param string $studentAnswer [studentanswer] of the info array of the answer field
  545. * @param string $correctAnswer [tabwords] of the info array of the answer field
  546. *
  547. * @return bool
  548. */
  549. public static function isGoodStudentAnswer($studentAnswer, $correctAnswer)
  550. {
  551. switch (self::getFillTheBlankAnswerType($correctAnswer)) {
  552. case self::FILL_THE_BLANK_MENU:
  553. $listMenu = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  554. $result = $listMenu[0] == $studentAnswer;
  555. break;
  556. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  557. // the answer must be one of the choice made
  558. $listSeveral = self::getFillTheBlankSeveralAnswers($correctAnswer);
  559. $result = in_array($studentAnswer, $listSeveral);
  560. break;
  561. case self::FILL_THE_BLANK_STANDARD:
  562. default:
  563. $result = $studentAnswer == $correctAnswer;
  564. break;
  565. }
  566. return $result;
  567. }
  568. /**
  569. * @param string $correctAnswer
  570. *
  571. * @return int
  572. */
  573. public static function getFillTheBlankAnswerType($correctAnswer)
  574. {
  575. if (api_strpos($correctAnswer, "|") && !api_strpos($correctAnswer, "||")) {
  576. return self::FILL_THE_BLANK_MENU;
  577. } elseif (api_strpos($correctAnswer, "||")) {
  578. return self::FILL_THE_BLANK_SEVERAL_ANSWER;
  579. } else {
  580. return self::FILL_THE_BLANK_STANDARD;
  581. }
  582. }
  583. /**
  584. * Return information about the answer
  585. * @param string $userAnswer the text of the answer of the question
  586. * @param bool $isStudentAnswer true if it's a student answer false the empty question model
  587. *
  588. * @return array of information about the answer
  589. */
  590. public static function getAnswerInfo($userAnswer = "", $isStudentAnswer = false)
  591. {
  592. $listAnswerResults = array();
  593. $listAnswerResults['text'] = '';
  594. $listAnswerResults['wordsCount'] = 0;
  595. $listAnswerResults['tabwordsbracket'] = array();
  596. $listAnswerResults['tabwords'] = array();
  597. $listAnswerResults['tabweighting'] = array();
  598. $listAnswerResults['tabinputsize'] = array();
  599. $listAnswerResults['switchable'] = '';
  600. $listAnswerResults['studentanswer'] = array();
  601. $listAnswerResults['studentscore'] = array();
  602. $listAnswerResults['blankseparatornumber'] = 0;
  603. $listDoubleColon = array();
  604. api_preg_match("/(.*)::(.*)$/s", $userAnswer, $listResult);
  605. if (count($listResult) < 2) {
  606. $listDoubleColon[] = '';
  607. $listDoubleColon[] = '';
  608. } else {
  609. $listDoubleColon[] = $listResult[1];
  610. $listDoubleColon[] = $listResult[2];
  611. }
  612. $listAnswerResults['systemstring'] = $listDoubleColon[1];
  613. // make sure we only take the last bit to find special marks
  614. $listArobaseSplit = explode('@', $listDoubleColon[1]);
  615. if (count($listArobaseSplit) < 2) {
  616. $listArobaseSplit[1] = '';
  617. }
  618. // take the complete string except after the last '::'
  619. $listDetails = explode(":", $listArobaseSplit[0]);
  620. // < number of item after the ::[score]:[size]:[separator_id]@ , here there are 3
  621. if (count($listDetails) < 3) {
  622. $listWeightings = explode(',', $listDetails[0]);
  623. $listSizeOfInput = array();
  624. for ($i=0; $i < count($listWeightings); $i++) {
  625. $listSizeOfInput[] = 200;
  626. }
  627. $blankSeparatorNumber = 0; // 0 is [...]
  628. } else {
  629. $listWeightings = explode(',', $listDetails[0]);
  630. $listSizeOfInput = explode(',', $listDetails[1]);
  631. $blankSeparatorNumber = $listDetails[2];
  632. }
  633. $listAnswerResults['text'] = $listDoubleColon[0];
  634. $listAnswerResults['tabweighting'] = $listWeightings;
  635. $listAnswerResults['tabinputsize'] = $listSizeOfInput;
  636. $listAnswerResults['switchable'] = $listArobaseSplit[1];
  637. $listAnswerResults['blankseparatorstart'] = self::getStartSeparator($blankSeparatorNumber);
  638. $listAnswerResults['blankseparatorend'] = self::getEndSeparator($blankSeparatorNumber);
  639. $listAnswerResults['blankseparatornumber'] = $blankSeparatorNumber;
  640. $blankCharStart = self::getStartSeparator($blankSeparatorNumber);
  641. $blankCharEnd = self::getEndSeparator($blankSeparatorNumber);
  642. $blankCharStartForRegexp = self::escapeForRegexp($blankCharStart);
  643. $blankCharEndForRegexp = self::escapeForRegexp($blankCharEnd);
  644. // get all blanks words
  645. $listAnswerResults['wordsCount'] = api_preg_match_all(
  646. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  647. $listDoubleColon[0],
  648. $listWords
  649. );
  650. if ($listAnswerResults['wordsCount'] > 0) {
  651. $listAnswerResults['tabwordsbracket'] = $listWords[0];
  652. // remove [ and ] in string
  653. array_walk(
  654. $listWords[0],
  655. function (&$value, $key, $tabBlankChar) {
  656. $trimChars = '';
  657. for ($i=0; $i < count($tabBlankChar); $i++) {
  658. $trimChars .= $tabBlankChar[$i];
  659. }
  660. $value = trim($value, $trimChars);
  661. },
  662. array($blankCharStart, $blankCharEnd)
  663. );
  664. $listAnswerResults['tabwords'] = $listWords[0];
  665. }
  666. // get all common words
  667. $commonWords = api_preg_replace(
  668. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  669. "::",
  670. $listDoubleColon[0]
  671. );
  672. // if student answer, the second [] is the student answer,
  673. // the third is if student scored or not
  674. $listBrackets = array();
  675. $listWords = array();
  676. if ($isStudentAnswer) {
  677. for ($i=0; $i < count($listAnswerResults['tabwords']); $i++) {
  678. $listBrackets[] = $listAnswerResults['tabwordsbracket'][$i];
  679. $listWords[] = $listAnswerResults['tabwords'][$i];
  680. if ($i+1 < count($listAnswerResults['tabwords'])) {
  681. // should always be
  682. $i++;
  683. }
  684. $listAnswerResults['studentanswer'][] = $listAnswerResults['tabwords'][$i];
  685. if ($i+1 < count($listAnswerResults['tabwords'])) {
  686. // should always be
  687. $i++;
  688. }
  689. $listAnswerResults['studentscore'][] = $listAnswerResults['tabwords'][$i];
  690. }
  691. $listAnswerResults['tabwords'] = $listWords;
  692. $listAnswerResults['tabwordsbracket'] = $listBrackets;
  693. // if we are in student view, we've got 3 times :::::: for common words
  694. $commonWords = api_preg_replace("/::::::/", "::", $commonWords);
  695. }
  696. $listAnswerResults['commonwords'] = explode("::", $commonWords);
  697. return $listAnswerResults;
  698. }
  699. /**
  700. * Return an array of student state answers for fill the blank questions
  701. * for each students that answered the question
  702. * -2 : didn't answer
  703. * -1 : student answer is wrong
  704. * 0 : student answer is correct
  705. * >0 : for fill the blank question with choice menu, is the index of the student answer (right answer indice is 0)
  706. *
  707. * @param integer $testId
  708. * @param integer $questionId
  709. * @param $studentsIdList
  710. * @param string $startDate
  711. * @param string $endDate
  712. * @param bool $useLastAnsweredAttempt
  713. * @return array
  714. * (
  715. * [student_id] => Array
  716. * (
  717. * [first fill the blank for question] => -1
  718. * [second fill the blank for question] => 2
  719. * [third fill the blank for question] => -1
  720. * )
  721. * )
  722. */
  723. public static function getFillTheBlankTabResult(
  724. $testId,
  725. $questionId,
  726. $studentsIdList,
  727. $startDate,
  728. $endDate,
  729. $useLastAnsweredAttempt = true
  730. ) {
  731. $tblTrackEAttempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  732. $tblTrackEExercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  733. $courseId = api_get_course_int_id();
  734. // If no user has answered questions, no need to go further. Return empty array.
  735. if (empty($studentsIdList)) {
  736. return array();
  737. }
  738. // request to have all the answers of student for this question
  739. // student may have doing it several time
  740. // student may have not answered the bracket id, in this case, is result of the answer is empty
  741. // we got the less recent attempt first
  742. $sql = 'SELECT * FROM '.$tblTrackEAttempt.' tea
  743. LEFT JOIN '.$tblTrackEExercise.' tee
  744. ON
  745. tee.exe_id = tea.exe_id AND
  746. tea.c_id = '.$courseId.' AND
  747. exe_exo_id = '.$testId.'
  748. WHERE
  749. tee.c_id = '.$courseId.' AND
  750. question_id = '.$questionId.' AND
  751. tea.user_id IN ('.implode(',', $studentsIdList).') AND
  752. tea.tms >= "'.$startDate.'" AND
  753. tea.tms <= "'.$endDate.'"
  754. ORDER BY user_id, tea.exe_id;
  755. ';
  756. $res = Database::query($sql);
  757. $tabUserResult = array();
  758. // foreach attempts for all students starting with his older attempt
  759. while ($data = Database::fetch_array($res)) {
  760. $tabAnswer = self::getAnswerInfo($data['answer'], true);
  761. // for each bracket to find in this question
  762. foreach ($tabAnswer['studentanswer'] as $bracketNumber => $studentAnswer) {
  763. if ($tabAnswer['studentanswer'][$bracketNumber] != '') {
  764. // student has answered this bracket, cool
  765. switch (self::getFillTheBlankAnswerType($tabAnswer['tabwords'][$bracketNumber])) {
  766. case self::FILL_THE_BLANK_MENU:
  767. // get the indice of the choosen answer in the menu
  768. // we know that the right answer is the first entry of the menu, ie 0
  769. // (remember, menu entries are shuffled when taking the test)
  770. $tabUserResult[$data['user_id']][$bracketNumber] = self::getFillTheBlankMenuAnswerNum(
  771. $tabAnswer['tabwords'][$bracketNumber],
  772. $tabAnswer['studentanswer'][$bracketNumber]
  773. );
  774. break;
  775. default:
  776. if (self::isGoodStudentAnswer(
  777. $tabAnswer['studentanswer'][$bracketNumber],
  778. $tabAnswer['tabwords'][$bracketNumber]
  779. )
  780. ) {
  781. $tabUserResult[$data['user_id']][$bracketNumber] = 0; // right answer
  782. } else {
  783. $tabUserResult[$data['user_id']][$bracketNumber] = -1; // wrong answer
  784. }
  785. }
  786. } else {
  787. // student didn't answer this bracket
  788. if ($useLastAnsweredAttempt) {
  789. // if we take into account the last answered attempt
  790. if (!isset($tabUserResult[$data['user_id']][$bracketNumber])) {
  791. $tabUserResult[$data['user_id']][$bracketNumber] = -2; // not answered
  792. }
  793. } else {
  794. // we take the last attempt, even if the student answer the question before
  795. $tabUserResult[$data['user_id']][$bracketNumber] = -2; // not answered
  796. }
  797. }
  798. }
  799. }
  800. return $tabUserResult;
  801. }
  802. /**
  803. * Return the number of student that give at leat an answer in the fill the blank test
  804. * @param array $resultList
  805. * @return int
  806. */
  807. public static function getNbResultFillBlankAll($resultList)
  808. {
  809. $outRes = 0;
  810. // for each student in group
  811. foreach ($resultList as $userId => $tabValue) {
  812. $found = false;
  813. // for each bracket, if student has at least one answer ( choice > -2) then he pass the question
  814. foreach ($tabValue as $i => $choice) {
  815. if ($choice > -2 && !$found) {
  816. $outRes++;
  817. $found = true;
  818. }
  819. }
  820. }
  821. return $outRes;
  822. }
  823. /**
  824. * Replace the occurrence of blank word with [correct answer][student answer][answer is correct]
  825. * @param array $listWithStudentAnswer
  826. *
  827. * @return string
  828. */
  829. public static function getAnswerInStudentAttempt($listWithStudentAnswer)
  830. {
  831. $separatorStart = $listWithStudentAnswer['blankseparatorstart'];
  832. $separatorEnd = $listWithStudentAnswer['blankseparatorend'];
  833. // lets rebuild the sentence with [correct answer][student answer][answer is correct]
  834. $result = '';
  835. for ($i=0; $i < count($listWithStudentAnswer['commonwords']) - 1; $i++) {
  836. $result .= $listWithStudentAnswer['commonwords'][$i];
  837. $result .= $listWithStudentAnswer['tabwordsbracket'][$i];
  838. $result .= $separatorStart.$listWithStudentAnswer['studentanswer'][$i].$separatorEnd;
  839. $result .= $separatorStart.$listWithStudentAnswer['studentscore'][$i].$separatorEnd;
  840. }
  841. $result .= $listWithStudentAnswer['commonwords'][$i];
  842. $result .= "::";
  843. // add the system string
  844. $result .= $listWithStudentAnswer['systemstring'];
  845. return $result;
  846. }
  847. /**
  848. * This function is the same than the js one above getBlankSeparatorRegexp
  849. * @param string $inChar
  850. *
  851. * @return string
  852. */
  853. public static function escapeForRegexp($inChar)
  854. {
  855. $listChars = [
  856. ".",
  857. "+",
  858. "*",
  859. "?",
  860. "[",
  861. "^",
  862. "]",
  863. "$",
  864. "(",
  865. ")",
  866. "{",
  867. "}",
  868. "=",
  869. "!",
  870. ">",
  871. "|",
  872. ":",
  873. "-",
  874. ")",
  875. ];
  876. if (in_array($inChar, $listChars)) {
  877. return "\\".$inChar;
  878. } else {
  879. return $inChar;
  880. }
  881. }
  882. /**
  883. * return $text protected for use in regexp
  884. * @param string $text
  885. *
  886. * @return string
  887. */
  888. public static function getRegexpProtected($text)
  889. {
  890. $listRegexpCharacters = [
  891. "/",
  892. ".",
  893. "+",
  894. "*",
  895. "?",
  896. "[",
  897. "^",
  898. "]",
  899. "$",
  900. "(",
  901. ")",
  902. "{",
  903. "}",
  904. "=",
  905. "!",
  906. ">",
  907. "|",
  908. ":",
  909. "-",
  910. ")",
  911. ];
  912. $result = $text;
  913. for ($i=0; $i < count($listRegexpCharacters); $i++) {
  914. $result = str_replace($listRegexpCharacters[$i], "\\".$listRegexpCharacters[$i], $result);
  915. }
  916. return $result;
  917. }
  918. /**
  919. * This function must be the same than the js one getSeparatorFromNumber above
  920. * @return array
  921. */
  922. public static function getAllowedSeparator()
  923. {
  924. $fillBlanksAllowedSeparator = array(
  925. array('[', ']'),
  926. array('{', '}'),
  927. array('(', ')'),
  928. array('*', '*'),
  929. array('#', '#'),
  930. array('%', '%'),
  931. array('$', '$'),
  932. );
  933. return $fillBlanksAllowedSeparator;
  934. }
  935. /**
  936. * return the start separator for answer
  937. * @param string $number
  938. *
  939. * @return string
  940. */
  941. public static function getStartSeparator($number)
  942. {
  943. $listSeparators = self::getAllowedSeparator();
  944. return $listSeparators[$number][0];
  945. }
  946. /**
  947. * return the end separator for answer
  948. * @param string $number
  949. *
  950. * @return string
  951. */
  952. public static function getEndSeparator($number)
  953. {
  954. $listSeparators = self::getAllowedSeparator();
  955. return $listSeparators[$number][1];
  956. }
  957. /**
  958. * Return as a description text, array of allowed separators for question
  959. * eg: array("[...]", "(...)")
  960. * @return array
  961. */
  962. public static function getAllowedSeparatorForSelect()
  963. {
  964. $listResults = array();
  965. $fillBlanksAllowedSeparator = self::getAllowedSeparator();
  966. for ($i=0; $i < count($fillBlanksAllowedSeparator); $i++) {
  967. $listResults[] = $fillBlanksAllowedSeparator[$i][0]."...".$fillBlanksAllowedSeparator[$i][1];
  968. }
  969. return $listResults;
  970. }
  971. /**
  972. * return the code number of the separator for the question
  973. * @param string $startSeparator
  974. * @param string $endSeparator
  975. *
  976. * @return int
  977. */
  978. public function getDefaultSeparatorNumber($startSeparator, $endSeparator)
  979. {
  980. $listSeparators = self::getAllowedSeparator();
  981. $result = 0;
  982. for ($i=0; $i < count($listSeparators); $i++) {
  983. if ($listSeparators[$i][0] == $startSeparator &&
  984. $listSeparators[$i][1] == $endSeparator
  985. ) {
  986. $result = $i;
  987. }
  988. }
  989. return $result;
  990. }
  991. /**
  992. * return the HTML display of the answer
  993. * @param string $answer
  994. * @param int $feedbackType
  995. * @param bool $resultsDisabled
  996. * @param bool $showTotalScoreAndUserChoices
  997. * @return string
  998. */
  999. public static function getHtmlDisplayForAnswer(
  1000. $answer,
  1001. $feedbackType,
  1002. $resultsDisabled = false,
  1003. $showTotalScoreAndUserChoices = false
  1004. ) {
  1005. $result = '';
  1006. $listStudentAnswerInfo = self::getAnswerInfo($answer, true);
  1007. if ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
  1008. if ($showTotalScoreAndUserChoices) {
  1009. $resultsDisabled = false;
  1010. } else {
  1011. $resultsDisabled = true;
  1012. }
  1013. }
  1014. // rebuild the answer with good HTML style
  1015. // this is the student answer, right or wrong
  1016. for ($i=0; $i < count($listStudentAnswerInfo['studentanswer']); $i++) {
  1017. if ($listStudentAnswerInfo['studentscore'][$i] == 1) {
  1018. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlRightAnswer(
  1019. $listStudentAnswerInfo['studentanswer'][$i],
  1020. $listStudentAnswerInfo['tabwords'][$i],
  1021. $feedbackType,
  1022. $resultsDisabled,
  1023. $showTotalScoreAndUserChoices
  1024. );
  1025. } else {
  1026. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlWrongAnswer(
  1027. $listStudentAnswerInfo['studentanswer'][$i],
  1028. $listStudentAnswerInfo['tabwords'][$i],
  1029. $feedbackType,
  1030. $resultsDisabled,
  1031. $showTotalScoreAndUserChoices
  1032. );
  1033. }
  1034. }
  1035. // rebuild the sentence with student answer inserted
  1036. for ($i=0; $i < count($listStudentAnswerInfo['commonwords']); $i++) {
  1037. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  1038. $result .= isset($listStudentAnswerInfo['studentanswer'][$i]) ? $listStudentAnswerInfo['studentanswer'][$i] : '';
  1039. }
  1040. // the last common word (should be </p>)
  1041. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  1042. return $result;
  1043. }
  1044. /**
  1045. * return the HTML code of answer for correct and wrong answer
  1046. * @param string $answer
  1047. * @param string $correct
  1048. * @param string $right
  1049. * @param int $feedbackType
  1050. * @param bool $resultsDisabled
  1051. * @param bool $showTotalScoreAndUserChoices
  1052. * @return string
  1053. */
  1054. public static function getHtmlAnswer(
  1055. $answer,
  1056. $correct,
  1057. $right,
  1058. $feedbackType,
  1059. $resultsDisabled = false,
  1060. $showTotalScoreAndUserChoices = false
  1061. ) {
  1062. $hideExpectedAnswer = false;
  1063. if ($feedbackType == 0 && ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ONLY)) {
  1064. $hideExpectedAnswer = true;
  1065. }
  1066. if ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
  1067. if ($showTotalScoreAndUserChoices) {
  1068. $hideExpectedAnswer = false;
  1069. } else {
  1070. $hideExpectedAnswer = true;
  1071. }
  1072. }
  1073. $style = "color: green";
  1074. if (!$right) {
  1075. $style = "color: red; text-decoration: line-through;";
  1076. }
  1077. $type = self::getFillTheBlankAnswerType($correct);
  1078. switch ($type) {
  1079. case self::FILL_THE_BLANK_MENU:
  1080. $correctAnswerHtml = '';
  1081. $listPossibleAnswers = self::getFillTheBlankMenuAnswers($correct, false);
  1082. $correctAnswerHtml .= "<span style='color: green'>".$listPossibleAnswers[0]."</span>";
  1083. $correctAnswerHtml .= " <span style='font-weight:normal'>(";
  1084. for ($i = 1; $i < count($listPossibleAnswers); $i++) {
  1085. $correctAnswerHtml .= $listPossibleAnswers[$i];
  1086. if ($i != count($listPossibleAnswers) - 1) {
  1087. $correctAnswerHtml .= " | ";
  1088. }
  1089. }
  1090. $correctAnswerHtml .= ")</span>";
  1091. break;
  1092. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  1093. $listCorrects = explode("||", $correct);
  1094. $firstCorrect = $correct;
  1095. if (count($listCorrects) > 0) {
  1096. $firstCorrect = $listCorrects[0];
  1097. }
  1098. $correctAnswerHtml = "<span style='color: green'>".$firstCorrect."</span>";
  1099. break;
  1100. case self::FILL_THE_BLANK_STANDARD:
  1101. default:
  1102. $correctAnswerHtml = "<span style='color: green'>".$correct."</span>";
  1103. }
  1104. if ($hideExpectedAnswer) {
  1105. $correctAnswerHtml = "<span title='".get_lang("ExerciseWithFeedbackWithoutCorrectionComment")."'> - </span>";
  1106. }
  1107. $result = "<span style='border:1px solid black; border-radius:5px; padding:2px; font-weight:bold;'>";
  1108. $result .= "<span style='$style'>".$answer."</span>";
  1109. $result .= "&nbsp;<span style='font-size:120%;'>/</span>&nbsp;";
  1110. $result .= $correctAnswerHtml;
  1111. $result .= "</span>";
  1112. return $result;
  1113. }
  1114. /**
  1115. * return HTML code for correct answer
  1116. * @param string $answer
  1117. * @param string $correct
  1118. * @param bool $resultsDisabled
  1119. *
  1120. * @return string
  1121. */
  1122. public static function getHtmlRightAnswer(
  1123. $answer,
  1124. $correct,
  1125. $feedbackType,
  1126. $resultsDisabled = false,
  1127. $showTotalScoreAndUserChoices = false
  1128. ) {
  1129. return self::getHtmlAnswer(
  1130. $answer,
  1131. $correct,
  1132. true,
  1133. $feedbackType,
  1134. $resultsDisabled,
  1135. $showTotalScoreAndUserChoices
  1136. );
  1137. }
  1138. /**
  1139. * return HTML code for wrong answer
  1140. * @param string $answer
  1141. * @param string $correct
  1142. * @param bool $resultsDisabled
  1143. *
  1144. * @return string
  1145. */
  1146. public static function getHtmlWrongAnswer(
  1147. $answer,
  1148. $correct,
  1149. $feedbackType,
  1150. $resultsDisabled = false,
  1151. $showTotalScoreAndUserChoices = false
  1152. ) {
  1153. return self::getHtmlAnswer(
  1154. $answer,
  1155. $correct,
  1156. false,
  1157. $feedbackType,
  1158. $resultsDisabled,
  1159. $showTotalScoreAndUserChoices
  1160. );
  1161. }
  1162. /**
  1163. * Check if a answer is correct by its text
  1164. * @param string $answerText
  1165. * @return bool
  1166. */
  1167. public static function isCorrect($answerText)
  1168. {
  1169. $answerInfo = self::getAnswerInfo($answerText, true);
  1170. $correctAnswerList = $answerInfo['tabwords'];
  1171. $studentAnswer = $answerInfo['studentanswer'];
  1172. $isCorrect = true;
  1173. foreach ($correctAnswerList as $i => $correctAnswer) {
  1174. $isGoodStudentAnswer = self::isGoodStudentAnswer($studentAnswer[$i], $correctAnswer);
  1175. $isCorrect = $isCorrect && $isGoodStudentAnswer;
  1176. }
  1177. return $isCorrect;
  1178. }
  1179. }