123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446 |
- <?php
- class FillBlanks extends Question
- {
- const FILL_THE_BLANK_STANDARD = 0;
- const FILL_THE_BLANK_MENU = 1;
- const FILL_THE_BLANK_SEVERAL_ANSWER = 2;
- public static $typePicture = 'fill_in_blanks.png';
- public static $explanationLangVar = 'FillBlanks';
-
- public function __construct()
- {
- parent::__construct();
- $this->type = FILL_IN_BLANKS;
- $this->isContent = $this->getIsContent();
- }
-
- public function createAnswersForm($form)
- {
- $defaults = [];
- $defaults['answer'] = get_lang('DefaultTextInBlanks');
- $defaults['select_separator'] = 0;
- $blankSeparatorNumber = 0;
- if (!empty($this->id)) {
- $objectAnswer = new Answer($this->id);
- $answer = $objectAnswer->selectAnswer(1);
- $listAnswersInfo = self::getAnswerInfo($answer);
- $defaults['multiple_answer'] = 0;
- if ($listAnswersInfo['switchable']) {
- $defaults['multiple_answer'] = 1;
- }
-
- $defaults['answer'] = $listAnswersInfo['text'];
- $defaults['select_separator'] = $listAnswersInfo['blank_separator_number'];
- $blankSeparatorNumber = $listAnswersInfo['blank_separator_number'];
- }
- $blankSeparatorStart = self::getStartSeparator($blankSeparatorNumber);
- $blankSeparatorEnd = self::getEndSeparator($blankSeparatorNumber);
- $setWeightAndSize = '';
- if (isset($listAnswersInfo) && count($listAnswersInfo['weighting']) > 0) {
- foreach ($listAnswersInfo['weighting'] as $i => $weighting) {
- $setWeightAndSize .= 'document.getElementById("weighting['.$i.']").value = "'.$weighting.'";';
- }
- foreach ($listAnswersInfo['input_size'] as $i => $sizeOfInput) {
- $setWeightAndSize .= 'document.getElementById("sizeofinput['.$i.']").value = "'.$sizeOfInput.'";';
- $setWeightAndSize .= 'document.getElementById("samplesize['.$i.']").style.width = "'.$sizeOfInput.'px";';
- }
- }
- echo '<script>
- var firstTime = true;
- var originalOrder = new Array();
- var blankSeparatorStart = "'.$blankSeparatorStart.'";
- var blankSeparatorEnd = "'.$blankSeparatorEnd.'";
- var blankSeparatorStartRegexp = getBlankSeparatorRegexp(blankSeparatorStart);
- var blankSeparatorEndRegexp = getBlankSeparatorRegexp(blankSeparatorEnd);
- var blanksRegexp = "/"+blankSeparatorStartRegexp+"[^"+blankSeparatorStartRegexp+"]*"+blankSeparatorEndRegexp+"/g";
-
- CKEDITOR.on("instanceCreated", function(e) {
- if (e.editor.name === "answer") {
- //e.editor.on("change", updateBlanks);
- e.editor.on("change", function(){
- updateBlanks();
- });
- }
- });
-
- function updateBlanks()
- {
- var answer;
- if (firstTime) {
- var field = document.getElementById("answer");
- answer = field.value;
- } else {
- answer = CKEDITOR.instances["answer"].getData();
- }
-
- // disable the save button, if not blanks have been created
- $("button").attr("disabled", "disabled");
- $("#defineoneblank").show();
-
- var blanks = answer.match(eval(blanksRegexp));
- var fields = "<div class=\"form-group \">";
- fields += "<label class=\"col-sm-2 control-label\"></label>";
- fields += "<div class=\"col-sm-8\">";
- fields += "<table class=\"data_table\">";
- fields += "<tr><th style=\"width:220px\">'.get_lang('WordTofind').'</th>";
- fields += "<th style=\"width:50px\">'.get_lang('QuestionWeighting').'</th>";
- fields += "<th>'.get_lang('BlankInputSize').'</th></tr>";
- if (blanks != null) {
- for (var i=0; i < blanks.length; i++) {
- // remove forbidden characters that causes bugs
- blanks[i] = removeForbiddenChars(blanks[i]);
- // trim blanks between brackets
- blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatorStart, blankSeparatorEnd);
-
- // if the word is empty []
- if (blanks[i] == blankSeparatorStartRegexp+blankSeparatorEndRegexp) {
- break;
- }
-
- // get input size
- var inputSize = 100;
- var textValue = blanks[i].substr(1, blanks[i].length - 2);
- var btoaValue = textValue.hashCode();
-
- if (firstTime == false) {
- var element = document.getElementById("samplesize["+i+"]");
- if (element) {
- inputSize = document.getElementById("sizeofinput["+i+"]").value;
- }
- }
- if (document.getElementById("weighting["+i+"]")) {
- var value = document.getElementById("weighting["+i+"]").value;
- } else {
- var value = "1";
- }
- var blanksWithColor = trimBlanksBetweenSeparator(blanks[i], blankSeparatorStart, blankSeparatorEnd, 1);
-
- fields += "<tr>";
- fields += "<td>"+blanksWithColor+"</td>";
- fields += "<td><input class=\"form-control\" style=\"width:60px\" value=\""+value+"\" type=\"text\" id=\"weighting["+i+"]\" name=\"weighting["+i+"]\" /></td>";
- fields += "<td>";
- fields += "<input class=\"btn btn-default\" type=\"button\" value=\"-\" onclick=\"changeInputSize(-1, "+i+")\"> ";
- fields += "<input class=\"btn btn-default\" type=\"button\" value=\"+\" onclick=\"changeInputSize(1, "+i+")\"> ";
- fields += " <input class=\"sample\" id=\"samplesize["+i+"]\" data-btoa=\""+btoaValue+"\" type=\"text\" value=\""+textValue+"\" style=\"width:"+inputSize+"px\" disabled=disabled />";
- fields += "<input id=\"sizeofinput["+i+"]\" type=\"hidden\" value=\""+inputSize+"\" name=\"sizeofinput["+i+"]\" />";
- fields += "</td>";
- fields += "</tr>";
-
- // enable the save button
- $("button").removeAttr("disabled");
- $("#defineoneblank").hide();
- }
- }
-
- document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>";
-
- $(originalOrder).each(function(i, data) {
- if (firstTime == false) {
- value = data.value;
- var d = $("input.sample[data-btoa=\'"+value+"\']");
- var id = d.attr("id");
- if (id) {
- var sizeInputId = id.replace("samplesize", "sizeofinput");
- var sizeInputId = sizeInputId.replace("[", "\\\[");
- var sizeInputId = sizeInputId.replace("]", "\\\]");
- $("#"+sizeInputId).val(data.width);
- d.outerWidth(data.width+"px");
- }
- }
- });
-
- updateOrder(blanks);
- if (firstTime) {
- firstTime = false;
- '.$setWeightAndSize.'
- }
- }
- window.onload = updateBlanks;
- String.prototype.hashCode = function() {
- var hash = 0, i, chr, len;
- if (this.length === 0) return hash;
- for (i = 0, len = this.length; i < len; i++) {
- chr = this.charCodeAt(i);
- hash = ((hash << 5) - hash) + chr;
- hash |= 0; // Convert to 32bit integer
- }
- return hash;
- };
-
- function updateOrder(blanks)
- {
- originalOrder = new Array();
- if (blanks != null) {
- for (var i=0; i < blanks.length; i++) {
- // remove forbidden characters that causes bugs
- blanks[i] = removeForbiddenChars(blanks[i]);
- // trim blanks between brackets
- blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatorStart, blankSeparatorEnd);
-
- // if the word is empty []
- if (blanks[i] == blankSeparatorStartRegexp+blankSeparatorEndRegexp) {
- break;
- }
- var textValue = blanks[i].substr(1, blanks[i].length - 2);
- var btoaValue = textValue.hashCode();
-
- if (firstTime == false) {
- var element = document.getElementById("samplesize["+i+"]");
- if (element) {
- inputSize = document.getElementById("sizeofinput["+i+"]").value;
- originalOrder.push({ "width" : inputSize, "value": btoaValue });
- }
- }
- }
- }
- }
-
- function changeInputSize(coef, inIdNum)
- {
- if (firstTime) {
- var field = document.getElementById("answer");
- answer = field.value;
- } else {
- answer = CKEDITOR.instances["answer"].getData();
- }
-
- var blanks = answer.match(eval(blanksRegexp));
- var currentWidth = $("#samplesize\\\["+inIdNum+"\\\]").width();
- var newWidth = currentWidth + coef * 20;
- newWidth = Math.max(20, newWidth);
- newWidth = Math.min(newWidth, 600);
- $("#samplesize\\\["+inIdNum+"\\\]").outerWidth(newWidth);
- $("#sizeofinput\\\["+inIdNum+"\\\]").attr("value", newWidth);
-
- updateOrder(blanks);
- }
- function removeForbiddenChars(inTxt)
- {
- outTxt = inTxt;
- outTxt = outTxt.replace(/"/g, ""); // remove the char
- outTxt = outTxt.replace(/\x22/g, ""); // remove the char
- outTxt = outTxt.replace(/"/g, ""); // remove the char
- outTxt = outTxt.replace(/\\\\/g, ""); // remove the \ char
- outTxt = outTxt.replace(/ /g, " ");
- outTxt = outTxt.replace(/^ +/, "");
- outTxt = outTxt.replace(/ +$/, "");
-
- return outTxt;
- }
- function changeBlankSeparator()
- {
- var separatorNumber = $("#select_separator").val();
- var tabSeparator = getSeparatorFromNumber(separatorNumber);
- blankSeparatorStart = tabSeparator[0];
- blankSeparatorEnd = tabSeparator[1];
- blankSeparatorStartRegexp = getBlankSeparatorRegexp(blankSeparatorStart);
- blankSeparatorEndRegexp = getBlankSeparatorRegexp(blankSeparatorEnd);
- blanksRegexp = "/"+blankSeparatorStartRegexp+"[^"+blankSeparatorStartRegexp+"]*"+blankSeparatorEndRegexp+"/g";
- updateBlanks();
- }
- // this function is the same than the PHP one
- // if modify it modify the php one escapeForRegexp
- function getBlankSeparatorRegexp(inTxt)
- {
- var tabSpecialChar = new Array(".", "+", "*", "?", "[", "^", "]", "$", "(", ")",
- "{", "}", "=", "!", "<", ">", "|", ":", "-", ")");
- for (var i=0; i < tabSpecialChar.length; i++) {
- if (inTxt == tabSpecialChar[i]) {
- return "\\\"+inTxt;
- }
- }
- return inTxt;
- }
- // this function is the same than the PHP one
- // if modify it modify the php one getAllowedSeparator
- function getSeparatorFromNumber(number)
- {
- var separator = new Array();
- separator[0] = new Array("[", "]");
- separator[1] = new Array("{", "}");
- separator[2] = new Array("(", ")");
- separator[3] = new Array("*", "*");
- separator[4] = new Array("#", "#");
- separator[5] = new Array("%", "%");
- separator[6] = new Array("$", "$");
- return separator[number];
- }
- function trimBlanksBetweenSeparator(inTxt, inSeparatorStart, inSeparatorEnd, addColor)
- {
- var result = inTxt
- result = result.replace(inSeparatorStart, "");
- result = result.replace(inSeparatorEnd, "");
- result = result.trim();
-
- if (addColor == 1) {
- var resultParts = result.split("|");
- var partsToString = "";
- resultParts.forEach(function(item, index) {
- if (index == 0) {
- item = "<b><font style=\"color:green\"> " + item +"</font></b>";
- }
- if (index < resultParts.length - 1) {
- item = item + " | ";
- }
- partsToString += item;
- });
- result = partsToString;
- }
-
- return inSeparatorStart+result+inSeparatorEnd;
- }
-
- </script>';
-
- $form->addLabel(
- null,
- get_lang('TypeTextBelow').', '.get_lang('And').' '.get_lang('UseTagForBlank')
- );
- $form->addElement(
- 'html_editor',
- 'answer',
- Display::return_icon('fill_field.png'),
- ['id' => 'answer'],
- ['ToolbarSet' => 'TestQuestionDescription']
- );
- $form->addRule('answer', get_lang('GiveText'), 'required');
-
- $form->addElement('checkbox', 'multiple_answer', '', get_lang('FillInBlankSwitchable'));
- $form->addElement(
- 'select',
- 'select_separator',
- get_lang('SelectFillTheBlankSeparator'),
- self::getAllowedSeparatorForSelect(),
- ' id="select_separator" style="width:150px" class="selectpicker" onchange="changeBlankSeparator()" '
- );
- $form->addLabel(
- null,
- '<input type="button" onclick="updateBlanks()" value="'.get_lang('RefreshBlanks').'" class="btn btn-default" />'
- );
- $form->addHtml('<div id="blanks_weighting"></div>');
- global $text;
-
- $form->addHtml('<div id="defineoneblank" style="color:#D04A66; margin-left:160px">'.get_lang('DefineBlanks').'</div>');
- $form->addButtonSave($text, 'submitQuestion');
- if (!empty($this->id)) {
- $form->setDefaults($defaults);
- } else {
- if ($this->isContent == 1) {
- $form->setDefaults($defaults);
- }
- }
- }
-
- public function processAnswersCreation($form, $exercise)
- {
- $answer = $form->getSubmitValue('answer');
-
-
-
-
- $answer = str_replace('::', '', $answer);
-
- $answer = api_preg_replace("/\xc2\xa0/", " ", $answer);
-
- $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
- $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
- $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
- $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
-
- $answer = preg_replace_callback(
- "/".$blankStartSeparatorRegexp."[^]]+".$blankEndSeparatorRegexp."/",
- function ($matches) use ($blankStartSeparator, $blankEndSeparator) {
- $matchingResult = $matches[0];
- $matchingResult = trim($matchingResult, $blankStartSeparator);
- $matchingResult = trim($matchingResult, $blankEndSeparator);
- $matchingResult = trim($matchingResult);
-
- $matchingResult = str_replace("/\\/", "", $matchingResult);
- $matchingResult = str_replace('/"/', "", $matchingResult);
- return $blankStartSeparator.$matchingResult.$blankEndSeparator;
- },
- $answer
- );
-
- $nb = preg_match_all(
- '/'.$blankStartSeparatorRegexp.'[^'.$blankStartSeparatorRegexp.']*'.$blankEndSeparatorRegexp.'/',
- $answer,
- $blanks
- );
- if (isset($_GET['editQuestion'])) {
- $this->weighting = 0;
- }
-
- if ($nb > 0) {
- $answer .= '::';
-
- for ($i = 0; $i < $nb; $i++) {
-
- $answer .= $form->getSubmitValue('weighting['.$i.']');
-
- if ($i != $nb - 1) {
- $answer .= ',';
- }
-
- $this->weighting += (float) $form->getSubmitValue('weighting['.$i.']');
- }
-
- $answer .= ":";
- for ($i = 0; $i < $nb; $i++) {
-
- $answer .= $form->getSubmitValue('sizeofinput['.$i.']');
-
- if ($i != $nb - 1) {
- $answer .= ',';
- }
- }
- }
-
-
-
- $answer .= ':'.$form->getSubmitValue('select_separator');
-
- $is_multiple = $form->getSubmitValue('multiple_answer');
- $answer .= '@'.$is_multiple;
- $this->save($exercise);
- $objAnswer = new Answer($this->id);
- $objAnswer->createAnswer($answer, 0, '', 0, 1);
- $objAnswer->save();
- }
-
- public function return_header($exercise, $counter = null, $score = null)
- {
- $header = parent::return_header($exercise, $counter, $score);
- $header .= '<table class="'.$this->question_table_class.'">
- <tr>
- <th>'.get_lang('Answer').'</th>
- </tr>';
- return $header;
- }
-
- public static function getFillTheBlankHtml(
- $currentQuestion,
- $questionId,
- $correctItem,
- $attributes,
- $answer,
- $listAnswersInfo,
- $displayForStudent,
- $inBlankNumber,
- $labelId = ''
- ) {
- $inTabTeacherSolution = $listAnswersInfo['words'];
- $inTeacherSolution = $inTabTeacherSolution[$inBlankNumber];
- if (empty($labelId)) {
- $labelId = 'choice_id_'.$currentQuestion.'_'.$inBlankNumber;
- }
- switch (self::getFillTheBlankAnswerType($inTeacherSolution)) {
- case self::FILL_THE_BLANK_MENU:
- $selected = '';
-
-
-
- $listMenu = self::getFillTheBlankMenuAnswers(
- $inTeacherSolution,
- $displayForStudent
- );
- $resultOptions = ['' => '--'];
- foreach ($listMenu as $item) {
- $resultOptions[sha1($item)] = $item;
- }
- foreach ($resultOptions as $key => $value) {
- if ($correctItem == $value) {
- $selected = $key;
- break;
- }
- }
- $width = '';
- if (!empty($attributes['style'])) {
- $width = str_replace('width:', '', $attributes['style']);
- }
- $result = Display::select(
- "choice[$questionId][]",
- $resultOptions,
- $selected,
- [
- 'class' => 'selectpicker',
- 'data-width' => $width,
- 'id' => $labelId,
- ],
- false
- );
- break;
- case self::FILL_THE_BLANK_SEVERAL_ANSWER:
- case self::FILL_THE_BLANK_STANDARD:
- default:
- $attributes['id'] = $labelId;
- $result = Display::input(
- 'text',
- "choice[$questionId][]",
- $correctItem,
- $attributes
- );
- break;
- }
- return $result;
- }
-
- public static function getFillTheBlankMenuAnswers($correctAnswer, $displayForStudent)
- {
- $list = api_preg_split("/\|/", $correctAnswer);
- foreach ($list as &$item) {
- $item = self::trimOption($item);
- $item = api_html_entity_decode($item);
- }
-
- if ($displayForStudent) {
- shuffle_assoc($list);
- }
- return $list;
- }
-
- public static function getFillTheBlankMenuAnswerNum($correctAnswer, $studentAnswer)
- {
- $listChoices = self::getFillTheBlankMenuAnswers($correctAnswer, false);
- foreach ($listChoices as $num => $value) {
- if ($value == $studentAnswer) {
- return $num;
- }
- }
-
- return -1;
- }
-
- public static function getFillTheBlankSeveralAnswers($correctAnswer)
- {
-
- $listSeveral = api_preg_split("/\|\|/", $correctAnswer);
- return $listSeveral;
- }
-
- public static function isStudentAnswerGood($studentAnswer, $correctAnswer, $fromDatabase = false)
- {
- $result = false;
- switch (self::getFillTheBlankAnswerType($correctAnswer)) {
- case self::FILL_THE_BLANK_MENU:
- $listMenu = self::getFillTheBlankMenuAnswers($correctAnswer, false);
- if ($studentAnswer != '' && isset($listMenu[0])) {
-
- $item = $listMenu[0];
- if (!$fromDatabase) {
- $item = sha1($item);
- $studentAnswer = sha1($studentAnswer);
- }
- if ($item === $studentAnswer) {
- $result = true;
- }
- }
- break;
- case self::FILL_THE_BLANK_SEVERAL_ANSWER:
-
- $listSeveral = self::getFillTheBlankSeveralAnswers($correctAnswer);
- $listSeveral = array_map(
- function ($item) {
- return self::trimOption(api_html_entity_decode($item));
- },
- $listSeveral
- );
-
- $result = in_array($studentAnswer, $listSeveral);
- break;
- case self::FILL_THE_BLANK_STANDARD:
- default:
- $correctAnswer = api_html_entity_decode($correctAnswer);
-
- $result = $studentAnswer == self::trimOption($correctAnswer);
- break;
- }
- return $result;
- }
-
- public static function getFillTheBlankAnswerType($correctAnswer)
- {
- $type = self::FILL_THE_BLANK_STANDARD;
- if (api_strpos($correctAnswer, '|') && !api_strpos($correctAnswer, '||')) {
- $type = self::FILL_THE_BLANK_MENU;
- } elseif (api_strpos($correctAnswer, '||')) {
- $type = self::FILL_THE_BLANK_SEVERAL_ANSWER;
- }
- return $type;
- }
-
- public static function getAnswerInfo($userAnswer = '', $isStudentAnswer = false)
- {
- $listAnswerResults = [];
- $listAnswerResults['text'] = '';
- $listAnswerResults['words_count'] = 0;
- $listAnswerResults['words_with_bracket'] = [];
- $listAnswerResults['words'] = [];
- $listAnswerResults['weighting'] = [];
- $listAnswerResults['input_size'] = [];
- $listAnswerResults['switchable'] = '';
- $listAnswerResults['student_answer'] = [];
- $listAnswerResults['student_score'] = [];
- $listAnswerResults['blank_separator_number'] = 0;
- $listDoubleColon = [];
- api_preg_match("/(.*)::(.*)$/s", $userAnswer, $listResult);
- if (count($listResult) < 2) {
- $listDoubleColon[] = '';
- $listDoubleColon[] = '';
- } else {
- $listDoubleColon[] = $listResult[1];
- $listDoubleColon[] = $listResult[2];
- }
- $listAnswerResults['system_string'] = $listDoubleColon[1];
-
- $listArobaseSplit = explode('@', $listDoubleColon[1]);
- if (count($listArobaseSplit) < 2) {
- $listArobaseSplit[1] = '';
- }
-
- $listDetails = explode(':', $listArobaseSplit[0]);
-
- if (count($listDetails) < 3) {
- $listWeightings = explode(',', $listDetails[0]);
- $listSizeOfInput = [];
- for ($i = 0; $i < count($listWeightings); $i++) {
- $listSizeOfInput[] = 200;
- }
- $blankSeparatorNumber = 0;
- } else {
- $listWeightings = explode(',', $listDetails[0]);
- $listSizeOfInput = explode(',', $listDetails[1]);
- $blankSeparatorNumber = $listDetails[2];
- }
- $listAnswerResults['text'] = $listDoubleColon[0];
- $listAnswerResults['weighting'] = $listWeightings;
- $listAnswerResults['input_size'] = $listSizeOfInput;
- $listAnswerResults['switchable'] = $listArobaseSplit[1];
- $listAnswerResults['blank_separator_start'] = self::getStartSeparator($blankSeparatorNumber);
- $listAnswerResults['blank_separator_end'] = self::getEndSeparator($blankSeparatorNumber);
- $listAnswerResults['blank_separator_number'] = $blankSeparatorNumber;
- $blankCharStart = self::getStartSeparator($blankSeparatorNumber);
- $blankCharEnd = self::getEndSeparator($blankSeparatorNumber);
- $blankCharStartForRegexp = self::escapeForRegexp($blankCharStart);
- $blankCharEndForRegexp = self::escapeForRegexp($blankCharEnd);
-
- $listAnswerResults['words_count'] = api_preg_match_all(
- '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
- $listDoubleColon[0],
- $listWords
- );
- if ($listAnswerResults['words_count'] > 0) {
- $listAnswerResults['words_with_bracket'] = $listWords[0];
-
- array_walk(
- $listWords[0],
- function (&$value, $key, $tabBlankChar) {
- $trimChars = '';
- for ($i = 0; $i < count($tabBlankChar); $i++) {
- $trimChars .= $tabBlankChar[$i];
- }
- $value = trim($value, $trimChars);
- },
- [$blankCharStart, $blankCharEnd]
- );
- $listAnswerResults['words'] = $listWords[0];
- }
-
- $commonWords = api_preg_replace(
- '/'.$blankCharStartForRegexp.'[^'.$blankCharEndForRegexp.']*'.$blankCharEndForRegexp.'/',
- "::",
- $listDoubleColon[0]
- );
-
-
- $listBrackets = [];
- $listWords = [];
- if ($isStudentAnswer) {
- for ($i = 0; $i < count($listAnswerResults['words']); $i++) {
- $listBrackets[] = $listAnswerResults['words_with_bracket'][$i];
- $listWords[] = $listAnswerResults['words'][$i];
- if ($i + 1 < count($listAnswerResults['words'])) {
-
- $i++;
- }
- $listAnswerResults['student_answer'][] = $listAnswerResults['words'][$i];
- if ($i + 1 < count($listAnswerResults['words'])) {
-
- $i++;
- }
- $listAnswerResults['student_score'][] = $listAnswerResults['words'][$i];
- }
- $listAnswerResults['words'] = $listWords;
- $listAnswerResults['words_with_bracket'] = $listBrackets;
-
- $commonWords = api_preg_replace("/::::::/", '::', $commonWords);
- }
- $listAnswerResults['common_words'] = explode('::', $commonWords);
- return $listAnswerResults;
- }
-
- public static function getFillTheBlankResult(
- $testId,
- $questionId,
- $studentsIdList,
- $startDate,
- $endDate,
- $useLastAnsweredAttempt = true
- ) {
- $tblTrackEAttempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
- $tblTrackEExercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $courseId = api_get_course_int_id();
-
- if (empty($studentsIdList)) {
- return [];
- }
-
-
-
-
- $sql = 'SELECT * FROM '.$tblTrackEAttempt.' tea
- LEFT JOIN '.$tblTrackEExercise.' tee
- ON
- tee.exe_id = tea.exe_id AND
- tea.c_id = '.$courseId.' AND
- exe_exo_id = '.$testId.'
- WHERE
- tee.c_id = '.$courseId.' AND
- question_id = '.$questionId.' AND
- tea.user_id IN ('.implode(',', $studentsIdList).') AND
- tea.tms >= "'.$startDate.'" AND
- tea.tms <= "'.$endDate.'"
- ORDER BY user_id, tea.exe_id;
- ';
- $res = Database::query($sql);
- $userResult = [];
-
- while ($data = Database::fetch_array($res)) {
- $answer = self::getAnswerInfo($data['answer'], true);
-
- foreach ($answer['student_answer'] as $bracketNumber => $studentAnswer) {
- if ($answer['student_answer'][$bracketNumber] != '') {
-
- switch (self::getFillTheBlankAnswerType($answer['words'][$bracketNumber])) {
- case self::FILL_THE_BLANK_MENU:
-
-
-
- $userResult[$data['user_id']][$bracketNumber] = self::getFillTheBlankMenuAnswerNum(
- $answer['words'][$bracketNumber],
- $answer['student_answer'][$bracketNumber]
- );
- break;
- default:
- if (self::isStudentAnswerGood(
- $answer['student_answer'][$bracketNumber],
- $answer['words'][$bracketNumber]
- )
- ) {
- $userResult[$data['user_id']][$bracketNumber] = 0;
- } else {
- $userResult[$data['user_id']][$bracketNumber] = -1;
- }
- }
- } else {
-
- if ($useLastAnsweredAttempt) {
-
- if (!isset($userResult[$data['user_id']][$bracketNumber])) {
- $userResult[$data['user_id']][$bracketNumber] = -2;
- }
- } else {
-
- $userResult[$data['user_id']][$bracketNumber] = -2;
- }
- }
- }
- }
- return $userResult;
- }
-
- public static function getNbResultFillBlankAll($resultList)
- {
- $outRes = 0;
-
- foreach ($resultList as $list) {
- $found = false;
-
- foreach ($list as $choice) {
- if ($choice > -2 && !$found) {
- $outRes++;
- $found = true;
- }
- }
- }
- return $outRes;
- }
-
- public static function getAnswerInStudentAttempt($listWithStudentAnswer)
- {
- $separatorStart = $listWithStudentAnswer['blank_separator_start'];
- $separatorEnd = $listWithStudentAnswer['blank_separator_end'];
-
- $result = '';
- for ($i = 0; $i < count($listWithStudentAnswer['common_words']) - 1; $i++) {
- $answerValue = null;
- if (isset($listWithStudentAnswer['student_answer'][$i])) {
- $answerValue = $listWithStudentAnswer['student_answer'][$i];
- }
- $scoreValue = null;
- if (isset($listWithStudentAnswer['student_score'][$i])) {
- $scoreValue = $listWithStudentAnswer['student_score'][$i];
- }
- $result .= $listWithStudentAnswer['common_words'][$i];
- $result .= $listWithStudentAnswer['words_with_bracket'][$i];
- $result .= $separatorStart.$answerValue.$separatorEnd;
- $result .= $separatorStart.$scoreValue.$separatorEnd;
- }
- $result .= $listWithStudentAnswer['common_words'][$i];
- $result .= '::';
-
- $result .= $listWithStudentAnswer['system_string'];
- return $result;
- }
-
- public static function escapeForRegexp($inChar)
- {
- $listChars = [
- ".",
- "+",
- "*",
- "?",
- "[",
- "^",
- "]",
- "$",
- "(",
- ")",
- "{",
- "}",
- "=",
- "!",
- ">",
- "|",
- ":",
- "-",
- ")",
- ];
- if (in_array($inChar, $listChars)) {
- return "\\".$inChar;
- } else {
- return $inChar;
- }
- }
-
- public static function getRegexpProtected($text)
- {
- $listRegexpCharacters = [
- "/",
- ".",
- "+",
- "*",
- "?",
- "[",
- "^",
- "]",
- "$",
- "(",
- ")",
- "{",
- "}",
- "=",
- "!",
- ">",
- "|",
- ":",
- "-",
- ")",
- ];
- $result = $text;
- for ($i = 0; $i < count($listRegexpCharacters); $i++) {
- $result = str_replace($listRegexpCharacters[$i], "\\".$listRegexpCharacters[$i], $result);
- }
- return $result;
- }
-
- public static function getAllowedSeparator()
- {
- return [
- ['[', ']'],
- ['{', '}'],
- ['(', ')'],
- ['*', '*'],
- ['#', '#'],
- ['%', '%'],
- ['$', '$'],
- ];
- }
-
- public static function getStartSeparator($number)
- {
- $listSeparators = self::getAllowedSeparator();
- return $listSeparators[$number][0];
- }
-
- public static function getEndSeparator($number)
- {
- $listSeparators = self::getAllowedSeparator();
- return $listSeparators[$number][1];
- }
-
- public static function getAllowedSeparatorForSelect()
- {
- $listResults = [];
- $allowedSeparator = self::getAllowedSeparator();
- foreach ($allowedSeparator as $part) {
- $listResults[] = $part[0].'...'.$part[1];
- }
- return $listResults;
- }
-
- public function getDefaultSeparatorNumber($startSeparator, $endSeparator)
- {
- $listSeparators = self::getAllowedSeparator();
- $result = 0;
- for ($i = 0; $i < count($listSeparators); $i++) {
- if ($listSeparators[$i][0] == $startSeparator &&
- $listSeparators[$i][1] == $endSeparator
- ) {
- $result = $i;
- }
- }
- return $result;
- }
-
- public static function getHtmlDisplayForAnswer(
- $answer,
- $feedbackType,
- $resultsDisabled = false,
- $showTotalScoreAndUserChoices = false
- ) {
- $result = '';
- $listStudentAnswerInfo = self::getAnswerInfo($answer, true);
- if (in_array($resultsDisabled, [
- RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT,
- RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK,
- ]
- )
- ) {
- $resultsDisabled = true;
- if ($showTotalScoreAndUserChoices) {
- $resultsDisabled = false;
- }
- }
-
-
- for ($i = 0; $i < count($listStudentAnswerInfo['student_answer']); $i++) {
- if ($listStudentAnswerInfo['student_score'][$i] == 1) {
- $listStudentAnswerInfo['student_answer'][$i] = self::getHtmlRightAnswer(
- $listStudentAnswerInfo['student_answer'][$i],
- $listStudentAnswerInfo['words'][$i],
- $feedbackType,
- $resultsDisabled,
- $showTotalScoreAndUserChoices
- );
- } else {
- $listStudentAnswerInfo['student_answer'][$i] = self::getHtmlWrongAnswer(
- $listStudentAnswerInfo['student_answer'][$i],
- $listStudentAnswerInfo['words'][$i],
- $feedbackType,
- $resultsDisabled,
- $showTotalScoreAndUserChoices
- );
- }
- }
-
- for ($i = 0; $i < count($listStudentAnswerInfo['common_words']); $i++) {
- $result .= isset($listStudentAnswerInfo['common_words'][$i]) ? $listStudentAnswerInfo['common_words'][$i] : '';
- $studentLabel = isset($listStudentAnswerInfo['student_answer'][$i]) ? $listStudentAnswerInfo['student_answer'][$i] : '';
- $result .= $studentLabel;
- }
-
- $result .= isset($listStudentAnswerInfo['common_words'][$i]) ? $listStudentAnswerInfo['common_words'][$i] : '';
- return $result;
- }
-
- public static function getHtmlAnswer(
- $answer,
- $correct,
- $right,
- $feedbackType,
- $resultsDisabled = false,
- $showTotalScoreAndUserChoices = false
- ) {
- $hideExpectedAnswer = false;
- $hideUserSelection = false;
- switch ($resultsDisabled) {
- case RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER:
- $hideUserSelection = true;
- break;
- case RESULT_DISABLE_SHOW_SCORE_ONLY:
- if ($feedbackType == 0) {
- $hideExpectedAnswer = true;
- }
- break;
- case RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK:
- case RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT:
- $hideExpectedAnswer = true;
- if ($showTotalScoreAndUserChoices) {
- $hideExpectedAnswer = false;
- }
- break;
- }
- $style = 'feedback-green';
- $iconAnswer = Display::return_icon('attempt-check.png', get_lang('Correct'), null, ICON_SIZE_SMALL);
- if (!$right) {
- $style = 'feedback-red';
- $iconAnswer = Display::return_icon('attempt-nocheck.png', get_lang('Incorrect'), null, ICON_SIZE_SMALL);
- }
- $correctAnswerHtml = '';
- $type = self::getFillTheBlankAnswerType($correct);
- switch ($type) {
- case self::FILL_THE_BLANK_MENU:
- $listPossibleAnswers = self::getFillTheBlankMenuAnswers($correct, false);
- $correctAnswerHtml .= "<span class='correct-answer'><strong>".$listPossibleAnswers[0]."</strong>";
- $correctAnswerHtml .= ' (';
- for ($i = 1; $i < count($listPossibleAnswers); $i++) {
- $correctAnswerHtml .= $listPossibleAnswers[$i];
- if ($i != count($listPossibleAnswers) - 1) {
- $correctAnswerHtml .= ' | ';
- }
- }
- $correctAnswerHtml .= ")</span>";
- break;
- case self::FILL_THE_BLANK_SEVERAL_ANSWER:
- $listCorrects = explode('||', $correct);
- $firstCorrect = $correct;
- if (count($listCorrects) > 0) {
- $firstCorrect = $listCorrects[0];
- }
- $correctAnswerHtml = "<span class='correct-answer'>".$firstCorrect."</span>";
- break;
- case self::FILL_THE_BLANK_STANDARD:
- default:
- $correctAnswerHtml = "<span class='correct-answer'>".$correct."</span>";
- }
- if ($hideExpectedAnswer) {
- $correctAnswerHtml = "<span
- class='feedback-green'
- title='".get_lang('ExerciseWithFeedbackWithoutCorrectionComment')."'> — </span>";
- }
- $result = "<span class='feedback-question'>";
- if ($hideUserSelection === false) {
- $result .= $iconAnswer."<span class='$style'>".$answer."</span>";
- }
- $result .= "<span class='feedback-separator'>|</span>";
- $result .= $correctAnswerHtml;
- $result .= '</span>';
- return $result;
- }
-
- public static function getHtmlRightAnswer(
- $answer,
- $correct,
- $feedbackType,
- $resultsDisabled = false,
- $showTotalScoreAndUserChoices = false
- ) {
- return self::getHtmlAnswer(
- $answer,
- $correct,
- true,
- $feedbackType,
- $resultsDisabled,
- $showTotalScoreAndUserChoices
- );
- }
-
- public static function getHtmlWrongAnswer(
- $answer,
- $correct,
- $feedbackType,
- $resultsDisabled = false,
- $showTotalScoreAndUserChoices = false
- ) {
- return self::getHtmlAnswer(
- $answer,
- $correct,
- false,
- $feedbackType,
- $resultsDisabled,
- $showTotalScoreAndUserChoices
- );
- }
-
- public static function isCorrect($answerText)
- {
- $answerInfo = self::getAnswerInfo($answerText, true);
- $correctAnswerList = $answerInfo['words'];
- $studentAnswer = $answerInfo['student_answer'];
- $isCorrect = true;
- foreach ($correctAnswerList as $i => $correctAnswer) {
- $value = self::isStudentAnswerGood($studentAnswer[$i], $correctAnswer);
- $isCorrect = $isCorrect && $value;
- }
- return $isCorrect;
- }
-
- public static function clearStudentAnswer($answer)
- {
- $answer = htmlentities(api_utf8_encode($answer), ENT_QUOTES);
- $answer = str_replace(''', ''', $answer);
- $answer = api_preg_replace('/\s\s+/', ' ', $answer);
- $answer = strtr($answer, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
- return trim($answer);
- }
-
- private static function trimOption($text)
- {
- $text = trim($text);
- $text = preg_replace("/\s+/", ' ', $text);
- return $text;
- }
- }
|