• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

FormulasQuestion / moodle-qtype_formulas / 25756686224

12 May 2026 07:16PM UTC coverage: 97.465% (-0.03%) from 97.498%
25756686224

Pull #326

github

web-flow
Merge a4e5efa66 into eb60bc71b
Pull Request #326: Improve feedback in adaptive mode

19 of 19 new or added lines in 1 file covered. (100.0%)

2 existing lines in 1 file now uncovered.

4613 of 4733 relevant lines covered (97.46%)

1143.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.94
/renderer.php
1
<?php
2
// This file is part of Moodle - https://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
16

17
use qtype_formulas\local\formulas_part;
18

19
/**
20
 * Formulas question renderer class.
21
 *
22
 * @package    qtype_formulas
23
 * @copyright  2009 The Open University
24
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
26

27
/**
28
 * Base class for generating the bits of output for formulas questions.
29
 *
30
 * @copyright  2009 The Open University
31
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32
 */
33
class qtype_formulas_renderer extends qtype_with_combined_feedback_renderer {
34
    /** @var string */
35
    const UNIT_FIELD = 'u';
36

37
    /** @var string */
38
    const COMBINED_FIELD = '';
39

40
    /**
41
     * Generate the display of the formulation part of the question. This is the area that
42
     * contains the question text and the controls for students to input their answers.
43
     * Once the question is answered, it will contain the green tick or the red cross and
44
     * the part's general / combined feedback.
45
     *
46
     * @param question_attempt $qa the question attempt to display.
47
     * @param question_display_options $options controls what should and should not be displayed.
48
     * @return ?string HTML fragment.
49
     */
50
    public function formulation_and_controls(question_attempt $qa, question_display_options $options): ?string {
51
        // First, fetch the instantiated question from the attempt.
52
        /** @var qtype_formulas_question $question */
53
        $question = $qa->get_question();
1,573✔
54

55
        if (count($question->textfragments) !== $question->numparts + 1) {
1,573✔
56
            $this->output->notification(get_string('error_question_damaged', 'qtype_formulas'), 'error');
×
57
            return null;
×
58
        }
59

60
        $questiontext = '';
1,573✔
61
        // First, iterate over all parts, put the corresponding fragment of the main question text at the
62
        // right position, followed by the part's text, input and (if applicable) feedback elements.
63
        foreach ($question->parts as $part) {
1,573✔
64
            $questiontext .= $question->format_text(
1,573✔
65
                $question->textfragments[$part->partindex],
1,573✔
66
                $question->questiontextformat,
1,573✔
67
                $qa,
1,573✔
68
                'question',
1,573✔
69
                'questiontext',
1,573✔
70
                $question->id,
1,573✔
71
                false,
1,573✔
72
            );
1,573✔
73
            $questiontext .= $this->part_formulation_and_controls($qa, $options, $part);
1,573✔
74
        }
75
        // All parts are done. We now append the final fragment of the main question text. Note that this fragment
76
        // might be empty.
77
        $questiontext .= $question->format_text(
1,573✔
78
            end($question->textfragments),
1,573✔
79
            $question->questiontextformat,
1,573✔
80
            $qa,
1,573✔
81
            'question',
1,573✔
82
            'questiontext',
1,573✔
83
            $question->id,
1,573✔
84
            false,
1,573✔
85
        );
1,573✔
86

87
        // Pack everything in a <div> and, if the question is in an invalid state, append the appropriate error message
88
        // at the very end.
89
        $result = html_writer::tag('div', $questiontext, ['class' => 'qtext']);
1,573✔
90
        if ($qa->get_state() == question_state::$invalid) {
1,573✔
91
            $result .= html_writer::nonempty_tag(
26✔
92
                'div',
26✔
93
                $question->get_validation_error($qa->get_last_qt_data()),
26✔
94
                ['class' => 'validationerror']
26✔
95
            );
26✔
96
        }
97

98
        return $result;
1,573✔
99
    }
100

101
    /**
102
     * Return HTML that needs to be included in the page's <head> when this
103
     * question is used.
104
     *
105
     * @param question_attempt $qa question attempt that will be displayed on the page
106
     * @return string HTML fragment
107
     */
108
    public function head_code(question_attempt $qa): string {
109
        $this->page->requires->js_call_amd(
×
110
            'qtype_formulas/answervalidation',
×
111
            'init',
×
112
            [get_config('qtype_formulas', 'debouncedelay')]
×
113
        );
×
114
        $this->page->requires->js_call_amd(
×
115
            'qtype_formulas/tooltip',
×
116
            'init',
×
117
        );
×
118

119
        return '';
×
120
    }
121

122
    /**
123
     * Return the part text, controls, grading details and feedbacks.
124
     *
125
     * @param question_attempt $qa question attempt that will be displayed on the page
126
     * @param question_display_options $options controls what should and should not be displayed
127
     * @param formulas_part $part question part
128
     * @return void
129
     */
130
    public function part_formulation_and_controls(
131
        question_attempt $qa,
132
        question_display_options $options,
133
        formulas_part $part
134
    ): string {
135

136
        // The behaviour might change the display options per part, so it is safer to clone them here.
137
        $partoptions = clone $options;
1,573✔
138
        if ($qa->get_behaviour_name() === 'adaptivemultipart') {
1,573✔
139
            $qa->get_behaviour()->adjust_display_options_for_part($part->partindex, $partoptions);
65✔
140
        }
141

142
        // Fetch information about the outcome: grade, feedback symbol, CSS class to be used.
143
        $outcomedata = $this->get_part_feedback_class_and_symbol($qa, $partoptions, $part);
1,573✔
144

145
        // First of all, we take the part's question text and its input fields.
146
        $output = $this->get_part_formulation($qa, $partoptions, $part, $outcomedata);
1,573✔
147

148
        // If the user has requested the feedback symbol to be placed at a special position, we
149
        // do that now. Otherwise, we just append it after the part's text and input boxes.
150
        if (strpos($output, '{_m}') !== false) {
1,573✔
151
            $output = str_replace('{_m}', $outcomedata->feedbacksymbol, $output);
×
152
        } else {
153
            $output .= $outcomedata->feedbacksymbol;
1,573✔
154
        }
155

156
        // The part's feedback consists of the combined feedback (correct, partially correct, incorrect -- depending on the
157
        // outcome) and the general feedback which is given in all cases.
158
        $feedback = $this->part_combined_feedback($qa, $partoptions, $part, $outcomedata->fraction);
1,573✔
159
        $feedback .= $this->part_general_feedback($qa, $partoptions, $part);
1,573✔
160

161
        // If requested, the correct answer should be appended to the feedback.
162
        if ($partoptions->rightanswer) {
1,573✔
163
            $feedback .= $this->part_correct_response($part);
234✔
164
        }
165

166
        // If the current response is a real submission (or identical to one), we put all feedback into a
167
        // <div> with the appropriate CSS class and append it to the output.
168
        if ($this->response_is_same_as_submitted($qa, $part)) {
1,573✔
169
            $output .= html_writer::nonempty_tag('div', $feedback, ['class' => 'formulaspartoutcome outcome']);
299✔
170
        }
171

172
        return html_writer::tag('div', $output, ['class' => 'formulaspart']);
1,573✔
173
    }
174

175
    /**
176
     * Return class and symbol for the part feedback.
177
     *
178
     * @param question_attempt $qa question attempt that will be displayed on the page
179
     * @param question_display_options $options controls what should and should not be displayed
180
     * @param formulas_part $part question part
181
     * @return stdClass
182
     */
183
    public function get_part_feedback_class_and_symbol(
184
        question_attempt $qa,
185
        question_display_options $options,
186
        formulas_part $part
187
    ): stdClass {
188
        // Prepare a new object to hold the different elements.
189
        $result = new stdClass();
1,573✔
190

191
        // Fetch the last response data and grade it.
192
        $response = $qa->get_last_qt_data();
1,573✔
193
        ['answer' => $answergrade, 'unit' => $unitcorrect] = $part->grade($response);
1,573✔
194

195
        // The fraction will later be used to determine which feedback (correct, partially correct or incorrect)
196
        // to use. We have to take into account a possible deduction for a wrong unit.
197
        $result->fraction = $answergrade;
1,573✔
198
        if ($unitcorrect === false) {
1,573✔
199
            $result->fraction *= (1 - $part->unitpenalty);
949✔
200
        }
201

202
        // By default, we add no feedback at all...
203
        $result->feedbacksymbol = '';
1,573✔
204
        $result->feedbackclass = '';
1,573✔
205
        // ... unless correctness is requested in the display options.
206
        // Note that no feedback should be given, if the response has been modified since the last submission,
207
        // i. e. it is just a response that was saved during page navigation.
208
        if ($this->response_is_same_as_submitted($qa, $part) && $options->correctness) {
1,573✔
209
            $result->feedbacksymbol = $this->feedback_image($result->fraction);
286✔
210
            $result->feedbackclass = $this->feedback_class($result->fraction);
286✔
211
        }
212
        return $result;
1,573✔
213
    }
214

215
    /**
216
     * Format given number according to numbering style, e. g. abc or 123.
217
     *
218
     * @param int $num number
219
     * @param string $style style to render the number in, acccording to {@see qtype_multichoice::get_numbering_styles()}
220
     * @return string number $num in the requested style
221
     */
222
    protected static function number_in_style(int $num, string $style): string {
223
        switch ($style) {
224
            case 'abc':
39✔
225
                $number = chr(ord('a') + $num);
26✔
226
                break;
26✔
227
            case 'ABCD':
13✔
228
                $number = chr(ord('A') + $num);
×
229
                break;
×
230
            case '123':
13✔
231
                $number = $num + 1;
×
232
                break;
×
233
            case 'iii':
13✔
234
                $number = question_utils::int_to_roman($num + 1);
×
235
                break;
×
236
            case 'IIII':
13✔
237
                $number = strtoupper(question_utils::int_to_roman($num + 1));
×
238
                break;
×
239
            case 'none':
13✔
240
                return '';
×
241
            default:
242
                // Default similar to none for compatibility with old questions.
243
                return '';
13✔
244
        }
245
        return $number . '. ';
26✔
246
    }
247

248
    /**
249
     * Create a set of radio boxes for a multiple choice answer input.
250
     *
251
     * @param formulas_part $part question part
252
     * @param int|string $answerindex index of the answer (starting at 0) or special value for combined/separate unit field
253
     * @param question_attempt $qa question attempt that will be displayed on the page
254
     * @param array $answeroptions array of strings containing the answer options to choose from
255
     * @param bool $shuffle whether the options should be shuffled
256
     * @param question_display_options $displayoptions controls what should and should not be displayed
257
     * @param string $feedbackclass
258
     * @return string HTML fragment
259
     */
260
    protected function create_radio_mc_answer(
261
        formulas_part $part,
262
        $answerindex,
263
        question_attempt $qa,
264
        array $answeroptions,
265
        bool $shuffle,
266
        question_display_options $displayoptions,
267
        string $feedbackclass = ''
268
    ): string {
269
        /** @var qtype_formulas_question $question */
270
        $question = $qa->get_question();
39✔
271

272
        $variablename = "{$part->partindex}_{$answerindex}";
39✔
273
        $currentanswer = $qa->get_last_qt_var($variablename);
39✔
274
        $inputname = $qa->get_qt_field_name($variablename);
39✔
275

276
        $inputattributes['type'] = 'radio';
39✔
277
        $inputattributes['name'] = $inputname;
39✔
278
        if ($displayoptions->readonly) {
39✔
279
            $inputattributes['disabled'] = 'disabled';
13✔
280
        }
281

282
        // First, we open a <fieldset> around the entire group of options.
283
        $output = html_writer::start_tag('fieldset', ['class' => 'multichoice_answer']);
39✔
284

285
        // Inside the fieldset, we put the accessibility label, following the example of core's multichoice
286
        // question type, i. e. the label is inside a <span> with class 'sr-only', wrapped in a <legend>.
287
        // TODO: we should use visually-hidden after dropping Moodle 4.5.
288
        $output .= html_writer::start_tag('legend', ['class' => 'sr-only']);
39✔
289
        $output .= html_writer::span(
39✔
290
            $this->generate_accessibility_label_text($answerindex, $part->numbox, $part->partindex, $question->numparts),
39✔
291
            'sr-only'
39✔
292
        );
39✔
293
        $output .= html_writer::end_tag('legend');
39✔
294

295
        // If needed, shuffle the options while maintaining the keys.
296
        if ($shuffle) {
39✔
297
            $keys = array_keys($answeroptions);
13✔
298
            shuffle($keys);
13✔
299

300
            $shuffledoptions = [];
13✔
301
            foreach ($keys as $key) {
13✔
302
                $shuffledoptions[$key] = $answeroptions[$key];
13✔
303
            }
304
            $answeroptions = $shuffledoptions;
13✔
305
        }
306

307
        // Iterate over all options.
308
        foreach ($answeroptions as $i => $optiontext) {
39✔
309
            $numbering = html_writer::span(self::number_in_style($i, $question->answernumbering), 'answernumber');
39✔
310
            $labeltext = $question->format_text(
39✔
311
                $numbering . $optiontext,
39✔
312
                $part->subqtextformat,
39✔
313
                $qa,
39✔
314
                'qtype_formulas',
39✔
315
                'answersubqtext',
39✔
316
                $part->id,
39✔
317
                false,
39✔
318
            );
39✔
319

320
            $inputattributes['id'] = $inputname . '_' . $i;
39✔
321
            $inputattributes['value'] = $i;
39✔
322
            // Class ml-3 is Bootstrap's class for margin-left: 1rem; it used to be m-l-1.
323
            $label = $this->create_label_for_input($labeltext, $inputattributes['id'], ['class' => 'ml-3']);
39✔
324
            $inputattributes['aria-labelledby'] = $label['id'];
39✔
325

326
            // We must make sure $currentanswer is not null, because otherwise the first radio box
327
            // might be selected if there is no answer at all. It seems better to avoid strict equality,
328
            // because we might compare a string to a number.
329
            $isselected = ($i == $currentanswer && !is_null($currentanswer));
39✔
330

331
            // We do not reset the $inputattributes array on each iteration, so we have to add/remove the
332
            // attribute every time.
333
            if ($isselected) {
39✔
334
                $inputattributes['checked'] = 'checked';
13✔
335
            } else {
336
                unset($inputattributes['checked']);
39✔
337
            }
338

339
            // Each option (radio box element plus label) is wrapped in its own <div> element.
340
            $divclass = 'r' . ($i % 2);
39✔
341
            if ($displayoptions->correctness && $isselected) {
39✔
342
                $divclass .= ' ' . $feedbackclass;
13✔
343
            }
344
            $output .= html_writer::start_div($divclass);
39✔
345

346
            // Now add the <input> tag and its <label>.
347
            $output .= html_writer::empty_tag('input', $inputattributes);
39✔
348
            $output .= $label['html'];
39✔
349

350
            // Close the option's <div>.
351
            $output .= html_writer::end_div();
39✔
352
        }
353

354
        // Close the option group's <fieldset>.
355
        $output .= html_writer::end_tag('fieldset');
39✔
356

357
        return $output;
39✔
358
    }
359

360
    /**
361
     * Translate an array containing formatting options into a CSS format string, e. g. from
362
     * ['w' => '50px', 'bgcol' => 'yellow'] to 'width: 50px; background-color: yellow'. Note:
363
     * - colors can be defined in 3 or 6 digit hex RGB, in 4 or 8 digit hex RGBA or as CSS named color
364
     * - widths can be defined as a number followed by the units px, rem or em; if the unit is omitted, rem will be used
365
     * - alignment can be defined as left, right, center, start or end
366
     *
367
     * @param array $options associative array containing options (in our own denomination) and their settings
368
     * @return string
369
     */
370
    protected function get_css_properties(array $options): string {
371
        // Define some regex pattern.
372
        $hexcolor = '#([0-9A-F]{8}|[0-9A-F]{6}|[0-9A-F]{3}|[0-9A-F]{4})';
1,521✔
373
        $namedcolor = '[A-Z]+';
1,521✔
374
        // We accept floating point numbers with or without a leading integer part and integers.
375
        // Floating point numbers with a trailing decimal point do not work in all browsers.
376
        $length = '(\d+\.\d+|\d*\.\d+|\d+)(px|em|rem)?';
1,521✔
377
        $alignment = 'start|end|left|right|center';
1,521✔
378

379
        $styles = [];
1,521✔
380
        foreach ($options as $name => $value) {
1,521✔
381
            switch ($name) {
382
                case 'bgcol':
1,521✔
383
                    if (!preg_match("/^(($hexcolor)|($namedcolor))$/i", $value)) {
377✔
384
                        break;
26✔
385
                    }
386
                    $styles[] = "background-color: $value";
351✔
387
                    break;
351✔
388
                case 'txtcol':
1,521✔
389
                    if (!preg_match("/^(($hexcolor)|($namedcolor))$/i", $value)) {
156✔
390
                        break;
26✔
391
                    }
392
                    $styles[] = "color: $value";
130✔
393
                    break;
130✔
394
                case 'w':
1,521✔
395
                    if (!preg_match("/^($length)$/i", $value)) {
1,521✔
396
                        break;
104✔
397
                    }
398
                    // If no unit is given, append rem.
399
                    $styles[] = "width: $value" . (preg_match('/\d$/', $value) ? 'rem' : '');
1,469✔
400
                    break;
1,469✔
401
                case 'align':
169✔
402
                    if (!preg_match("/^($alignment)$/i", $value)) {
169✔
403
                        break;
26✔
404
                    }
405
                    $styles[] = "text-align: $value";
143✔
406
                    break;
143✔
407
            }
408
        }
409

410
        return implode(';', $styles);
1,521✔
411
    }
412

413
    /**
414
     * Create a <label> element for a given input control (e. g. a text field). Returns the
415
     * HTML and the label's ID.
416
     *
417
     * @param string $text the label's text
418
     * @param string $inputid ID of the input control for which the label is created
419
     * @param array $additionalattributes possibility to add custom attributes, attribute name => value
420
     * @return array 'id' => label's ID to be used in 'aria-labelledby' attribute, 'html' => HTML code
421
     */
422
    protected function create_label_for_input(string $text, string $inputid, array $additionalattributes = []): array {
423
        $labelid = 'lbl_' . str_replace(':', '__', $inputid);
1,573✔
424
        $attributes = [
1,573✔
425
            'class' => 'subq sr-only',
1,573✔
426
            'for' => $inputid,
1,573✔
427
            'id' => $labelid,
1,573✔
428
        ];
1,573✔
429

430
        // Merging the additional attributes with the default attributes; left array has precedence when
431
        // using the + operator.
432
        $attributes = $additionalattributes + $attributes;
1,573✔
433

434
        return [
1,573✔
435
            'id' => $labelid,
1,573✔
436
            'html' => html_writer::tag('label', $text, $attributes),
1,573✔
437
        ];
1,573✔
438
    }
439

440
    /**
441
     * Create a <select> field for a multiple choice answer input.
442
     *
443
     * @param formulas_part $part question part
444
     * @param int|string $answerindex index of the answer (starting at 0) or special value for combined/separate unit field
445
     * @param question_attempt $qa question attempt that will be displayed on the page
446
     * @param array $answeroptions array of strings containing the answer options to choose from
447
     * @param bool $shuffle whether the options should be shuffled
448
     * @param question_display_options $displayoptions controls what should and should not be displayed
449
     * @return string HTML fragment
450
     */
451
    protected function create_dropdown_mc_answer(
452
        formulas_part $part,
453
        $answerindex,
454
        question_attempt $qa,
455
        array $answeroptions,
456
        bool $shuffle,
457
        question_display_options $displayoptions
458
    ): string {
459
        /** @var qtype_formulas_question $question */
460
        $question = $qa->get_question();
39✔
461

462
        $variablename = "{$part->partindex}_{$answerindex}";
39✔
463
        $currentanswer = $qa->get_last_qt_var($variablename);
39✔
464
        $inputname = $qa->get_qt_field_name($variablename);
39✔
465

466
        $inputattributes['name'] = $inputname;
39✔
467
        $inputattributes['value'] = $currentanswer;
39✔
468
        $inputattributes['id'] = $inputname;
39✔
469
        $inputattributes['class'] = 'formulas-select';
39✔
470

471
        $label = $this->create_label_for_input(
39✔
472
            $this->generate_accessibility_label_text($answerindex, $part->numbox, $part->partindex, $question->numparts),
39✔
473
            $inputname
39✔
474
        );
39✔
475
        $inputattributes['aria-labelledby'] = $label['id'];
39✔
476

477
        if ($displayoptions->readonly) {
39✔
478
            $inputattributes['disabled'] = 'disabled';
13✔
479
        }
480

481
        // First, we open a <span> around the dropdown field and its accessibility label.
482
        $output = html_writer::start_tag('span', ['class' => 'formulas_menu']);
39✔
483
        $output .= $label['html'];
39✔
484

485
        // Iterate over all options.
486
        $entries = [];
39✔
487
        foreach ($answeroptions as $optiontext) {
39✔
488
            $entries[] = $question->format_text(
39✔
489
                $optiontext,
39✔
490
                $part->subqtextformat,
39✔
491
                $qa,
39✔
492
                'qtype_formulas',
39✔
493
                'answersubqtext',
39✔
494
                $part->id,
39✔
495
                false,
39✔
496
            );
39✔
497
        }
498

499
        // If needed, shuffle the options while maintaining the keys.
500
        if ($shuffle) {
39✔
501
            $keys = array_keys($entries);
13✔
502
            shuffle($keys);
13✔
503

504
            $shuffledentries = [];
13✔
505
            foreach ($keys as $key) {
13✔
506
                $shuffledentries[$key] = $entries[$key];
13✔
507
            }
508
            $entries = $shuffledentries;
13✔
509
        }
510

511
        $output .= html_writer::select($entries, $inputname, $currentanswer, ['' => ''], $inputattributes);
39✔
512
        $output .= html_writer::end_tag('span');
39✔
513

514
        return $output;
39✔
515
    }
516

517
    /**
518
     * Generate the right label for the input control, depending on the number of answers in the given part
519
     * and the number of parts in the question. Special cases (combined field, unit field) are also taken
520
     * into account. Returns the appropriate string from the language file. Examples are "Answer field for
521
     * part X", "Answer field X for part Y" or "Answer and unit for part X".
522
     *
523
     * @param int|string $answerindex index of the answer (starting at 0) or special value for combined/separate unit field
524
     * @param int $totalanswers number of answers for the given part
525
     * @param int $partindex number of the part (starting at 0) in this question
526
     * @param int $totalparts number of parts in the question
527
     * @return string localized string
528
     */
529
    protected function generate_accessibility_label_text(
530
        $answerindex,
531
        int $totalanswers,
532
        int $partindex,
533
        int $totalparts
534
    ): string {
535

536
        // Some language strings need parameters.
537
        $labeldata = new stdClass();
1,573✔
538

539
        // The language strings start with 'answerunit' for a separate unit field, 'answercombinedunit' for
540
        // a combined field, 'answercoordinate' for an answer field when there are multiple answers in the
541
        // part or just 'answer' if there is a single field.
542
        $labelstring = 'answer';
1,573✔
543
        if ($answerindex === self::UNIT_FIELD) {
1,573✔
544
            $labelstring .= 'unit';
481✔
545
        } else if ($answerindex === self::COMBINED_FIELD) {
1,573✔
546
            $labelstring .= 'combinedunit';
520✔
547
        } else if ($totalanswers > 1) {
1,300✔
548
            $labelstring .= 'coordinate';
39✔
549
            $labeldata->numanswer = $answerindex + 1;
39✔
550
        }
551

552
        // The language strings end with 'multi' for multi-part questions or 'single' for single-part
553
        // questions.
554
        if ($totalparts > 1) {
1,573✔
555
            $labelstring .= 'multi';
65✔
556
            $labeldata->part = $partindex + 1;
65✔
557
        } else {
558
            $labelstring .= 'single';
1,534✔
559
        }
560

561
        return get_string($labelstring, 'qtype_formulas', $labeldata);
1,573✔
562
    }
563

564
    /**
565
     * Create an <input> field.
566
     *
567
     * @param formulas_part $part question part
568
     * @param int|string $answerindex index of the answer (starting at 0) or special value for combined/separate unit field
569
     * @param question_attempt $qa question attempt that will be displayed on the page
570
     * @param question_display_options $displayoptions controls what should and should not be displayed
571
     * @param array $formatoptions associative array 'optionname' => 'value', e. g. 'w' => '50px'
572
     * @param string $feedbackclass
573
     * @return string HTML fragment
574
     */
575
    protected function create_input_box(
576
        formulas_part $part,
577
        $answerindex,
578
        question_attempt $qa,
579
        question_display_options $displayoptions,
580
        array $formatoptions = [],
581
        string $feedbackclass = ''
582
    ): string {
583
        /** @var qtype_formulas_question $question */
584
        $question = $qa->get_question();
1,521✔
585

586
        // The variable name will be N_ for the (single) combined unit field of part N,
587
        // or N_M for answer #M in part #N. If #M is equal to the part's numbox (i. e. the
588
        // number of answers), it is a unit field; note that the fields are numbered starting
589
        // from 0, so with 3 answers, we have N_0, N_1, N_2 and only use N_3 if there is a
590
        // unit.
591
        $variablename = $part->partindex . '_';
1,521✔
592
        if ($answerindex === self::UNIT_FIELD) {
1,521✔
593
            $variablename .= $part->numbox;
481✔
594
        } else {
595
            $variablename .= ($answerindex === self::COMBINED_FIELD ? '' : $answerindex);
1,521✔
596
        }
597

598
        $currentanswer = $qa->get_last_qt_var($variablename);
1,521✔
599
        $inputname = $qa->get_qt_field_name($variablename);
1,521✔
600

601
        // Text fields will have a tooltip attached. The tooltip's content depends on the
602
        // answer type. Special tooltips exist for combined or separate unit fields.
603
        switch ($part->answertype) {
1,521✔
604
            case qtype_formulas::ANSWER_TYPE_NUMERIC:
605
                $titlestring = 'numeric';
78✔
606
                break;
78✔
607
            case qtype_formulas::ANSWER_TYPE_NUMERICAL_FORMULA:
608
                $titlestring = 'numerical_formula';
78✔
609
                break;
78✔
610
            case qtype_formulas::ANSWER_TYPE_ALGEBRAIC:
611
                $titlestring = 'algebraic_formula';
104✔
612
                break;
104✔
613
            case qtype_formulas::ANSWER_TYPE_NUMBER:
614
            default:
615
                $titlestring = 'number';
1,313✔
616
        }
617
        if ($answerindex === self::COMBINED_FIELD) {
1,521✔
618
            $titlestring .= '_unit';
520✔
619
        }
620
        if ($answerindex === self::UNIT_FIELD) {
1,521✔
621
            $titlestring = 'unit';
481✔
622
        }
623
        $title = get_string($titlestring, 'qtype_formulas');
1,521✔
624

625
        // Fetch the configured default width and use it, if the setting exists. Otherwise,
626
        // the plugin's default as defined in styles.css will be used. If the user did not
627
        // specify a unit, we use pixels (px). Note that this is different from the renderer
628
        // where rem is used in order to allow for the short syntax 'w=3' (3 chars wide).
629
        $defaultformat = [];
1,521✔
630
        $defaultwidth = get_config('qtype_formulas', "defaultwidth_{$titlestring}");
1,521✔
631
        // If the default width has not been set for the current answer box type, $defaultwidth will
632
        // be false and thus not numeric.
633
        if (is_numeric($defaultwidth)) {
1,521✔
634
            $defaultwidthunit = get_config('qtype_formulas', "defaultwidthunit");
1,521✔
635
            if (!in_array($defaultwidthunit, ['px', 'rem', 'em'])) {
1,521✔
636
                $defaultwidthunit = 'px';
104✔
637
            }
638
            $defaultformat = ['w' => $defaultwidth . $defaultwidthunit];
1,521✔
639
        }
640
        // Using the union operator the values from the left array will be kept.
641
        $formatoptions = $formatoptions + $defaultformat;
1,521✔
642

643
        $inputattributes = [
1,521✔
644
            'type' => 'text',
1,521✔
645
            'name' => $inputname,
1,521✔
646
            'value' => $currentanswer,
1,521✔
647
            'id' => $inputname,
1,521✔
648
            'style' => $this->get_css_properties($formatoptions),
1,521✔
649

650
            'data-answertype' => ($answerindex === self::UNIT_FIELD ? 'unit' : $part->answertype),
1,521✔
651
            'data-withunit' => ($answerindex === self::COMBINED_FIELD ? '1' : '0'),
1,521✔
652

653
            'title' => $title,
1,521✔
654
            'class' => "form-control formulas_{$titlestring} {$feedbackclass}",
1,521✔
655
            'maxlength' => 128,
1,521✔
656
        ];
1,521✔
657

658
        // If the answer type is "Number" and it is not a combined field, we only add the tooltip, if the
659
        // corresponding option is set.
660
        $iscombined = $inputattributes['data-withunit'] === '1';
1,521✔
661
        $isnumber = !$iscombined && $inputattributes['data-answertype'] === qtype_formulas::ANSWER_TYPE_NUMBER;
1,521✔
662
        $shownumbertooltip = get_config('qtype_formulas', 'shownumbertooltip');
1,521✔
663
        $inputattributes += [
1,521✔
664
            'data-qtype-formulas-enable-tooltip' => (!$isnumber || $shownumbertooltip ? 'true' : 'false'),
1,521✔
665
            'data-qtype-formulas-tooltip-trigger' => get_config('qtype_formulas', 'tooltiptrigger'),
1,521✔
666
        ];
1,521✔
667

668
        if ($displayoptions->readonly) {
1,521✔
669
            $inputattributes['readonly'] = 'readonly';
221✔
670
        }
671

672
        $label = $this->create_label_for_input(
1,521✔
673
            $this->generate_accessibility_label_text($answerindex, $part->numbox, $part->partindex, $question->numparts),
1,521✔
674
            $inputname
1,521✔
675
        );
1,521✔
676
        $inputattributes['aria-labelledby'] = $label['id'];
1,521✔
677

678
        // We need to wrap our input field into a wrapper <div>, in order for the LaTeX preview
679
        // to be correctly positioned even inside a table.
680
        $output = $label['html'];
1,521✔
681
        $output .= html_writer::empty_tag('input', $inputattributes);
1,521✔
682

683
        return $output;
1,521✔
684
    }
685

686
    /**
687
     * Return the part's text with variables replaced by their values.
688
     *
689
     * @param question_attempt $qa question attempt that will be displayed on the page
690
     * @param question_display_options $options controls what should and should not be displayed
691
     * @param formulas_part $part question part
692
     * @param stdClass $sub class and symbol for the part feedback
693
     * @return string HTML fragment
694
     */
695
    public function get_part_formulation(
696
        question_attempt $qa,
697
        question_display_options $options,
698
        formulas_part $part,
699
        stdClass $sub
700
    ): string {
701
        /** @var qtype_formulas_question $question */
702
        $question = $qa->get_question();
1,573✔
703

704
        // Clone the part's evaluator and remove special variables like _0 etc., because they must
705
        // not be substituted here; otherwise, we would lose input boxes.
706
        $evaluator = clone $part->evaluator;
1,573✔
707
        $evaluator->remove_special_vars();
1,573✔
708
        $text = $evaluator->substitute_variables_in_text($part->subqtext);
1,573✔
709

710
        $subqreplaced = $question->format_text(
1,573✔
711
            $text,
1,573✔
712
            $part->subqtextformat,
1,573✔
713
            $qa,
1,573✔
714
            'qtype_formulas',
1,573✔
715
            'answersubqtext',
1,573✔
716
            $part->id,
1,573✔
717
            false,
1,573✔
718
        );
1,573✔
719

720
        // Get the set of defined placeholders and their options.
721
        $boxes = $part->scan_for_answer_boxes($subqreplaced);
1,573✔
722

723
        // Append missing placholders at the end of part. We do not put a space before the opening
724
        // or after the closing brace, in order to get {_0}{_u} for questions with one answer and
725
        // a unit. This makes sure that the question will receive a combined unit field.
726
        for ($i = 0; $i <= $part->numbox; $i++) {
1,573✔
727
            // If no unit has been set, we do not append the {_u} placeholder.
728
            if ($i == $part->numbox && empty($part->postunit)) {
1,573✔
729
                continue;
884✔
730
            }
731
            $placeholder = ($i == $part->numbox) ? '_u' : "_{$i}";
1,573✔
732
            // If the placeholder does not exist yet, we create it with default settings, i. e. no multi-choice
733
            // and no styling.
734
            if (!array_key_exists($placeholder, $boxes)) {
1,573✔
735
                $boxes[$placeholder] = [
390✔
736
                    'placeholder' => '{' . $placeholder . '}',
390✔
737
                    'options' => '',
390✔
738
                    'dropdown' => false,
390✔
739
                    'format' => [],
390✔
740
                ];
390✔
741
                $subqreplaced .= '{' . $placeholder . '}';
390✔
742
            }
743
        }
744

745
        // If part has combined unit answer input.
746
        if ($part->has_combined_unit_field()) {
1,573✔
747
            // For a combined unit field, we try to merge the formatting options from the {_0} and the
748
            // {_u} placeholder, giving precedence to the latter.
749
            $mergedformat = $boxes['_u']['format'] + $boxes['_0']['format'];
520✔
750
            $combinedfieldhtml = $this->create_input_box(
520✔
751
                $part,
520✔
752
                self::COMBINED_FIELD,
520✔
753
                $qa,
520✔
754
                $options,
520✔
755
                $mergedformat,
520✔
756
                $sub->feedbackclass,
520✔
757
            );
520✔
758
            // The combined field must be placed where the user has the {_0}{_u} placeholders, possibly with
759
            // their formatting options.
760
            $boxplaceholders = $boxes['_0']['placeholder'] . $boxes['_u']['placeholder'];
520✔
761
            return str_replace($boxplaceholders, $combinedfieldhtml, $subqreplaced);
520✔
762
        }
763

764
        // Iterate over all boxes again, this time creating the appropriate input control and insert it
765
        // at the position indicated by the placeholder.
766
        for ($i = 0; $i <= $part->numbox; $i++) {
1,300✔
767
            // For normal answer fields, the placeholder is {_N} with N being the number of the
768
            // answer, starting from 0. The unit field, if there is one, comes last and has the
769
            // {_u} placeholder.
770
            if ($i < $part->numbox) {
1,300✔
771
                $answerindex = $i;
1,300✔
772
                $placeholder = "_$i";
1,300✔
773
            } else if (!empty($part->postunit)) {
1,300✔
774
                $answerindex = self::UNIT_FIELD;
481✔
775
                $placeholder = '_u';
481✔
776
            }
777

778
            // If the user has requested a multi-choice element, they must have specified an array
779
            // variable containing the options. We try to fetch that variable. If this fails, we
780
            // simply continue and build a text field instead.
781
            $optiontexts = null;
1,300✔
782
            if (!empty($boxes[$placeholder]['options'])) {
1,300✔
783
                try {
784
                    $optiontexts = $part->evaluator->export_single_variable($boxes[$placeholder]['options']);
91✔
785
                } catch (Exception $e) {
13✔
786
                    // TODO: use non-capturing catch.
787
                    unset($e);
13✔
788
                }
789
            }
790

791
            if ($optiontexts === null) {
1,300✔
792
                $inputfieldhtml = $this->create_input_box(
1,248✔
793
                    $part,
1,248✔
794
                    $answerindex,
1,248✔
795
                    $qa,
1,248✔
796
                    $options,
1,248✔
797
                    $boxes[$placeholder]['format'],
1,248✔
798
                    $sub->feedbackclass,
1,248✔
799
                );
1,248✔
800
            } else if ($boxes[$placeholder]['dropdown']) {
78✔
801
                $inputfieldhtml = $this->create_dropdown_mc_answer(
39✔
802
                    $part,
39✔
803
                    $i,
39✔
804
                    $qa,
39✔
805
                    $optiontexts->value,
39✔
806
                    $boxes[$placeholder]['shuffle'],
39✔
807
                    $options,
39✔
808
                );
39✔
809
            } else {
810
                $inputfieldhtml = $this->create_radio_mc_answer(
39✔
811
                    $part,
39✔
812
                    $i,
39✔
813
                    $qa,
39✔
814
                    $optiontexts->value,
39✔
815
                    $boxes[$placeholder]['shuffle'],
39✔
816
                    $options,
39✔
817
                    $sub->feedbackclass,
39✔
818
                );
39✔
819
            }
820

821
            // The replacement text *might* contain a backslash and in the worst case this might
822
            // lead to an erroneous backreference, e. g. if the student's answer was \1. Thus,
823
            // we better use preg_replace_callback() instead of just preg_replace(), as this allows
824
            // us to ignore such unintentional backreferences.
825
            $subqreplaced = preg_replace_callback(
1,300✔
826
                '/' . preg_quote($boxes[$placeholder]['placeholder'], '/') . '/',
1,300✔
827
                function ($matches) use ($inputfieldhtml) {
1,300✔
828
                    return $inputfieldhtml;
1,300✔
829
                },
1,300✔
830
                $subqreplaced,
1,300✔
831
                1
1,300✔
832
            );
1,300✔
833
        }
834

835
        return $subqreplaced;
1,300✔
836
    }
837

838
    /**
839
     * Correct response for the question. This is not needed for the Formulas question, because
840
     * answers are relative to parts.
841
     *
842
     * @param question_attempt $qa question attempt that will be displayed on the page
843
     * @return string empty string
844
     */
845
    public function correct_response(question_attempt $qa) {
846
        return '';
234✔
847
    }
848

849
    /**
850
     * Generate an automatic description of the correct response for a given part.
851
     *
852
     * @param formulas_part $part question part
853
     * @return string HTML fragment
854
     */
855
    public function part_correct_response($part) {
856
        $answers = $part->get_correct_response(true);
234✔
857
        $answertext = implode('; ', $answers);
234✔
858

859
        $string = ($part->answernotunique ? 'correctansweris' : 'uniquecorrectansweris');
234✔
860
        return html_writer::nonempty_tag(
234✔
861
            'div',
234✔
862
            get_string($string, 'qtype_formulas', $answertext),
234✔
863
            ['class' => 'formulaspartcorrectanswer filter_mathjaxloader_equation'],
234✔
864
        );
234✔
865
    }
866

867
    /**
868
     * Check whether the last response of a question attempt is the same as the last submitted response, i. e. it
869
     * was either submitted (e. g. using the "Check" button) or it was saved during page navigation in a quiz but
870
     * still contains the same answers as the ones from the last regular submission.
871
     *
872
     * @param question_attempt $qa
873
     * @param formulas_part|null $part
874
     * @return bool
875
     */
876
    protected function response_is_same_as_submitted(question_attempt $qa, formulas_part|null $part = null): bool {
877
        // If the last step contains the behaviour var 'submit', it was itself a submitted response.
878
        // For the deferredfeedback behaviour, the step will contain 'finish' instead of 'submit'.
879
        $laststep = $qa->get_last_step();
1,573✔
880
        if ($laststep->has_behaviour_var('submit') || $laststep->has_behaviour_var('finish')) {
1,573✔
881
            return true;
299✔
882
        }
883

884
        // Otherwise, we try to fetch the step containing the last submitted response.
885
        $lastsubmitted = $qa->get_last_step_with_behaviour_var('submit');
1,547✔
886
        $lastsubmitteddata = $lastsubmitted->get_qt_data();
1,547✔
887

888
        // If there is no data, then no response has ever been submitted.
889
        if (empty($lastsubmitteddata)) {
1,547✔
890
            return false;
1,547✔
891
        }
892

893
        // If we have a part, we compare the last step's data to the one from the last submitted response,
894
        // but only for the fields of the relevant part.
895
        $lastdata = $laststep->get_qt_data();
26✔
896
        if ($part !== null) {
26✔
897
            return $part->is_same_response($lastsubmitteddata, $lastdata);
26✔
898
        }
899

900
        // If we do not have a part, we compare the reponse for the entire question.
901
        /** @var qtype_formulas_question $question */
902
        $question = $qa->get_question();
26✔
903

904
        return $question->is_same_response($lastsubmitteddata, $lastdata);
26✔
905
    }
906

907
    #[\Override]
908
    public function feedback(question_attempt $qa, question_display_options $options) {
909
        // We should not give feedback if the response is not properly submitted, but rather just saved
910
        // during navigation through the quiz.
911
        if (!$this->response_is_same_as_submitted($qa)) {
1,573✔
912
            return '';
1,547✔
913
        }
914

915
        return parent::feedback($qa, $options);
299✔
916
    }
917

918
    /**
919
     * Generate a brief statement of how many sub-parts of this question the
920
     * student got right.
921
     *
922
     * @param question_attempt $qa question attempt that will be displayed on the page
923
     * @return string HTML fragment
924
     */
925
    protected function num_parts_correct(question_attempt $qa) {
926
        /** @var qtype_formulas_question $question */
927
        $question = $qa->get_question();
156✔
928
        $response = $qa->get_last_qt_data();
156✔
929
        if (!$question->is_gradable_response($response)) {
156✔
UNCOV
930
            return '';
×
931
        }
932

933
        $numright = $question->get_num_parts_right($response)[0];
156✔
934
        if ($numright === 1) {
156✔
935
            return get_string('yougotoneright', 'qtype_formulas');
26✔
936
        } else {
937
            return get_string('yougotnright', 'qtype_formulas', $numright);
143✔
938
        }
939
    }
940

941
    /**
942
     * We need to owerwrite this method to replace global variables by their value.
943
     *
944
     * @param question_attempt $qa question attempt that will be displayed on the page
945
     * @param question_hint $hint the hint to be shown
946
     * @return string HTML fragment
947
     */
948
    protected function hint(question_attempt $qa, question_hint $hint) {
949
        /** @var qtype_formulas_question $question */
950
        $question = $qa->get_question();
26✔
951
        $hint->hint = $question->evaluator->substitute_variables_in_text($hint->hint);
26✔
952

953
        return html_writer::nonempty_tag('div', $question->format_hint($hint, $qa), ['class' => 'hint']);
26✔
954
    }
955

956
    /**
957
     * Generate HTML fragment for the question's combined feedback.
958
     *
959
     * @param question_attempt $qa question attempt that will be displayed on the page
960
     * @return string HTML fragment
961
     */
962
    protected function combined_feedback(question_attempt $qa) {
963
        /** @var qtype_formulas_question $question */
964
        $question = $qa->get_question();
299✔
965

966
        $state = $qa->get_state();
299✔
967
        if (!$state->is_finished()) {
299✔
968
            $response = $qa->get_last_qt_data();
91✔
969
            if (!$question->is_gradable_response($response)) {
91✔
UNCOV
970
                return '';
×
971
            }
972
            $state = $question->grade_response($response)[1];
91✔
973
        }
974

975
        // The feedback will be in ->correctfeedback, ->partiallycorrectfeedback or ->incorrectfeedback,
976
        // with the corresponding ->...feedbackformat setting. We create the property names here to simplify
977
        // access.
978
        $fieldname = $state->get_feedback_class() . 'feedback';
299✔
979
        $formatname = $state->get_feedback_class() . 'feedbackformat';
299✔
980

981
        // If there is no feedback, we return an empty string.
982
        if (strlen(trim($question->$fieldname)) === 0) {
299✔
983
            return '';
×
984
        }
985

986
        // Otherwise, we return the appropriate feedback. The text is run through format_text() to have
987
        // variables replaced.
988
        return $question->format_text(
299✔
989
            $question->$fieldname,
299✔
990
            $question->$formatname,
299✔
991
            $qa,
299✔
992
            'question',
299✔
993
            $fieldname,
299✔
994
            $question->id,
299✔
995
            false,
299✔
996
        );
299✔
997
    }
998

999
    /**
1000
     * Generate the specific feedback. This is feedback that varies according to
1001
     * the response the student gave.
1002
     *
1003
     * @param question_attempt $qa question attempt that will be displayed on the page
1004
     * @return string
1005
     */
1006
    public function specific_feedback(question_attempt $qa) {
1007
        return $this->combined_feedback($qa);
299✔
1008
    }
1009

1010
    /**
1011
     * Gereate the part's general feedback. This is feedback is shown to all students.
1012
     *
1013
     * @param question_attempt $qa question attempt that will be displayed on the page
1014
     * @param question_display_options $options controls what should and should not be displayed
1015
     * @param formulas_part $part question part
1016
     * @return string HTML fragment
1017
     */
1018
    protected function part_general_feedback(question_attempt $qa, question_display_options $options, formulas_part $part) {
1019
        /** @var qtype_formulas_question $question */
1020
        $question = $qa->get_question();
1,573✔
1021
        $state = $qa->get_state();
1,573✔
1022

1023
        // If no feedback should be shown, we return an empty string.
1024
        if (!$options->feedback) {
1,573✔
1025
            return '';
1,547✔
1026
        }
1027

1028
        // If we use the adaptive multipart behaviour, there will be some feedback about the grading,
1029
        // e. g. the obtained marks for this submission and the attracted penalty.
1030
        $gradingdetailsdiv = '';
299✔
1031
        if ($qa->get_behaviour_name() == 'adaptivemultipart') {
299✔
1032
            // This is rather a hack, but it will probably work.
1033
            $renderer = $this->page->get_renderer('qbehaviour_adaptivemultipart');
65✔
1034
            $details = $qa->get_behaviour()->get_part_mark_details($part->partindex);
65✔
1035
            $gradingdetailsdiv = $renderer->render_adaptive_marks($details, $options);
65✔
1036
            $state = $details->state;
65✔
1037
        }
1038
        // If the question is in a state that does not yet allow to give a feedback
1039
        // or if the response is not the last one to be checked, we return an empty string.
1040
        if (!$this->response_is_same_as_submitted($qa, $part) || empty($state->get_feedback_class())) {
299✔
1041
            return '';
26✔
1042
        }
1043

1044
        // If we have a general feedback, we substitute local / grading variables and
1045
        // wrap it in a <div>.
1046
        $feedbackdiv = '';
286✔
1047
        if (strlen(trim($part->feedback)) !== 0) {
286✔
1048
            $feedbacktext = $part->evaluator->substitute_variables_in_text($part->feedback);
169✔
1049
            $feedbacktext = $question->format_text(
169✔
1050
                $feedbacktext,
169✔
1051
                FORMAT_HTML,
169✔
1052
                $qa,
169✔
1053
                'qtype_formulas',
169✔
1054
                'answerfeedback',
169✔
1055
                $part->id,
169✔
1056
                false
169✔
1057
            );
169✔
1058
            $feedbackdiv = html_writer::tag('div', $feedbacktext, ['class' => 'feedback formulaslocalfeedback']);
169✔
1059
        }
1060

1061
        // Append the grading details, if they exist. If the result is not empty, wrap in
1062
        // a <div> and return.
1063
        $feedbackdiv .= $gradingdetailsdiv;
286✔
1064
        if (!empty($feedbackdiv)) {
286✔
1065
            return html_writer::nonempty_tag(
182✔
1066
                'div',
182✔
1067
                $feedbackdiv,
182✔
1068
                ['class' => 'formulaspartfeedback formulaspartfeedback-' . $part->partindex],
182✔
1069
            );
182✔
1070
        }
1071

1072
        // Still here? Then we return an empty string.
1073
        return '';
117✔
1074
    }
1075

1076
    /**
1077
     * Generate HTML fragment for the part's combined feedback.
1078
     *
1079
     * @param question_attempt $qa question attempt that will be displayed on the page
1080
     * @param question_display_options $options controls what should and should not be displayed
1081
     * @param formulas_part $part question part
1082
     * @param float $fraction the obtained grade
1083
     * @return string HTML fragment
1084
     */
1085
    protected function part_combined_feedback(
1086
        question_attempt $qa,
1087
        question_display_options $options,
1088
        formulas_part $part,
1089
        float $fraction
1090
    ): string {
1091
        $feedback = '';
1,573✔
1092
        $showfeedback = false;
1,573✔
1093
        /** @var qtype_formulas_question $question */
1094
        $question = $qa->get_question();
1,573✔
1095
        $state = $qa->get_state();
1,573✔
1096
        $feedbackclass = $state->get_feedback_class();
1,573✔
1097

1098
        if ($qa->get_behaviour_name() == 'adaptivemultipart') {
1,573✔
1099
            $details = $qa->get_behaviour()->get_part_mark_details($part->partindex);
65✔
1100
            $feedbackclass = $details->state->get_feedback_class();
65✔
1101
        } else {
1102
            $state = question_state::graded_state_for_fraction($fraction);
1,521✔
1103
            $feedbackclass = $state->get_feedback_class();
1,521✔
1104
        }
1105
        if ($feedbackclass != '') {
1,573✔
1106
            $showfeedback = $options->feedback;
1,573✔
1107
            $field = 'part' . $feedbackclass . 'fb';
1,573✔
1108
            $format = 'part' . $feedbackclass . 'fbformat';
1,573✔
1109
            if ($part->$field) {
1,573✔
1110
                // Clone the part's evaluator and substitute local / grading vars first.
1111
                $part->$field = $part->evaluator->substitute_variables_in_text($part->$field);
1,560✔
1112
                $feedback = $question->format_text(
1,560✔
1113
                    $part->$field,
1,560✔
1114
                    $part->$format,
1,560✔
1115
                    $qa,
1,560✔
1116
                    'qtype_formulas',
1,560✔
1117
                    $field,
1,560✔
1118
                    $part->id,
1,560✔
1119
                    false,
1,560✔
1120
                );
1,560✔
1121
            }
1122
        }
1123
        if ($showfeedback && $feedback) {
1,573✔
1124
                $feedback = html_writer::tag('div', $feedback, ['class' => 'feedback formulaslocalfeedback']);
286✔
1125
                return html_writer::nonempty_tag(
286✔
1126
                    'div',
286✔
1127
                    $feedback,
286✔
1128
                    ['class' => 'formulaspartfeedback formulaspartfeedback-' . $part->partindex],
286✔
1129
                );
286✔
1130
        }
1131
        return '';
1,547✔
1132
    }
1133
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc