fill_blanks.class.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. static $typePicture = 'fill_in_blanks.png';
  13. 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. * function which redefines Question::createAnswersForm
  28. * @param FormValidator $form
  29. */
  30. public function createAnswersForm($form)
  31. {
  32. $defaults = array();
  33. if (!empty($this->id)) {
  34. $objectAnswer = new Answer($this->id);
  35. $answer = $objectAnswer->selectAnswer(1);
  36. $listAnswersInfo = FillBlanks::getAnswerInfo($answer);
  37. if ($listAnswersInfo["switchable"]) {
  38. $defaults['multiple_answer'] = 1;
  39. } else {
  40. $defaults['multiple_answer'] = 0;
  41. }
  42. //take the complete string except after the last '::'
  43. $defaults['answer'] = $listAnswersInfo["text"];
  44. $defaults['select_separator'] = $listAnswersInfo["blankseparatornumber"];
  45. $blanksepartornumber = $listAnswersInfo["blankseparatornumber"];
  46. } else {
  47. $defaults['answer'] = get_lang('DefaultTextInBlanks');
  48. $defaults['select_separator'] = 0;
  49. $blanksepartornumber = 0;
  50. }
  51. $blankSeparatorStart = self::getStartSeparator($blanksepartornumber);
  52. $blankSeparatorEnd = self::getEndSeparator($blanksepartornumber);
  53. $setValues = null;
  54. if (isset($a_weightings) && count($a_weightings) > 0) {
  55. foreach ($a_weightings as $i => $weighting) {
  56. $setValues .= 'document.getElementById("weighting['.$i.']").value = "'.$weighting.'";';
  57. }
  58. }
  59. // javascript
  60. echo '<script>
  61. var blankSeparatortStart = "'.$blankSeparatorStart.'";
  62. var blankSeparatortEnd = "'.$blankSeparatorEnd.'";
  63. var blankSeparatortStartRegexp = getBlankSeparatorRegexp(blankSeparatortStart);
  64. var blankSeparatortEndRegexp = getBlankSeparatorRegexp(blankSeparatortEnd);
  65. CKEDITOR.on("instanceCreated", function(e) {
  66. if (e.editor.name === "answer") {
  67. e.editor.on("change", updateBlanks);
  68. }
  69. });
  70. var firstTime = true;
  71. function updateBlanks()
  72. {
  73. if (firstTime) {
  74. var field = document.getElementById("answer");
  75. var answer = field.value;
  76. } else {
  77. var answer = CKEDITOR.instances["answer"].getData();
  78. }
  79. // disable the save button, if not blanks have been created
  80. $("button").attr("disabled", "disabled");
  81. $("#defineoneblank").show();
  82. var blanksRegexp = "/"+blankSeparatortStartRegexp+"[^"+blankSeparatortStartRegexp+"]*"+blankSeparatortEndRegexp+"/g";
  83. var blanks = answer.match(eval(blanksRegexp));
  84. var fields = "<div class=\"form-group \">";
  85. fields += "<label class=\"col-sm-2 control-label\">'.get_lang('Weighting').'</label>";
  86. fields += "<div class=\"col-sm-8\">";
  87. fields += "<table>";
  88. 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>";
  89. if (blanks != null) {
  90. for (var i=0 ; i < blanks.length ; i++){
  91. // remove forbidden characters that causes bugs
  92. blanks[i] = removeForbiddenChars(blanks[i]);
  93. // trim blanks between brackets
  94. blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatortStart, blankSeparatortEnd);
  95. // if the word is empty []
  96. if (blanks[i] == blankSeparatortStartRegexp+blankSeparatortEndRegexp) {
  97. break;
  98. }
  99. // get input size
  100. var lainputsize = 200;
  101. if ($("#samplesize\\\["+i+"\\\]").width()) {
  102. lainputsize = $("#samplesize\\\["+i+"\\\]").width();
  103. }
  104. if (document.getElementById("weighting["+i+"]")) {
  105. var value = document.getElementById("weighting["+i+"]").value;
  106. } else {
  107. var value = "10";
  108. }
  109. fields += "<tr>";
  110. fields += "<td>"+blanks[i]+"</td>";
  111. fields += "<td><input style=\"width:35px\" value=\""+value+"\" type=\"text\" id=\"weighting["+i+"]\" name=\"weighting["+i+"]\" /></td>";
  112. fields += "<td>";
  113. fields += "<input type=\"button\" value=\"-\" onclick=\"changeInputSize(-1, "+i+")\">";
  114. fields += "<input type=\"button\" value=\"+\" onclick=\"changeInputSize(1, "+i+")\">";
  115. fields += "<input value=\""+blanks[i].substr(1, blanks[i].length - 2)+"\" style=\"width:"+lainputsize+"px\" disabled=disabled id=\"samplesize["+i+"]\"/>";
  116. fields += "<input type=\"hidden\" id=\"sizeofinput["+i+"]\" name=\"sizeofinput["+i+"]\" value=\""+lainputsize+"\" \"/>";
  117. fields += "</td>";
  118. fields += "</tr>";
  119. // enable the save button
  120. $("button").removeAttr("disabled");
  121. $("#defineoneblank").hide();
  122. }
  123. }
  124. document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>";
  125. if (firstTime) {
  126. firstTime = false;
  127. ';
  128. if (isset($listAnswersInfo) && count($listAnswersInfo["tabweighting"]) > 0) {
  129. foreach ($listAnswersInfo["tabweighting"] as $i => $weighting) {
  130. if (!empty($i)) {
  131. echo 'document.getElementById("weighting['.$i.']").value = "'.$weighting.'";';
  132. }
  133. }
  134. foreach ($listAnswersInfo["tabinputsize"] as $i => $sizeOfInput) {
  135. if (!empty($i)) {
  136. echo 'document.getElementById("sizeofinput['.$i.']").value = "'.$sizeOfInput.'";';
  137. echo '$("#samplesize\\\['.$i.'\\\]").width('.$sizeOfInput.');';
  138. }
  139. }
  140. }
  141. echo '}
  142. }
  143. window.onload = updateBlanks;
  144. function getInputSize() {
  145. var outTabSize = new Array();
  146. $("input").each(function() {
  147. if ($(this).attr("id") && $(this).attr("id").match(/samplesize/)) {
  148. var tabidnum = $(this).attr("id").match(/\d+/);
  149. var idnum = tabidnum[0];
  150. var thewidth = $(this).next().attr("value");
  151. tabInputSize[idnum] = thewidth;
  152. }
  153. });
  154. }
  155. function changeInputSize(inCoef, inIdNum)
  156. {
  157. var currentWidth = $("#samplesize\\\["+inIdNum+"\\\]").width();
  158. var newWidth = currentWidth + inCoef * 20;
  159. newWidth = Math.max(20, newWidth);
  160. newWidth = Math.min(newWidth, 600);
  161. $("#samplesize\\\["+inIdNum+"\\\]").width(newWidth);
  162. $("#sizeofinput\\\["+inIdNum+"\\\]").attr("value", newWidth);
  163. }
  164. function removeForbiddenChars(inTxt) {
  165. outTxt = inTxt;
  166. outTxt = outTxt.replace(/&quot;/g, ""); // remove the char
  167. outTxt = outTxt.replace(/\x22/g, ""); // remove the char
  168. outTxt = outTxt.replace(/"/g, ""); // remove the char
  169. outTxt = outTxt.replace(/\\\\/g, ""); // remove the \ char
  170. outTxt = outTxt.replace(/&nbsp;/g, " ");
  171. outTxt = outTxt.replace(/^ +/, "");
  172. outTxt = outTxt.replace(/ +$/, "");
  173. return outTxt;
  174. }
  175. function changeBlankSeparator()
  176. {
  177. var separatorNumber = $("#select_separator").val();
  178. var tabSeparator = getSeparatorFromNumber(separatorNumber);
  179. blankSeparatortStart = tabSeparator[0];
  180. blankSeparatortEnd = tabSeparator[1];
  181. blankSeparatortStartRegexp = getBlankSeparatorRegexp(blankSeparatortStart);
  182. blankSeparatortEndRegexp = getBlankSeparatorRegexp(blankSeparatortEnd);
  183. updateBlanks();
  184. }
  185. // this function is the same than the PHP one
  186. // if modify it modify the php one escapeForRegexp
  187. function getBlankSeparatorRegexp(inTxt)
  188. {
  189. var tabSpecialChar = new Array(".", "+", "*", "?", "[", "^", "]", "$", "(", ")",
  190. "{", "}", "=", "!", "<", ">", "|", ":", "-", ")");
  191. for (var i=0; i < tabSpecialChar.length; i++) {
  192. if (inTxt == tabSpecialChar[i]) {
  193. return "\\\"+inTxt;
  194. }
  195. }
  196. return inTxt;
  197. }
  198. // this function is the same than the PHP one
  199. // if modify it modify the php one getAllowedSeparator
  200. function getSeparatorFromNumber(innumber)
  201. {
  202. tabSeparator = new Array();
  203. tabSeparator[0] = new Array("[", "]");
  204. tabSeparator[1] = new Array("{", "}");
  205. tabSeparator[2] = new Array("(", ")");
  206. tabSeparator[3] = new Array("*", "*");
  207. tabSeparator[4] = new Array("#", "#");
  208. tabSeparator[5] = new Array("%", "%");
  209. tabSeparator[6] = new Array("$", "$");
  210. return tabSeparator[innumber];
  211. }
  212. function trimBlanksBetweenSeparator(inTxt, inSeparatorStart, inSeparatorEnd)
  213. {
  214. // blankSeparatortStartRegexp
  215. // blankSeparatortEndRegexp
  216. var result = inTxt
  217. result = result.replace(inSeparatorStart, "");
  218. result = result.replace(inSeparatorEnd, "");
  219. result = result.trim();
  220. return inSeparatorStart+result+inSeparatorEnd;
  221. }
  222. </script>';
  223. // answer
  224. $form->addElement('label', null, '<br /><br />'.get_lang('TypeTextBelow').', '.get_lang('And').' '.get_lang('UseTagForBlank'));
  225. $form->addElement(
  226. 'html_editor',
  227. 'answer',
  228. '<img src="../img/fill_field.png">',
  229. ['id' => 'answer', 'onkeyup' => "javascript: updateBlanks(this);"],
  230. array('ToolbarSet' => 'TestQuestionDescription')
  231. );
  232. $form->addRule('answer',get_lang('GiveText'),'required');
  233. //added multiple answers
  234. $form->addElement('checkbox','multiple_answer','', get_lang('FillInBlankSwitchable'));
  235. $form->addElement(
  236. 'select',
  237. 'select_separator',
  238. get_lang("SelectFillTheBlankSeparator"),
  239. self::getAllowedSeparatorForSelect(),
  240. ' id="select_separator" style="width:150px" onchange="changeBlankSeparator()" '
  241. );
  242. $form->addElement(
  243. 'label',
  244. null,
  245. '<input type="button" onclick="updateBlanks()" value="'.get_lang('RefreshBlanks').'" class="btn btn-default" />'
  246. );
  247. $form->addElement('html','<div id="blanks_weighting"></div>');
  248. global $text;
  249. // setting the save button here and not in the question class.php
  250. $form->addElement('html','<div id="defineoneblank" style="color:#D04A66; margin-left:160px">'.get_lang('DefineBlanks').'</div>');
  251. $form->addButtonSave($text, 'submitQuestion');
  252. if (!empty($this->id)) {
  253. $form->setDefaults($defaults);
  254. } else {
  255. if ($this->isContent == 1) {
  256. $form->setDefaults($defaults);
  257. }
  258. }
  259. }
  260. /**
  261. * Function which creates the form to create/edit the answers of the question
  262. * @param FormValidator $form
  263. */
  264. public function processAnswersCreation($form)
  265. {
  266. $answer = $form->getSubmitValue('answer');
  267. // Due the ckeditor transform the elements to their HTML value
  268. //$answer = api_html_entity_decode($answer, ENT_QUOTES, $charset);
  269. //$answer = htmlentities(api_utf8_encode($answer));
  270. // remove the :: eventually written by the user
  271. $answer = str_replace('::', '', $answer);
  272. // remove starting and ending space and &nbsp;
  273. $answer = api_preg_replace("/\xc2\xa0/", " ", $answer);
  274. // start and end separator
  275. $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
  276. $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
  277. $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
  278. $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
  279. // remove spaces at the beginning and the end of text in square brackets
  280. $answer = preg_replace_callback(
  281. "/".$blankStartSeparatorRegexp."[^]]+".$blankEndSeparatorRegexp."/",
  282. function ($matches) use ($blankStartSeparator, $blankEndSeparator) {
  283. $matchingResult = $matches[0];
  284. $matchingResult = trim($matchingResult, $blankStartSeparator);
  285. $matchingResult = trim($matchingResult, $blankEndSeparator);
  286. $matchingResult = trim($matchingResult);
  287. // remove forbidden chars
  288. $matchingResult = str_replace("/\\/", "", $matchingResult);
  289. $matchingResult = str_replace('/"/', "", $matchingResult);
  290. return $blankStartSeparator.$matchingResult.$blankEndSeparator;
  291. },
  292. $answer
  293. );
  294. // get the blanks weightings
  295. $nb = preg_match_all(
  296. '/'.$blankStartSeparatorRegexp.'[^'.$blankStartSeparatorRegexp.']*'.$blankEndSeparatorRegexp.'/',
  297. $answer,
  298. $blanks
  299. );
  300. if (isset($_GET['editQuestion'])) {
  301. $this->weighting = 0;
  302. }
  303. /* if we have some [tobefound] in the text
  304. build the string to save the following in the answers table
  305. <p>I use a [computer] and a [pen].</p>
  306. becomes
  307. <p>I use a [computer] and a [pen].</p>::100,50:100,50@1
  308. ++++++++-------**
  309. --- -- --- -- -
  310. A B (C) (D)(E)
  311. +++++++ : required, weighting of each words
  312. ------- : optional, input width to display, 200 if not present
  313. ** : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  314. A : weighting for the word [computer]
  315. B : weighting for the word [pen]
  316. C : input width for the word [computer]
  317. D : input width for the word [pen]
  318. E : equal @1 if "Allow answers order switches" has been checked, @ otherwise
  319. */
  320. if ($nb > 0) {
  321. $answer .= '::';
  322. // weighting
  323. for ($i=0; $i < $nb; ++$i) {
  324. // enter the weighting of word $i
  325. $answer .= $form->getSubmitValue('weighting['.$i.']');
  326. // not the last word, add ","
  327. if ($i != $nb - 1) {
  328. $answer .= ",";
  329. }
  330. // calculate the global weighting for the question
  331. $this -> weighting += $form->getSubmitValue('weighting['.$i.']');
  332. }
  333. // input width
  334. $answer .= ":";
  335. for ($i=0; $i < $nb; ++$i) {
  336. // enter the width of input for word $i
  337. $answer .= $form->getSubmitValue('sizeofinput['.$i.']');
  338. // not the last word, add ","
  339. if ($i != $nb - 1) {
  340. $answer .= ",";
  341. }
  342. }
  343. }
  344. // write the blank separator code number
  345. // see function getAllowedSeparator
  346. /*
  347. 0 [...]
  348. 1 {...}
  349. 2 (...)
  350. 3 *...*
  351. 4 #...#
  352. 5 %...%
  353. 6 $...$
  354. */
  355. $answer .= ":".$form->getSubmitValue('select_separator');
  356. // Allow answers order switches
  357. $is_multiple = $form -> getSubmitValue('multiple_answer');
  358. $answer.= '@'.$is_multiple;
  359. $this->save();
  360. $objAnswer = new Answer($this->id);
  361. $objAnswer->createAnswer($answer, 0, '', 0, 1);
  362. $objAnswer->save();
  363. }
  364. /**
  365. * @param null $feedback_type
  366. * @param null $counter
  367. * @param null $score
  368. * @return null|string
  369. */
  370. public function return_header($feedback_type = null, $counter = null, $score = null)
  371. {
  372. $header = parent::return_header($feedback_type, $counter, $score);
  373. $header .= '<table class="'.$this->question_table_class .'">
  374. <tr>
  375. <th>'.get_lang("Answer").'</th>
  376. </tr>';
  377. return $header;
  378. }
  379. /**
  380. * @param $separatorStartRegexp
  381. * @param $separatorEndRegexp
  382. * @param $correctItemRegexp
  383. * @param $questionId
  384. * @param $correctItem
  385. * @param $attributes
  386. * @param $answer
  387. * @param $listAnswersInfo
  388. * @param $displayForStudent
  389. * @return string
  390. */
  391. public static function getFillTheBlankHtml(
  392. $separatorStartRegexp,
  393. $separatorEndRegexp,
  394. $correctItemRegexp,
  395. $questionId,
  396. $correctItem,
  397. $attributes,
  398. $answer,
  399. $listAnswersInfo,
  400. $displayForStudent,
  401. $inBlankNumber
  402. ) {
  403. $result = "";
  404. $inTabTeacherSolution = $listAnswersInfo['tabwords'];
  405. $inTeacherSolution = $inTabTeacherSolution[$inBlankNumber];
  406. switch (self::getFillTheBlankAnswerType($inTeacherSolution)) {
  407. case self::FILL_THE_BLANK_MENU:
  408. $selected = "";
  409. // the blank menu
  410. $optionMenu = "";
  411. // display a menu from answer separated with |
  412. // if display for student, shuffle the correct answer menu
  413. $listMenu = self::getFillTheBlankMenuAnswers($inTeacherSolution, $displayForStudent);
  414. $result .= '<select name="choice['.$questionId.'][]">';
  415. for ($k=0; $k < count($listMenu); $k++) {
  416. $selected = "";
  417. if ($correctItem == $listMenu[$k]) {
  418. $selected = " selected=selected ";
  419. }
  420. // if in teacher view, display the first item by default, which is the right answer
  421. if ($k==0 && !$displayForStudent) {
  422. $selected = " selected=selected ";
  423. }
  424. $optionMenu .= '<option '.$selected.' value="'.$listMenu[$k].'">'.$listMenu[$k].'</option>';
  425. }
  426. if ($selected == "") {
  427. // no good answer have been found...
  428. $selected = " selected=selected ";
  429. }
  430. $result .= "<option $selected value=''>--</option>";
  431. $result .= $optionMenu;
  432. $result .= '</select>';
  433. break;
  434. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  435. //no break
  436. case self::FILL_THE_BLANK_STANDARD:
  437. default:
  438. $result = Display::input('text', "choice[$questionId][]", $correctItem, $attributes);
  439. break;
  440. }
  441. return $result;
  442. }
  443. /**
  444. * Return an array with the different choices available
  445. * when the answers between bracket show as a menu
  446. * @param string $correctAnswer
  447. * @param bool $displayForStudent true if we want to shuffle the choices of the menu for students
  448. *
  449. * @return array
  450. */
  451. public static function getFillTheBlankMenuAnswers($correctAnswer, $displayForStudent)
  452. {
  453. // if $inDisplayForStudent, then shuffle the result array
  454. $listChoises = api_preg_split("/\|/", $correctAnswer);
  455. if ($displayForStudent) {
  456. shuffle($listChoises);
  457. }
  458. return $listChoises;
  459. }
  460. /**
  461. * Return the array index of the student answer
  462. * @param string $correctAnswer the menu Choice1|Choice2|Choice3
  463. * @param string $studentAnswer the student answer must be Choice1 or Choice2 or Choice3
  464. *
  465. * @return int in the example 0 1 or 2 depending of the choice of the student
  466. */
  467. public static function getFillTheBlankMenuAnswerNum($correctAnswer, $studentAnswer)
  468. {
  469. $listChoices = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  470. foreach ($listChoices as $num => $value) {
  471. if ($value == $studentAnswer) {
  472. return $num;
  473. }
  474. }
  475. // should not happened, because student choose the answer in a menu of possible answers
  476. return -1;
  477. }
  478. /**
  479. * Return the possible answer if the answer between brackets is a multiple choice menu
  480. * @param string $correctAnswer
  481. *
  482. * @return array
  483. */
  484. public static function getFillTheBlankSeveralAnswers($correctAnswer)
  485. {
  486. // is answer||Answer||response||Response , mean answer or Answer ...
  487. $listSeveral = api_preg_split("/\|\|/", $correctAnswer);
  488. return $listSeveral;
  489. }
  490. /**
  491. * Return true if student answer is right according to the correctAnswer
  492. * it is not as simple as equality, because of the type of Fill The Blank question
  493. * eg : studentAnswer = 'Un' and correctAnswer = 'Un||1||un'
  494. * @param string $studentAnswer [studentanswer] of the info array of the answer field
  495. * @param string $correctAnswer [tabwords] of the info array of the answer field
  496. *
  497. * @return bool
  498. */
  499. public static function isGoodStudentAnswer($studentAnswer, $correctAnswer)
  500. {
  501. switch (self::getFillTheBlankAnswerType($correctAnswer)) {
  502. case self::FILL_THE_BLANK_MENU:
  503. $listMenu = self::getFillTheBlankMenuAnswers($correctAnswer, false);
  504. $result = $listMenu[0] == $studentAnswer;
  505. break;
  506. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  507. // the answer must be one of the choice made
  508. $listSeveral = self::getFillTheBlankSeveralAnswers($correctAnswer);
  509. $result = in_array($studentAnswer, $listSeveral);
  510. break;
  511. case self::FILL_THE_BLANK_STANDARD:
  512. default:
  513. $result = $studentAnswer == $correctAnswer;
  514. break;
  515. }
  516. return $result;
  517. }
  518. /**
  519. * @param string $correctAnswer
  520. *
  521. * @return int
  522. */
  523. public static function getFillTheBlankAnswerType($correctAnswer)
  524. {
  525. if (api_strpos($correctAnswer, "|") && !api_strpos($correctAnswer, "||")) {
  526. return self::FILL_THE_BLANK_MENU;
  527. } elseif (api_strpos($correctAnswer, "||")) {
  528. return self::FILL_THE_BLANK_SEVERAL_ANSWER;
  529. } else {
  530. return self::FILL_THE_BLANK_STANDARD;
  531. }
  532. }
  533. /**
  534. * Return information about the answer
  535. * @param string $userAnswer the text of the answer of the question
  536. * @param bool $isStudentAnswer true if it's a student answer false the empty question model
  537. *
  538. * @return array of information about the answer
  539. */
  540. public static function getAnswerInfo($userAnswer = "", $isStudentAnswer = false)
  541. {
  542. $listAnswerResults = array();
  543. $listAnswerResults['text'] = "";
  544. $listAnswerResults['wordsCount'] = 0;
  545. $listAnswerResults['tabwordsbracket'] = array();
  546. $listAnswerResults['tabwords'] = array();
  547. $listAnswerResults['tabweighting'] = array();
  548. $listAnswerResults['tabinputsize'] = array();
  549. $listAnswerResults['switchable'] = "";
  550. $listAnswerResults['studentanswer'] = array();
  551. $listAnswerResults['studentscore'] = array();
  552. $listAnswerResults['blankseparatornumber'] = 0;
  553. $listDoubleColon = array();
  554. api_preg_match("/(.*)::(.*)$/s", $userAnswer, $listResult);
  555. if (count($listResult) < 2) {
  556. $listDoubleColon[] = '';
  557. $listDoubleColon[] = '';
  558. } else {
  559. $listDoubleColon[] = $listResult[1];
  560. $listDoubleColon[] = $listResult[2];
  561. }
  562. $listAnswerResults['systemstring'] = $listDoubleColon[1];
  563. // make sure we only take the last bit to find special marks
  564. $listArobaseSplit = explode('@', $listDoubleColon[1]);
  565. if (count($listArobaseSplit) < 2) {
  566. $listArobaseSplit[1] = "";
  567. }
  568. // take the complete string except after the last '::'
  569. $listDetails = explode(":", $listArobaseSplit[0]);
  570. // < number of item after the ::[score]:[size]:[separator_id]@ , here there are 3
  571. if (count($listDetails) < 3) {
  572. $listWeightings = explode(',', $listDetails[0]);
  573. $listSizeOfInput = array();
  574. for ($i=0; $i < count($listWeightings); $i++) {
  575. $listSizeOfInput[] = 200;
  576. }
  577. $blankSeparatorNumber = 0; // 0 is [...]
  578. } else {
  579. $listWeightings = explode(',', $listDetails[0]);
  580. $listSizeOfInput = explode(',', $listDetails[1]);
  581. $blankSeparatorNumber = $listDetails[2];
  582. }
  583. $listAnswerResults['text'] = $listDoubleColon[0];
  584. $listAnswerResults['tabweighting'] = $listWeightings;
  585. $listAnswerResults['tabinputsize'] = $listSizeOfInput;
  586. $listAnswerResults['switchable'] = $listArobaseSplit[1];
  587. $listAnswerResults['blankseparatorstart'] = self::getStartSeparator($blankSeparatorNumber);
  588. $listAnswerResults['blankseparatorend'] = self::getEndSeparator($blankSeparatorNumber);
  589. $listAnswerResults['blankseparatornumber'] = $blankSeparatorNumber;
  590. $blankCharStart = self::getStartSeparator($blankSeparatorNumber);
  591. $blankCharEnd = self::getEndSeparator($blankSeparatorNumber);
  592. $blankCharStartForRegexp = self::escapeForRegexp($blankCharStart);
  593. $blankCharEndForRegexp = self::escapeForRegexp($blankCharEnd);
  594. // get all blanks words
  595. $listAnswerResults['wordsCount'] = api_preg_match_all(
  596. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  597. $listDoubleColon[0],
  598. $listWords
  599. );
  600. if ($listAnswerResults['wordsCount'] > 0) {
  601. $listAnswerResults['tabwordsbracket'] = $listWords[0];
  602. // remove [ and ] in string
  603. array_walk(
  604. $listWords[0],
  605. function (&$value, $key, $tabBlankChar) {
  606. $trimChars = "";
  607. for ($i=0; $i < count($tabBlankChar); $i++) {
  608. $trimChars .= $tabBlankChar[$i];
  609. }
  610. $value = trim($value, $trimChars);
  611. },
  612. array($blankCharStart, $blankCharEnd)
  613. );
  614. $listAnswerResults['tabwords'] = $listWords[0];
  615. }
  616. // get all common words
  617. $commonWords = api_preg_replace(
  618. '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
  619. "::",
  620. $listDoubleColon[0]
  621. );
  622. // if student answer, the second [] is the student answer,
  623. // the third is if student scored or not
  624. $listBrackets = array();
  625. $listWords = array();
  626. if ($isStudentAnswer) {
  627. for ($i=0; $i < count($listAnswerResults['tabwords']); $i++) {
  628. $listBrackets[] = $listAnswerResults['tabwordsbracket'][$i];
  629. $listWords[] = $listAnswerResults['tabwords'][$i];
  630. if ($i+1 < count($listAnswerResults['tabwords'])) {
  631. // should always be
  632. $i++;
  633. }
  634. $listAnswerResults['studentanswer'][] = $listAnswerResults['tabwords'][$i];
  635. if ($i+1 < count($listAnswerResults['tabwords'])) {
  636. // should always be
  637. $i++;
  638. }
  639. $listAnswerResults['studentscore'][] = $listAnswerResults['tabwords'][$i];
  640. }
  641. $listAnswerResults['tabwords'] = $listWords;
  642. $listAnswerResults['tabwordsbracket'] = $listBrackets;
  643. // if we are in student view, we've got 3 times :::::: for common words
  644. $commonWords = api_preg_replace("/::::::/", "::", $commonWords);
  645. }
  646. $listAnswerResults['commonwords'] = explode("::", $commonWords);
  647. return $listAnswerResults;
  648. }
  649. /**
  650. * Replace the occurrence of blank word with [correct answer][student answer][answer is correct]
  651. * @param array $listWithStudentAnswer
  652. *
  653. * @return string
  654. */
  655. public static function getAnswerInStudentAttempt($listWithStudentAnswer)
  656. {
  657. $separatorStart = $listWithStudentAnswer['blankseparatorstart'];
  658. $separatorEnd = $listWithStudentAnswer['blankseparatorend'];
  659. // lets rebuild the sentence with [correct answer][student answer][answer is correct]
  660. $result = "";
  661. for ($i=0; $i < count($listWithStudentAnswer['commonwords']) - 1; $i++) {
  662. $result .= $listWithStudentAnswer['commonwords'][$i];
  663. $result .= $listWithStudentAnswer['tabwordsbracket'][$i];
  664. $result .= $separatorStart.$listWithStudentAnswer['studentanswer'][$i].$separatorEnd;
  665. $result .= $separatorStart.$listWithStudentAnswer['studentscore'][$i].$separatorEnd;
  666. }
  667. $result .= $listWithStudentAnswer['commonwords'][$i];
  668. $result .= "::";
  669. // add the system string
  670. $result .= $listWithStudentAnswer['systemstring'];
  671. return $result;
  672. }
  673. /**
  674. * This function is the same than the js one above getBlankSeparatorRegexp
  675. * @param string $inChar
  676. *
  677. * @return string
  678. */
  679. public static function escapeForRegexp($inChar)
  680. {
  681. $listChars = [
  682. ".",
  683. "+",
  684. "*",
  685. "?",
  686. "[",
  687. "^",
  688. "]",
  689. "$",
  690. "(",
  691. ")",
  692. "{",
  693. "}",
  694. "=",
  695. "!",
  696. ">",
  697. "|",
  698. ":",
  699. "-",
  700. ")",
  701. ];
  702. if (in_array($inChar, $listChars)) {
  703. return "\\".$inChar;
  704. } else {
  705. return $inChar;
  706. }
  707. }
  708. /**
  709. * return $text protected for use in regexp
  710. * @param string $text
  711. *
  712. * @return mixed
  713. */
  714. public static function getRegexpProtected($text)
  715. {
  716. $listRegexpCharacters = [
  717. "/",
  718. ".",
  719. "+",
  720. "*",
  721. "?",
  722. "[",
  723. "^",
  724. "]",
  725. "$",
  726. "(",
  727. ")",
  728. "{",
  729. "}",
  730. "=",
  731. "!",
  732. ">",
  733. "|",
  734. ":",
  735. "-",
  736. ")",
  737. ];
  738. $result = $text;
  739. for ($i=0; $i < count($listRegexpCharacters); $i++) {
  740. $result = str_replace($listRegexpCharacters[$i], "\\".$listRegexpCharacters[$i], $result);
  741. }
  742. return $result;
  743. }
  744. /**
  745. * This function must be the same than the js one getSeparatorFromNumber above
  746. * @return array
  747. */
  748. public static function getAllowedSeparator()
  749. {
  750. $fillBlanksAllowedSeparator = array(
  751. array('[', ']'),
  752. array('{', '}'),
  753. array('(', ')'),
  754. array('*', '*'),
  755. array('#', '#'),
  756. array('%', '%'),
  757. array('$', '$'),
  758. );
  759. return $fillBlanksAllowedSeparator;
  760. }
  761. /**
  762. * return the start separator for answer
  763. * @param string $number
  764. *
  765. * @return mixed
  766. */
  767. public static function getStartSeparator($number)
  768. {
  769. $listSeparators = self::getAllowedSeparator();
  770. return $listSeparators[$number][0];
  771. }
  772. /**
  773. * return the end separator for answer
  774. * @param string $number
  775. *
  776. * @return mixed
  777. */
  778. public static function getEndSeparator($number)
  779. {
  780. $listSeparators = self::getAllowedSeparator();
  781. return $listSeparators[$number][1];
  782. }
  783. /**
  784. * Return as a description text, array of allowed separators for question
  785. * eg: array("[...]", "(...)")
  786. * @return array
  787. */
  788. public static function getAllowedSeparatorForSelect()
  789. {
  790. $listResults = array();
  791. $fillBlanksAllowedSeparator = self::getAllowedSeparator();
  792. for ($i=0; $i < count($fillBlanksAllowedSeparator); $i++) {
  793. $listResults[] = $fillBlanksAllowedSeparator[$i][0]."...".$fillBlanksAllowedSeparator[$i][1];
  794. }
  795. return $listResults;
  796. }
  797. /**
  798. * return the code number of the separator for the question
  799. * @param string $startSeparator
  800. * @param string $endSeparator
  801. *
  802. * @return int
  803. */
  804. public function getDefaultSeparatorNumber($startSeparator, $endSeparator)
  805. {
  806. $listSeparators = self::getAllowedSeparator();
  807. $result = 0;
  808. for ($i=0; $i < count($listSeparators); $i++) {
  809. if ($listSeparators[$i][0] == $startSeparator &&
  810. $listSeparators[$i][1] == $endSeparator
  811. ) {
  812. $result = $i;
  813. }
  814. }
  815. return $result;
  816. }
  817. /**
  818. * return the HTML display of the answer
  819. * @param string $answer
  820. * @param bool $resultsDisabled
  821. *
  822. * @return string
  823. */
  824. public static function getHtmlDisplayForAnswer($answer, $resultsDisabled = false)
  825. {
  826. $result = "";
  827. $listStudentAnswerInfo = self::getAnswerInfo($answer, true);
  828. // rebuild the answer with good HTML style
  829. // this is the student answer, right or wrong
  830. for ($i=0; $i < count($listStudentAnswerInfo['studentanswer']); $i++) {
  831. if ($listStudentAnswerInfo['studentscore'][$i] == 1) {
  832. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlRightAnswer(
  833. $listStudentAnswerInfo['studentanswer'][$i],
  834. $listStudentAnswerInfo['tabwords'][$i],
  835. $resultsDisabled
  836. );
  837. } else {
  838. $listStudentAnswerInfo['studentanswer'][$i] = self::getHtmlWrongAnswer(
  839. $listStudentAnswerInfo['studentanswer'][$i],
  840. $listStudentAnswerInfo['tabwords'][$i],
  841. $resultsDisabled
  842. );
  843. }
  844. }
  845. // rebuild the sentence with student answer inserted
  846. for ($i=0; $i < count($listStudentAnswerInfo['commonwords']); $i++) {
  847. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  848. $result .= isset($listStudentAnswerInfo['studentanswer'][$i]) ? $listStudentAnswerInfo['studentanswer'][$i] : '';
  849. }
  850. // the last common word (should be </p>)
  851. $result .= isset($listStudentAnswerInfo['commonwords'][$i]) ? $listStudentAnswerInfo['commonwords'][$i] : '';
  852. return $result;
  853. }
  854. /**
  855. * return the HTML code of answer for correct and wrong answer
  856. * @param string $answer
  857. * @param string $correct
  858. * @param string $right
  859. * @param bool $resultsDisabled
  860. *
  861. * @return string
  862. */
  863. public static function getHtmlAnswer($answer, $correct, $right, $resultsDisabled = false)
  864. {
  865. $style = "color: green";
  866. if (!$right) {
  867. $style = "color: red; text-decoration: line-through;";
  868. }
  869. $type = FillBlanks::getFillTheBlankAnswerType($correct);
  870. switch ($type) {
  871. case self::FILL_THE_BLANK_MENU:
  872. $correctAnswerHtml = "";
  873. $listPossibleAnswers = FillBlanks::getFillTheBlankMenuAnswers($correct, false);
  874. $correctAnswerHtml .= "<span style='color: green'>".$listPossibleAnswers[0]."</span>";
  875. $correctAnswerHtml .= " <span style='font-weight:normal'>(";
  876. for ($i=1; $i < count($listPossibleAnswers); $i++) {
  877. $correctAnswerHtml .= $listPossibleAnswers[$i];
  878. if ($i != count($listPossibleAnswers) - 1) {
  879. $correctAnswerHtml .= " | ";
  880. }
  881. }
  882. $correctAnswerHtml .= ")</span>";
  883. break;
  884. case self::FILL_THE_BLANK_SEVERAL_ANSWER:
  885. $listCorrects = explode("||", $correct);
  886. $firstCorrect = $correct;
  887. if (count($listCorrects) > 0) {
  888. $firstCorrect = $listCorrects[0];
  889. }
  890. $correctAnswerHtml = "<span style='color: green'>".$firstCorrect."</span>";
  891. break;
  892. case self::FILL_THE_BLANK_STANDARD:
  893. default:
  894. $correctAnswerHtml = "<span style='color: green'>".$correct."</span>";
  895. }
  896. if ($resultsDisabled) {
  897. $correctAnswerHtml = "<span title='".get_lang("ExerciseWithFeedbackWithoutCorrectionComment")."'> - </span>";
  898. }
  899. $result = "<span style='border:1px solid black; border-radius:5px; padding:2px; font-weight:bold;'>";
  900. $result .= "<span style='$style'>".$answer."</span>";
  901. $result .= "&nbsp;<span style='font-size:120%;'>/</span>&nbsp;";
  902. $result .= $correctAnswerHtml;
  903. $result .= "</span>";
  904. return $result;
  905. }
  906. /**
  907. * return HTML code for correct answer
  908. * @param string $answer
  909. * @param string $correct
  910. * @param bool $resultsDisabled
  911. *
  912. * @return string
  913. */
  914. public static function getHtmlRightAnswer($answer, $correct, $resultsDisabled = false)
  915. {
  916. return self::getHtmlAnswer($answer, $correct, true, $resultsDisabled);
  917. }
  918. /**
  919. * return HTML code for wrong answer
  920. * @param string $answer
  921. * @param string $correct
  922. * @param bool $resultsDisabled
  923. *
  924. * @return string
  925. */
  926. public static function getHtmlWrongAnswer($answer, $correct, $resultsDisabled = false)
  927. {
  928. return self::getHtmlAnswer($answer, $correct, false, $resultsDisabled);
  929. }
  930. }