fill_blanks.class.php 51 KB

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