fill_blanks.class.php 54 KB

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