CalculatedAnswer::isAnswered()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 17
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Webit\Util\EvalMath\EvalMath;
6
7
/**
8
 *  Class CalculatedAnswer
9
 *  This class contains calculated answer form and answer processing functions.
10
 *
11
 *  @author Imanol Losada
12
 */
13
class CalculatedAnswer extends Question
14
{
15
    public $typePicture = 'calculated_answer.png';
16
    public $explanationLangVar = 'CalculatedAnswer';
17
18
    /**
19
     * Constructor.
20
     */
21
    public function __construct()
22
    {
23
        parent::__construct();
24
        $this->type = CALCULATED_ANSWER;
25
        $this->isContent = $this->getIsContent();
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function createAnswersForm($form)
32
    {
33
        $defaults = [];
34
        $defaults['answer'] = get_lang('DefaultTextInBlanks');
35
        if (!empty($this->iid)) {
36
            $objAnswer = new Answer($this->iid);
37
            $preArray = explode('@@', $objAnswer->selectAnswer(1));
38
            $defaults['formula'] = array_pop($preArray);
39
            $defaults['answer'] = array_shift($preArray);
40
            $defaults['answer'] = preg_replace("/\[.*\]/", '', $defaults['answer']);
41
            $defaults['weighting'] = $this->weighting;
42
        }
43
        $lowestValue = '1.00';
44
        $highestValue = '20.00';
45
46
        // javascript //
47
        echo '<script>
48
            function parseTextNumber(textNumber, floatValue) {
49
                if (textNumber.indexOf(".") > -1) {
50
                    textNumber = parseFloat(textNumber);
51
                    floatValue.exists = "true";
52
                } else {
53
                    textNumber = parseInt(textNumber);
54
                }
55
                return textNumber;
56
            }
57
58
            function updateRandomValue(element) {
59
                // "floatValue" helps to distinguish between an integer (10) and a float with all 0 decimals (10.00)
60
                var floatValue = { exists: "false" };
61
                var index = (element.name).match(/\[[^\]]*\]/g);
62
                var lowestValue = parseTextNumber(document.getElementById("lowestValue"+index).value, floatValue);
63
                var highestValue = parseTextNumber(document.getElementById("highestValue"+index).value, floatValue);
64
                var result = Math.random() * (highestValue - lowestValue) + lowestValue;
65
                if (floatValue.exists == "true") {
66
                    result = parseFloat(result).toFixed(2);
67
                } else {
68
                    result = parseInt(result);
69
                }
70
                document.getElementById("randomValue"+index).innerHTML = "'.get_lang("ExampleValue").': " + result;
71
           }
72
73
            CKEDITOR.on("instanceCreated", function(e) {
74
                if (e.editor.name === "answer") {
75
                    e.editor.on("change", updateBlanks);
76
                }
77
            });
78
79
            var firstTime = true;
80
            function updateBlanks(e) {
81
                if (firstTime) {
82
                    field = document.getElementById("answer");
83
                    var answer = field.value;
84
                } else {
85
                    var answer = e.editor.getData();
86
                }
87
                var blanks = answer.match(/\[[^\]]*\]/g);
88
                var fields = "<div class=\"form-group\"><label class=\"col-sm-2\">'.get_lang('VariableRanges').'</label><div class=\"col-sm-8\"><table>";
89
                if (blanks!=null) {
90
                    if (typeof updateBlanks.randomValues === "undefined") {
91
                        updateBlanks.randomValues = [];
92
                    }
93
                    for (i=0 ; i<blanks.length ; i++){
94
                        if (document.getElementById("lowestValue["+i+"]") && document.getElementById("highestValue["+i+"]")) {
95
                            lowestValue = document.getElementById("lowestValue["+i+"]").value;
96
                            highestValue = document.getElementById("highestValue["+i+"]").value;
97
                        } else {
98
                            lowestValue = '.$lowestValue.'.toFixed(2);
99
                            highestValue = '.$highestValue.'.toFixed(2);
100
                            for (j=0; j<blanks.length; j++) {
101
                                updateBlanks.randomValues[j] = parseFloat(Math.random() * (highestValue - lowestValue) + lowestValue).toFixed(2);
102
                            }
103
                        }
104
                        fields += "<tr><td><label>"+blanks[i]+"</label></td><td><input class=\"span1\" style=\"margin-left: 0em;\" size=\"5\" value=\""+lowestValue+"\" type=\"text\" id=\"lowestValue["+i+"]\" name=\"lowestValue["+i+"]\" onblur=\"updateRandomValue(this)\"/></td><td><input class=\"span1\" style=\"margin-left: 0em; width:80px;\" size=\"5\" value=\""+highestValue+"\" type=\"text\" id=\"highestValue["+i+"]\" name=\"highestValue["+i+"]\" onblur=\"updateRandomValue(this)\"/></td><td><label class=\"span3\" id=\"randomValue["+i+"]\"/>'.get_lang('ExampleValue').': "+updateBlanks.randomValues[i]+"</label></td></tr>";
105
                    }
106
                }
107
                document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>";
108
                if (firstTime) {
109
                    firstTime = false;
110
                }
111
            }
112
113
            window.onload = updateBlanks;
114
115
        </script>';
116
117
        // answer
118
        $form->addElement('label', null, '<br /><br />'.get_lang('TypeTextBelow').', '.get_lang('And').' '.get_lang('UseTagForBlank'));
119
        $form->addElement(
120
            'html_editor',
121
            'answer',
122
            Display::return_icon('fill_field.png'),
123
            [
124
                'id' => 'answer',
125
                'onkeyup' => 'javascript: updateBlanks(this);',
126
            ],
127
            [
128
                'ToolbarSet' => 'TestQuestionDescription',
129
                'Width' => '100%',
130
                'Height' => '350',
131
            ]
132
        );
133
134
        $form->addRule('answer', get_lang('GiveText'), 'required');
135
        $form->addRule('answer', get_lang('DefineBlanks'), 'regex', '/\[.*\]/');
136
        $form->applyFilter('answer', 'attr_on_filter');
137
138
        $form->addElement('label', null, get_lang('IfYouWantOnlyIntegerValuesWriteBothLimitsWithoutDecimals'));
139
        $form->addElement('html', '<div id="blanks_weighting"></div>');
140
141
        $notationListButton = Display::url(
142
            get_lang('NotationList'),
143
            api_get_path(WEB_CODE_PATH).'exercise/evalmathnotation.php',
144
            [
145
                'class' => 'btn btn-info ajax',
146
                'data-title' => get_lang('NotationList'),
147
                '_target' => '_blank',
148
            ]
149
        );
150
        $form->addElement(
151
            'label',
152
            null,
153
            $notationListButton
154
        );
155
156
        $form->addElement('text', 'formula', [get_lang('Formula'), get_lang('FormulaExample')], ['id' => 'formula']);
157
        $form->addRule('formula', get_lang('GiveFormula'), 'required');
158
159
        $form->addElement('text', 'weighting', get_lang('Weighting'), ['id' => 'weighting']);
160
        $form->setDefaults(['weighting' => '10']);
161
162
        $form->addElement('text', 'answerVariations', get_lang('AnswerVariations'));
163
        $form->addRule(
164
            'answerVariations',
165
            get_lang('GiveAnswerVariations'),
166
            'required'
167
        );
168
        $form->setDefaults(['answerVariations' => '1']);
169
170
        global $text;
171
        // setting the save button here and not in the question class.php
172
        $form->addButtonSave($text, 'submitQuestion');
173
174
        if (!empty($this->iid)) {
175
            $form->setDefaults($defaults);
176
        } else {
177
            if ($this->isContent == 1) {
178
                $form->setDefaults($defaults);
179
            }
180
        }
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186
    public function processAnswersCreation($form, $exercise)
187
    {
188
        if (!self::isAnswered()) {
0 ignored issues
show
Bug Best Practice introduced by
The method CalculatedAnswer::isAnswered() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

188
        if (!self::/** @scrutinizer ignore-call */ isAnswered()) {
Loading history...
189
            $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
190
            Database::delete(
191
                $table,
192
                [
193
                    'question_id = ?' => [
194
                        $this->iid,
195
                    ],
196
                ]
197
            );
198
            $answer = $form->getSubmitValue('answer');
199
            $formula = $form->getSubmitValue('formula');
200
            $lowestValues = $form->getSubmitValue('lowestValue');
201
            $highestValues = $form->getSubmitValue('highestValue');
202
            $answerVariations = $form->getSubmitValue('answerVariations');
203
            $this->weighting = $form->getSubmitValue('weighting');
204
205
            // Create as many answers as $answerVariations
206
            for ($j = 0; $j < $answerVariations; $j++) {
207
                $auxAnswer = $answer;
208
                $auxFormula = $formula;
209
                $nb = preg_match_all('/\[[^\]]*\]/', $auxAnswer, $blanks);
210
                if ($nb > 0) {
211
                    for ($i = 0; $i < $nb; $i++) {
212
                        $blankItem = $blanks[0][$i];
213
214
                        // take random float values when one or both edge values have a decimal point
215
                        $randomValue =
216
                            (strpos($lowestValues[$i], '.') !== false ||
217
                            strpos($highestValues[$i], '.') !== false) ?
218
                            mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
219
220
                        $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
221
                        $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
222
                    }
223
                    $math = new EvalMath();
224
                    $result = $math->evaluate($auxFormula);
225
                    $result = number_format($result, 2, '.', '');
226
                    // Remove decimal trailing zeros
227
                    $result = rtrim($result, '0');
228
                    // If it is an integer (ends in .00) remove the decimal point
229
                    if (mb_substr($result, -1) === '.') {
230
                        $result = str_replace('.', '', $result);
231
                    }
232
                    // Attach formula
233
                    $auxAnswer .= " [".$result."]@@".$formula;
234
                }
235
                $this->save($exercise);
236
                $objAnswer = new Answer($this->iid);
237
                $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
238
                $objAnswer->position = [];
239
                $objAnswer->save();
240
            }
241
        }
242
    }
243
244
    /**
245
     * {@inheritdoc}
246
     */
247
    public function return_header(Exercise $exercise, $counter = null, $score = [])
248
    {
249
        $header = parent::return_header($exercise, $counter, $score);
250
        $header .= '<table class="'.$this->question_table_class.'"><tr>';
251
        $header .= '<th>'.get_lang('Answer').'</th>';
252
        if ($exercise->showExpectedChoice()) {
253
            $header .= '<th>'.get_lang('YourChoice').'</th>';
254
            if ($exercise->showExpectedChoiceColumn()) {
255
                $header .= '<th>'.get_lang('ExpectedChoice').'</th>';
256
            }
257
            $header .= '<th>'.get_lang('Status').'</th>';
258
        }
259
        $header .= '</tr>';
260
261
        return $header;
262
    }
263
264
    /**
265
     * Returns true if the current question has been attempted to be answered.
266
     *
267
     * @return bool
268
     */
269
    public function isAnswered()
270
    {
271
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
272
        $result = Database::select(
273
            'question_id',
274
            $table,
275
            [
276
                'where' => [
277
                    'question_id = ? AND c_id = ?' => [
278
                        $this->iid,
279
                        $this->course['real_id'],
280
                    ],
281
                ],
282
            ]
283
        );
284
285
        return empty($result) ? false : true;
286
    }
287
}
288