fill_blanks.class.php 44 KB

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