fill_blanks.class.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. * @inheritdoc
  310. */
  311. public function processAnswersCreation($form, $exercise)
  312. {
  313. $answer = $form->getSubmitValue('answer');
  314. // Due the ckeditor transform the elements to their HTML value
  315. //$answer = api_html_entity_decode($answer, ENT_QUOTES, $charset);
  316. //$answer = htmlentities(api_utf8_encode($answer));
  317. // remove the "::" eventually written by the user
  318. $answer = str_replace('::', '', $answer);
  319. // remove starting and ending space and &nbsp;
  320. $answer = api_preg_replace("/\xc2\xa0/", " ", $answer);
  321. // start and end separator
  322. $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
  323. $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
  324. $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
  325. $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
  326. // remove spaces at the beginning and the end of text in square brackets
  327. $answer = preg_replace_callback(
  328. "/".$blankStartSeparatorRegexp."[^]]+".$blankEndSeparatorRegexp."/",
  329. function ($matches) use ($blankStartSeparator, $blankEndSeparator) {
  330. $matchingResult = $matches[0];
  331. $matchingResult = trim($matchingResult, $blankStartSeparator);
  332. $matchingResult = trim($matchingResult, $blankEndSeparator);
  333. $matchingResult = trim($matchingResult);
  334. // remove forbidden chars
  335. $matchingResult = str_replace("/\\/", "", $matchingResult);
  336. $matchingResult = str_replace('/"/', "", $matchingResult);
  337. return $blankStartSeparator.$matchingResult.$blankEndSeparator;
  338. },
  339. $answer
  340. );
  341. // get the blanks weightings
  342. $nb = preg_match_all(
  343. '/'.$blankStartSeparatorRegexp.'[^'.$blankStartSeparatorRegexp.']*'.$blankEndSeparatorRegexp.'/',
  344. $answer,
  345. $blanks
  346. );
  347. if (isset($_GET['editQuestion'])) {
  348. $this->weighting = 0;
  349. }
  350. /* if we have some [tobefound] in the text
  351. build the string to save the following in the answers table
  352. <p>I use a [computer] and a [pen].</p>
  353. becomes
  354. <p>I use a [computer] and a [pen].</p>::100,50:100,50@1
  355. ++++++++-------**
  356. --- -- --- -- -
  357. A B (C) (D)(E)
  358. +++++++ : required, weighting of each words
  359. ------- : optional, input width to display, 200 if not present
  360. ** : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  361. A : weighting for the word [computer]
  362. B : weighting for the word [pen]
  363. C : input width for the word [computer]
  364. D : input width for the word [pen]
  365. E : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  366. */
  367. if ($nb > 0) {
  368. $answer .= '::';
  369. // weighting
  370. for ($i = 0; $i < $nb; ++$i) {
  371. // enter the weighting of word $i
  372. $answer .= $form->getSubmitValue('weighting['.$i.']');
  373. // not the last word, add ","
  374. if ($i != $nb - 1) {
  375. $answer .= ",";
  376. }
  377. // calculate the global weighting for the question
  378. $this -> weighting += $form->getSubmitValue('weighting['.$i.']');
  379. }
  380. // input width
  381. $answer .= ":";
  382. for ($i = 0; $i < $nb; ++$i) {
  383. // enter the width of input for word $i
  384. $answer .= $form->getSubmitValue('sizeofinput['.$i.']');
  385. // not the last word, add ","
  386. if ($i != $nb - 1) {
  387. $answer .= ",";
  388. }
  389. }
  390. }
  391. // write the blank separator code number
  392. // see function getAllowedSeparator
  393. /*
  394. 0 [...]
  395. 1 {...}
  396. 2 (...)
  397. 3 *...*
  398. 4 #...#
  399. 5 %...%
  400. 6 $...$
  401. */
  402. $answer .= ":".$form->getSubmitValue('select_separator');
  403. // Allow answers order switches
  404. $is_multiple = $form -> getSubmitValue('multiple_answer');
  405. $answer .= '@'.$is_multiple;
  406. $this->save($exercise);
  407. $objAnswer = new Answer($this->id);
  408. $objAnswer->createAnswer($answer, 0, '', 0, 1);
  409. $objAnswer->save();
  410. }
  411. /**
  412. * @inheritdoc
  413. */
  414. public function return_header($exercise, $counter = null, $score = null)
  415. {
  416. $header = parent::return_header($exercise, $counter, $score);
  417. $header .= '<table class="'.$this->question_table_class.'">
  418. <tr>
  419. <th>'.get_lang("Answer").'</th>
  420. </tr>';
  421. return $header;
  422. }
  423. /**
  424. * @param int $currentQuestion
  425. * @param int $questionId
  426. * @param string $correctItem
  427. * @param array $attributes
  428. * @param string $answer
  429. * @param array $listAnswersInfo
  430. * @param boolean $displayForStudent
  431. * @param int $inBlankNumber
  432. * @return string
  433. */
  434. public static function getFillTheBlankHtml(
  435. $currentQuestion,
  436. $questionId,
  437. $correctItem,
  438. $attributes,
  439. $answer,
  440. $listAnswersInfo,
  441. $displayForStudent,
  442. $inBlankNumber
  443. ) {
  444. $inTabTeacherSolution = $listAnswersInfo['tabwords'];
  445. $inTeacherSolution = $inTabTeacherSolution[$inBlankNumber];
  446. switch (self::getFillTheBlankAnswerType($inTeacherSolution)) {
  447. case self::FILL_THE_BLANK_MENU:
  448. $selected = '';
  449. // the blank menu
  450. // display a menu from answer separated with |
  451. // if display for student, shuffle the correct answer menu
  452. $listMenu = self::getFillTheBlankMenuAnswers(
  453. $inTeacherSolution,
  454. $displayForStudent
  455. );
  456. $resultOptions = ['' => '--'];
  457. foreach ($listMenu as $item) {
  458. $item = self::trimOption($item);
  459. $resultOptions[$item] = $item;
  460. }
  461. for ($k = 0; $k < count($listMenu); $k++) {
  462. if ($correctItem == $listMenu[$k]) {
  463. $selected = $k;
  464. break;
  465. }
  466. // if in teacher view, display the first item by default, which is the right answer
  467. if ($k == 0 && !$displayForStudent) {
  468. $selected = $k;
  469. break;
  470. }
  471. }
  472. $result = Display::select(
  473. "choice[$questionId][]",
  474. $resultOptions,
  475. $selected,
  476. ['class' => 'selectpicker'],
  477. false
  478. );
  479. break;
  480. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  481. //no break
  482. case self::FILL_THE_BLANK_STANDARD:
  483. default:
  484. $attributes['id'] = 'choice_id_'.$currentQuestion.'_'.$inBlankNumber;
  485. $result = Display::input(
  486. 'text',
  487. "choice[$questionId][]",
  488. $correctItem,
  489. $attributes
  490. );
  491. break;
  492. }
  493. return $result;
  494. }
  495. private static function trimOption($text)
  496. {
  497. $converted = strtr($text, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
  498. $trimmed = trim($converted, chr(0xC2).chr(0xA0).' ');
  499. return $trimmed;
  500. }
  501. /**
  502. * Return an array with the different choices available
  503. * when the answers between bracket show as a menu
  504. * @param string $correctAnswer
  505. * @param bool $displayForStudent true if we want to shuffle the choices of the menu for students
  506. *
  507. * @return array
  508. */
  509. public static function getFillTheBlankMenuAnswers($correctAnswer, $displayForStudent)
  510. {
  511. $list = api_preg_split("/\|/", $correctAnswer);
  512. if ($displayForStudent) {
  513. shuffle($list);
  514. }
  515. return $list;
  516. }
  517. /**
  518. * Return the array index of the student answer
  519. * @param string $correctAnswer the menu Choice1|Choice2|Choice3
  520. * @param string $studentAnswer the student answer must be Choice1 or Choice2 or Choice3
  521. *
  522. * @return int in the example 0 1 or 2 depending of the choice of the student
  523. */
  524. public static function getFillTheBlankMenuAnswerNum($correctAnswer, $studentAnswer)
  525. {
  526. $listChoices = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  527. foreach ($listChoices as $num => $value) {
  528. if ($value == $studentAnswer) {
  529. return $num;
  530. }
  531. }
  532. // should not happened, because student choose the answer in a menu of possible answers
  533. return -1;
  534. }
  535. /**
  536. * Return the possible answer if the answer between brackets is a multiple choice menu
  537. * @param string $correctAnswer
  538. *
  539. * @return array
  540. */
  541. public static function getFillTheBlankSeveralAnswers($correctAnswer)
  542. {
  543. // is answer||Answer||response||Response , mean answer or Answer ...
  544. $listSeveral = api_preg_split("/\|\|/", $correctAnswer);
  545. return $listSeveral;
  546. }
  547. /**
  548. * Return true if student answer is right according to the correctAnswer
  549. * it is not as simple as equality, because of the type of Fill The Blank question
  550. * eg : studentAnswer = 'Un' and correctAnswer = 'Un||1||un'
  551. * @param string $studentAnswer [studentanswer] of the info array of the answer field
  552. * @param string $correctAnswer [tabwords] of the info array of the answer field
  553. *
  554. * @return bool
  555. */
  556. public static function isGoodStudentAnswer($studentAnswer, $correctAnswer)
  557. {
  558. switch (self::getFillTheBlankAnswerType($correctAnswer)) {
  559. case self::FILL_THE_BLANK_MENU:
  560. $listMenu = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  561. $result = self::trimOption($listMenu[0]) == $studentAnswer;
  562. break;
  563. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  564. // the answer must be one of the choice made
  565. $listSeveral = self::getFillTheBlankSeveralAnswers($correctAnswer);
  566. $listSeveral = array_map(function($item) {
  567. return self::trimOption($item);
  568. }, $listSeveral);
  569. $result = in_array($studentAnswer, $listSeveral);
  570. break;
  571. case self::FILL_THE_BLANK_STANDARD:
  572. default:
  573. $result = $studentAnswer == self::trimOption($correctAnswer);
  574. break;
  575. }
  576. return $result;
  577. }
  578. /**
  579. * @param string $correctAnswer
  580. *
  581. * @return int
  582. */
  583. public static function getFillTheBlankAnswerType($correctAnswer)
  584. {
  585. if (api_strpos($correctAnswer, "|") && !api_strpos($correctAnswer, "||")) {
  586. return self::FILL_THE_BLANK_MENU;
  587. } elseif (api_strpos($correctAnswer, "||")) {
  588. return self::FILL_THE_BLANK_SEVERAL_ANSWER;
  589. } else {
  590. return self::FILL_THE_BLANK_STANDARD;
  591. }
  592. }
  593. /**
  594. * Return information about the answer
  595. * @param string $userAnswer the text of the answer of the question
  596. * @param bool $isStudentAnswer true if it's a student answer false the empty question model
  597. *
  598. * @return array of information about the answer
  599. */
  600. public static function getAnswerInfo($userAnswer = "", $isStudentAnswer = false)
  601. {
  602. $listAnswerResults = array();
  603. $listAnswerResults['text'] = '';
  604. $listAnswerResults['wordsCount'] = 0;
  605. $listAnswerResults['tabwordsbracket'] = array();
  606. $listAnswerResults['tabwords'] = array();
  607. $listAnswerResults['tabweighting'] = array();
  608. $listAnswerResults['tabinputsize'] = array();
  609. $listAnswerResults['switchable'] = '';
  610. $listAnswerResults['studentanswer'] = array();
  611. $listAnswerResults['studentscore'] = array();
  612. $listAnswerResults['blankseparatornumber'] = 0;
  613. $listDoubleColon = array();
  614. api_preg_match("/(.*)::(.*)$/s", $userAnswer, $listResult);
  615. if (count($listResult) < 2) {
  616. $listDoubleColon[] = '';
  617. $listDoubleColon[] = '';
  618. } else {
  619. $listDoubleColon[] = $listResult[1];
  620. $listDoubleColon[] = $listResult[2];
  621. }
  622. $listAnswerResults['systemstring'] = $listDoubleColon[1];
  623. // make sure we only take the last bit to find special marks
  624. $listArobaseSplit = explode('@', $listDoubleColon[1]);
  625. if (count($listArobaseSplit) < 2) {
  626. $listArobaseSplit[1] = '';
  627. }
  628. // take the complete string except after the last '::'
  629. $listDetails = explode(":", $listArobaseSplit[0]);
  630. // < number of item after the ::[score]:[size]:[separator_id]@ , here there are 3
  631. if (count($listDetails) < 3) {
  632. $listWeightings = explode(',', $listDetails[0]);
  633. $listSizeOfInput = array();
  634. for ($i = 0; $i < count($listWeightings); $i++) {
  635. $listSizeOfInput[] = 200;
  636. }
  637. $blankSeparatorNumber = 0; // 0 is [...]
  638. } else {
  639. $listWeightings = explode(',', $listDetails[0]);
  640. $listSizeOfInput = explode(',', $listDetails[1]);
  641. $blankSeparatorNumber = $listDetails[2];
  642. }
  643. $listAnswerResults['text'] = $listDoubleColon[0];
  644. $listAnswerResults['tabweighting'] = $listWeightings;
  645. $listAnswerResults['tabinputsize'] = $listSizeOfInput;
  646. $listAnswerResults['switchable'] = $listArobaseSplit[1];
  647. $listAnswerResults['blankseparatorstart'] = self::getStartSeparator($blankSeparatorNumber);
  648. $listAnswerResults['blankseparatorend'] = self::getEndSeparator($blankSeparatorNumber);
  649. $listAnswerResults['blankseparatornumber'] = $blankSeparatorNumber;
  650. $blankCharStart = self::getStartSeparator($blankSeparatorNumber);
  651. $blankCharEnd = self::getEndSeparator($blankSeparatorNumber);
  652. $blankCharStartForRegexp = self::escapeForRegexp($blankCharStart);
  653. $blankCharEndForRegexp = self::escapeForRegexp($blankCharEnd);
  654. // get all blanks words
  655. $listAnswerResults['wordsCount'] = api_preg_match_all(
  656. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  657. $listDoubleColon[0],
  658. $listWords
  659. );
  660. if ($listAnswerResults['wordsCount'] > 0) {
  661. $listAnswerResults['tabwordsbracket'] = $listWords[0];
  662. // remove [ and ] in string
  663. array_walk(
  664. $listWords[0],
  665. function (&$value, $key, $tabBlankChar) {
  666. $trimChars = '';
  667. for ($i = 0; $i < count($tabBlankChar); $i++) {
  668. $trimChars .= $tabBlankChar[$i];
  669. }
  670. $value = trim($value, $trimChars);
  671. },
  672. array($blankCharStart, $blankCharEnd)
  673. );
  674. $listAnswerResults['tabwords'] = $listWords[0];
  675. }
  676. // get all common words
  677. $commonWords = api_preg_replace(
  678. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  679. "::",
  680. $listDoubleColon[0]
  681. );
  682. // if student answer, the second [] is the student answer,
  683. // the third is if student scored or not
  684. $listBrackets = array();
  685. $listWords = array();
  686. if ($isStudentAnswer) {
  687. for ($i = 0; $i < count($listAnswerResults['tabwords']); $i++) {
  688. $listBrackets[] = $listAnswerResults['tabwordsbracket'][$i];
  689. $listWords[] = $listAnswerResults['tabwords'][$i];
  690. if ($i + 1 < count($listAnswerResults['tabwords'])) {
  691. // should always be
  692. $i++;
  693. }
  694. $listAnswerResults['studentanswer'][] = $listAnswerResults['tabwords'][$i];
  695. if ($i + 1 < count($listAnswerResults['tabwords'])) {
  696. // should always be
  697. $i++;
  698. }
  699. $listAnswerResults['studentscore'][] = $listAnswerResults['tabwords'][$i];
  700. }
  701. $listAnswerResults['tabwords'] = $listWords;
  702. $listAnswerResults['tabwordsbracket'] = $listBrackets;
  703. // if we are in student view, we've got 3 times :::::: for common words
  704. $commonWords = api_preg_replace("/::::::/", "::", $commonWords);
  705. }
  706. $listAnswerResults['commonwords'] = explode("::", $commonWords);
  707. return $listAnswerResults;
  708. }
  709. /**
  710. * Return an array of student state answers for fill the blank questions
  711. * for each students that answered the question
  712. * -2 : didn't answer
  713. * -1 : student answer is wrong
  714. * 0 : student answer is correct
  715. * >0 : for fill the blank question with choice menu, is the index of the student answer (right answer indice is 0)
  716. *
  717. * @param integer $testId
  718. * @param integer $questionId
  719. * @param $studentsIdList
  720. * @param string $startDate
  721. * @param string $endDate
  722. * @param bool $useLastAnsweredAttempt
  723. * @return array
  724. * (
  725. * [student_id] => Array
  726. * (
  727. * [first fill the blank for question] => -1
  728. * [second fill the blank for question] => 2
  729. * [third fill the blank for question] => -1
  730. * )
  731. * )
  732. */
  733. public static function getFillTheBlankTabResult(
  734. $testId,
  735. $questionId,
  736. $studentsIdList,
  737. $startDate,
  738. $endDate,
  739. $useLastAnsweredAttempt = true
  740. ) {
  741. $tblTrackEAttempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  742. $tblTrackEExercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  743. $courseId = api_get_course_int_id();
  744. // If no user has answered questions, no need to go further. Return empty array.
  745. if (empty($studentsIdList)) {
  746. return array();
  747. }
  748. // request to have all the answers of student for this question
  749. // student may have doing it several time
  750. // student may have not answered the bracket id, in this case, is result of the answer is empty
  751. // we got the less recent attempt first
  752. $sql = 'SELECT * FROM '.$tblTrackEAttempt.' tea
  753. LEFT JOIN '.$tblTrackEExercise.' tee
  754. ON
  755. tee.exe_id = tea.exe_id AND
  756. tea.c_id = '.$courseId.' AND
  757. exe_exo_id = '.$testId.'
  758. WHERE
  759. tee.c_id = '.$courseId.' AND
  760. question_id = '.$questionId.' AND
  761. tea.user_id IN ('.implode(',', $studentsIdList).') AND
  762. tea.tms >= "'.$startDate.'" AND
  763. tea.tms <= "'.$endDate.'"
  764. ORDER BY user_id, tea.exe_id;
  765. ';
  766. $res = Database::query($sql);
  767. $tabUserResult = array();
  768. // foreach attempts for all students starting with his older attempt
  769. while ($data = Database::fetch_array($res)) {
  770. $tabAnswer = self::getAnswerInfo($data['answer'], true);
  771. // for each bracket to find in this question
  772. foreach ($tabAnswer['studentanswer'] as $bracketNumber => $studentAnswer) {
  773. if ($tabAnswer['studentanswer'][$bracketNumber] != '') {
  774. // student has answered this bracket, cool
  775. switch (self::getFillTheBlankAnswerType($tabAnswer['tabwords'][$bracketNumber])) {
  776. case self::FILL_THE_BLANK_MENU:
  777. // get the indice of the choosen answer in the menu
  778. // we know that the right answer is the first entry of the menu, ie 0
  779. // (remember, menu entries are shuffled when taking the test)
  780. $tabUserResult[$data['user_id']][$bracketNumber] = self::getFillTheBlankMenuAnswerNum(
  781. $tabAnswer['tabwords'][$bracketNumber],
  782. $tabAnswer['studentanswer'][$bracketNumber]
  783. );
  784. break;
  785. default:
  786. if (self::isGoodStudentAnswer(
  787. $tabAnswer['studentanswer'][$bracketNumber],
  788. $tabAnswer['tabwords'][$bracketNumber]
  789. )
  790. ) {
  791. $tabUserResult[$data['user_id']][$bracketNumber] = 0; // right answer
  792. } else {
  793. $tabUserResult[$data['user_id']][$bracketNumber] = -1; // wrong answer
  794. }
  795. }
  796. } else {
  797. // student didn't answer this bracket
  798. if ($useLastAnsweredAttempt) {
  799. // if we take into account the last answered attempt
  800. if (!isset($tabUserResult[$data['user_id']][$bracketNumber])) {
  801. $tabUserResult[$data['user_id']][$bracketNumber] = -2; // not answered
  802. }
  803. } else {
  804. // we take the last attempt, even if the student answer the question before
  805. $tabUserResult[$data['user_id']][$bracketNumber] = -2; // not answered
  806. }
  807. }
  808. }
  809. }
  810. return $tabUserResult;
  811. }
  812. /**
  813. * Return the number of student that give at leat an answer in the fill the blank test
  814. * @param array $resultList
  815. * @return int
  816. */
  817. public static function getNbResultFillBlankAll($resultList)
  818. {
  819. $outRes = 0;
  820. // for each student in group
  821. foreach ($resultList as $userId => $tabValue) {
  822. $found = false;
  823. // for each bracket, if student has at least one answer ( choice > -2) then he pass the question
  824. foreach ($tabValue as $i => $choice) {
  825. if ($choice > -2 && !$found) {
  826. $outRes++;
  827. $found = true;
  828. }
  829. }
  830. }
  831. return $outRes;
  832. }
  833. /**
  834. * Replace the occurrence of blank word with [correct answer][student answer][answer is correct]
  835. * @param array $listWithStudentAnswer
  836. *
  837. * @return string
  838. */
  839. public static function getAnswerInStudentAttempt($listWithStudentAnswer)
  840. {
  841. $separatorStart = $listWithStudentAnswer['blankseparatorstart'];
  842. $separatorEnd = $listWithStudentAnswer['blankseparatorend'];
  843. // lets rebuild the sentence with [correct answer][student answer][answer is correct]
  844. $result = '';
  845. for ($i = 0; $i < count($listWithStudentAnswer['commonwords']) - 1; $i++) {
  846. $result .= $listWithStudentAnswer['commonwords'][$i];
  847. $result .= $listWithStudentAnswer['tabwordsbracket'][$i];
  848. $result .= $separatorStart.$listWithStudentAnswer['studentanswer'][$i].$separatorEnd;
  849. $result .= $separatorStart.$listWithStudentAnswer['studentscore'][$i].$separatorEnd;
  850. }
  851. $result .= $listWithStudentAnswer['commonwords'][$i];
  852. $result .= "::";
  853. // add the system string
  854. $result .= $listWithStudentAnswer['systemstring'];
  855. return $result;
  856. }
  857. /**
  858. * This function is the same than the js one above getBlankSeparatorRegexp
  859. * @param string $inChar
  860. *
  861. * @return string
  862. */
  863. public static function escapeForRegexp($inChar)
  864. {
  865. $listChars = [
  866. ".",
  867. "+",
  868. "*",
  869. "?",
  870. "[",
  871. "^",
  872. "]",
  873. "$",
  874. "(",
  875. ")",
  876. "{",
  877. "}",
  878. "=",
  879. "!",
  880. ">",
  881. "|",
  882. ":",
  883. "-",
  884. ")",
  885. ];
  886. if (in_array($inChar, $listChars)) {
  887. return "\\".$inChar;
  888. } else {
  889. return $inChar;
  890. }
  891. }
  892. /**
  893. * return $text protected for use in regexp
  894. * @param string $text
  895. *
  896. * @return string
  897. */
  898. public static function getRegexpProtected($text)
  899. {
  900. $listRegexpCharacters = [
  901. "/",
  902. ".",
  903. "+",
  904. "*",
  905. "?",
  906. "[",
  907. "^",
  908. "]",
  909. "$",
  910. "(",
  911. ")",
  912. "{",
  913. "}",
  914. "=",
  915. "!",
  916. ">",
  917. "|",
  918. ":",
  919. "-",
  920. ")",
  921. ];
  922. $result = $text;
  923. for ($i = 0; $i < count($listRegexpCharacters); $i++) {
  924. $result = str_replace($listRegexpCharacters[$i], "\\".$listRegexpCharacters[$i], $result);
  925. }
  926. return $result;
  927. }
  928. /**
  929. * This function must be the same than the js one getSeparatorFromNumber above
  930. * @return array
  931. */
  932. public static function getAllowedSeparator()
  933. {
  934. $fillBlanksAllowedSeparator = array(
  935. array('[', ']'),
  936. array('{', '}'),
  937. array('(', ')'),
  938. array('*', '*'),
  939. array('#', '#'),
  940. array('%', '%'),
  941. array('$', '$'),
  942. );
  943. return $fillBlanksAllowedSeparator;
  944. }
  945. /**
  946. * return the start separator for answer
  947. * @param string $number
  948. *
  949. * @return string
  950. */
  951. public static function getStartSeparator($number)
  952. {
  953. $listSeparators = self::getAllowedSeparator();
  954. return $listSeparators[$number][0];
  955. }
  956. /**
  957. * return the end separator for answer
  958. * @param string $number
  959. *
  960. * @return string
  961. */
  962. public static function getEndSeparator($number)
  963. {
  964. $listSeparators = self::getAllowedSeparator();
  965. return $listSeparators[$number][1];
  966. }
  967. /**
  968. * Return as a description text, array of allowed separators for question
  969. * eg: array("[...]", "(...)")
  970. * @return array
  971. */
  972. public static function getAllowedSeparatorForSelect()
  973. {
  974. $listResults = array();
  975. $fillBlanksAllowedSeparator = self::getAllowedSeparator();
  976. for ($i = 0; $i < count($fillBlanksAllowedSeparator); $i++) {
  977. $listResults[] = $fillBlanksAllowedSeparator[$i][0]."...".$fillBlanksAllowedSeparator[$i][1];
  978. }
  979. return $listResults;
  980. }
  981. /**
  982. * return the code number of the separator for the question
  983. * @param string $startSeparator
  984. * @param string $endSeparator
  985. *
  986. * @return int
  987. */
  988. public function getDefaultSeparatorNumber($startSeparator, $endSeparator)
  989. {
  990. $listSeparators = self::getAllowedSeparator();
  991. $result = 0;
  992. for ($i = 0; $i < count($listSeparators); $i++) {
  993. if ($listSeparators[$i][0] == $startSeparator &&
  994. $listSeparators[$i][1] == $endSeparator
  995. ) {
  996. $result = $i;
  997. }
  998. }
  999. return $result;
  1000. }
  1001. /**
  1002. * return the HTML display of the answer
  1003. * @param string $answer
  1004. * @param int $feedbackType
  1005. * @param bool $resultsDisabled
  1006. * @param bool $showTotalScoreAndUserChoices
  1007. * @return string
  1008. */
  1009. public static function getHtmlDisplayForAnswer(
  1010. $answer,
  1011. $feedbackType,
  1012. $resultsDisabled = false,
  1013. $showTotalScoreAndUserChoices = false
  1014. ) {
  1015. $result = '';
  1016. $listStudentAnswerInfo = self::getAnswerInfo($answer, true);
  1017. if ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
  1018. if ($showTotalScoreAndUserChoices) {
  1019. $resultsDisabled = false;
  1020. } else {
  1021. $resultsDisabled = true;
  1022. }
  1023. }
  1024. // rebuild the answer with good HTML style
  1025. // this is the student answer, right or wrong
  1026. for ($i = 0; $i < count($listStudentAnswerInfo['studentanswer']); $i++) {
  1027. if ($listStudentAnswerInfo['studentscore'][$i] == 1) {
  1028. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlRightAnswer(
  1029. $listStudentAnswerInfo['studentanswer'][$i],
  1030. $listStudentAnswerInfo['tabwords'][$i],
  1031. $feedbackType,
  1032. $resultsDisabled,
  1033. $showTotalScoreAndUserChoices
  1034. );
  1035. } else {
  1036. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlWrongAnswer(
  1037. $listStudentAnswerInfo['studentanswer'][$i],
  1038. $listStudentAnswerInfo['tabwords'][$i],
  1039. $feedbackType,
  1040. $resultsDisabled,
  1041. $showTotalScoreAndUserChoices
  1042. );
  1043. }
  1044. }
  1045. // rebuild the sentence with student answer inserted
  1046. for ($i = 0; $i < count($listStudentAnswerInfo['commonwords']); $i++) {
  1047. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  1048. $result .= isset($listStudentAnswerInfo['studentanswer'][$i]) ? $listStudentAnswerInfo['studentanswer'][$i] : '';
  1049. }
  1050. // the last common word (should be </p>)
  1051. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  1052. return $result;
  1053. }
  1054. /**
  1055. * return the HTML code of answer for correct and wrong answer
  1056. * @param string $answer
  1057. * @param string $correct
  1058. * @param string $right
  1059. * @param int $feedbackType
  1060. * @param bool $resultsDisabled
  1061. * @param bool $showTotalScoreAndUserChoices
  1062. * @return string
  1063. */
  1064. public static function getHtmlAnswer(
  1065. $answer,
  1066. $correct,
  1067. $right,
  1068. $feedbackType,
  1069. $resultsDisabled = false,
  1070. $showTotalScoreAndUserChoices = false
  1071. ) {
  1072. $hideExpectedAnswer = false;
  1073. if ($feedbackType == 0 && ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ONLY)) {
  1074. $hideExpectedAnswer = true;
  1075. }
  1076. if ($resultsDisabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
  1077. if ($showTotalScoreAndUserChoices) {
  1078. $hideExpectedAnswer = false;
  1079. } else {
  1080. $hideExpectedAnswer = true;
  1081. }
  1082. }
  1083. $style = "color: green";
  1084. if (!$right) {
  1085. $style = "color: red; text-decoration: line-through;";
  1086. }
  1087. $type = self::getFillTheBlankAnswerType($correct);
  1088. switch ($type) {
  1089. case self::FILL_THE_BLANK_MENU:
  1090. $correctAnswerHtml = '';
  1091. $listPossibleAnswers = self::getFillTheBlankMenuAnswers($correct, false);
  1092. $correctAnswerHtml .= "<span style='color: green'>".$listPossibleAnswers[0]."</span>";
  1093. $correctAnswerHtml .= " <span style='font-weight:normal'>(";
  1094. for ($i = 1; $i < count($listPossibleAnswers); $i++) {
  1095. $correctAnswerHtml .= $listPossibleAnswers[$i];
  1096. if ($i != count($listPossibleAnswers) - 1) {
  1097. $correctAnswerHtml .= " | ";
  1098. }
  1099. }
  1100. $correctAnswerHtml .= ")</span>";
  1101. break;
  1102. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  1103. $listCorrects = explode("||", $correct);
  1104. $firstCorrect = $correct;
  1105. if (count($listCorrects) > 0) {
  1106. $firstCorrect = $listCorrects[0];
  1107. }
  1108. $correctAnswerHtml = "<span style='color: green'>".$firstCorrect."</span>";
  1109. break;
  1110. case self::FILL_THE_BLANK_STANDARD:
  1111. default:
  1112. $correctAnswerHtml = "<span style='color: green'>".$correct."</span>";
  1113. }
  1114. if ($hideExpectedAnswer) {
  1115. $correctAnswerHtml = "<span title='".get_lang("ExerciseWithFeedbackWithoutCorrectionComment")."'> - </span>";
  1116. }
  1117. $result = "<span style='border:1px solid black; border-radius:5px; padding:2px; font-weight:bold;'>";
  1118. $result .= "<span style='$style'>".$answer."</span>";
  1119. $result .= "&nbsp;<span style='font-size:120%;'>/</span>&nbsp;";
  1120. $result .= $correctAnswerHtml;
  1121. $result .= "</span>";
  1122. return $result;
  1123. }
  1124. /**
  1125. * return HTML code for correct answer
  1126. * @param string $answer
  1127. * @param string $correct
  1128. * @param bool $resultsDisabled
  1129. *
  1130. * @return string
  1131. */
  1132. public static function getHtmlRightAnswer(
  1133. $answer,
  1134. $correct,
  1135. $feedbackType,
  1136. $resultsDisabled = false,
  1137. $showTotalScoreAndUserChoices = false
  1138. ) {
  1139. return self::getHtmlAnswer(
  1140. $answer,
  1141. $correct,
  1142. true,
  1143. $feedbackType,
  1144. $resultsDisabled,
  1145. $showTotalScoreAndUserChoices
  1146. );
  1147. }
  1148. /**
  1149. * return HTML code for wrong answer
  1150. * @param string $answer
  1151. * @param string $correct
  1152. * @param bool $resultsDisabled
  1153. *
  1154. * @return string
  1155. */
  1156. public static function getHtmlWrongAnswer(
  1157. $answer,
  1158. $correct,
  1159. $feedbackType,
  1160. $resultsDisabled = false,
  1161. $showTotalScoreAndUserChoices = false
  1162. ) {
  1163. return self::getHtmlAnswer(
  1164. $answer,
  1165. $correct,
  1166. false,
  1167. $feedbackType,
  1168. $resultsDisabled,
  1169. $showTotalScoreAndUserChoices
  1170. );
  1171. }
  1172. /**
  1173. * Check if a answer is correct by its text
  1174. * @param string $answerText
  1175. * @return bool
  1176. */
  1177. public static function isCorrect($answerText)
  1178. {
  1179. $answerInfo = self::getAnswerInfo($answerText, true);
  1180. $correctAnswerList = $answerInfo['tabwords'];
  1181. $studentAnswer = $answerInfo['studentanswer'];
  1182. $isCorrect = true;
  1183. foreach ($correctAnswerList as $i => $correctAnswer) {
  1184. $isGoodStudentAnswer = self::isGoodStudentAnswer($studentAnswer[$i], $correctAnswer);
  1185. $isCorrect = $isCorrect && $isGoodStudentAnswer;
  1186. }
  1187. return $isCorrect;
  1188. }
  1189. /**
  1190. * Clear the answer entered by student
  1191. * @param string $answer
  1192. * @return string
  1193. */
  1194. public static function clearStudentAnswer($answer)
  1195. {
  1196. $answer = htmlentities(api_utf8_encode($answer), ENT_QUOTES);
  1197. $answer = str_replace('&#039;', '&#39;', $answer); // fix apostrophe
  1198. $answer = api_preg_replace('/\s\s+/', ' ', $answer); // replace excess white spaces
  1199. $answer = strtr($answer, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
  1200. return trim($answer);
  1201. }
  1202. }