-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathquestiontype.php
More file actions
1356 lines (1192 loc) · 64.5 KB
/
questiontype.php
File metadata and controls
1356 lines (1192 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Question type class for the Formulas question type.
*
* @copyright 2010-2011 Hon Wai, Lau; 2023 Philipp Imhof
* @author Hon Wai, Lau <lau65536@gmail.com>
* @author Philipp Imhof
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package qtype_formulas
*/
use qtype_formulas\answer_unit_conversion;
use qtype_formulas\unit_conversion_rules;
use qtype_formulas\local\evaluator;
use qtype_formulas\local\formulas_part;
use qtype_formulas\local\random_parser;
use qtype_formulas\local\answer_parser;
use qtype_formulas\local\parser;
use qtype_formulas\local\token;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/questionlib.php');
require_once($CFG->dirroot . '/question/engine/lib.php');
require_once($CFG->dirroot . '/question/type/formulas/answer_unit.php');
require_once($CFG->dirroot . '/question/type/formulas/conversion_rules.php');
require_once($CFG->dirroot . '/question/type/formulas/question.php');
/**
* Question type class for the Formulas question type.
*
* @copyright 2010-2011 Hon Wai, Lau; 2023 Philipp Imhof
* @license https://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*/
class qtype_formulas extends question_type {
/** @var int */
const ANSWER_TYPE_NUMBER = 0;
/** @var int */
const ANSWER_TYPE_NUMERIC = 10;
/** @var int */
const ANSWER_TYPE_NUMERICAL_FORMULA = 100;
/** @var int */
const ANSWER_TYPE_ALGEBRAIC = 1000;
/** @var int maximum allowed size for lists (arrays) */
const MAX_LIST_SIZE = 1000;
/**
* The following array contains some of the column names of the table qtype_formulas_answers,
* the table that holds the parts (not just answers) of a question. These columns undergo similar
* validation, so they are grouped in this array. Some columns are not listed here, namely
* the texts (part's text, part's feedback) and their formatting option, because they are
* validated separately:
* - placeholder: the part's placeholder to be used in the main question text, e. g. #1
* - answermark: grade awarded for this part, if answer is fully correct
* - numbox: number of answers for this part, not including a possible unit field
* - vars1: the part's local variables
* - answer: the model answer(s) for this part
* - vars2: the part's grading variables
* - correctness: the part's grading criterion
* - unitpenalty: deduction to be made for wrong units
* - postunit: the unit in which the model answer has been entered
* - ruleid: ruleset used for unit conversion
* - otherrule: additional rules for unit conversion
*/
const PART_BASIC_FIELDS = ['placeholder', 'answermark', 'answertype', 'numbox', 'vars1', 'answer', 'answernotunique', 'vars2',
'correctness', 'unitpenalty', 'postunit', 'ruleid', 'otherrule'];
/**
* This function returns the "simple" additional fields defined in the qtype_formulas_options
* table. It is called by Moodle's core in order to have those fields automatically saved
* backed up and restored. The basic fields like id and questionid do not need to included.
* Also, we do not include the more "complex" feedback fields (correct, partially correct, incorrect),
* as they need special treatment, because they can contain references to uploaded files.
*
* @return string[]
*/
public function extra_question_fields() {
return ['qtype_formulas_options', 'varsrandom', 'varsglobal', 'shownumcorrect', 'answernumbering'];
}
/**
* Fetch the ID for every part of a given question.
*
* @param int $questionid
* @return int[]
*/
protected function fetch_part_ids_for_question(int $questionid): array {
global $DB;
// Fetch the parts from the DB. The result will be an associative array with
// the parts' IDs as keys.
$parts = $DB->get_records('qtype_formulas_answers', ['questionid' => $questionid]);
return array_keys($parts);
}
/**
* Move all the files belonging to this question (and its parts) from one context to another.
*
* @param int $questionid the question being moved.
* @param int $oldcontextid the context it is moving from.
* @param int $newcontextid the context it is moving to.
*/
public function move_files($questionid, $oldcontextid, $newcontextid): void {
// Fetch the part IDs for every part of this question.
$partids = $this->fetch_part_ids_for_question($questionid);
// Move files for all areas and all parts.
$fs = get_file_storage();
$areas = ['answersubqtext', 'answerfeedback', 'partcorrectfb', 'partpartiallycorrectfb', 'partincorrectfb'];
foreach ($areas as $area) {
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid, 'qtype_formulas', $area, $questionid);
foreach ($partids as $partid) {
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid, 'qtype_formulas', $area, $partid);
}
}
$this->move_files_in_combined_feedback($questionid, $oldcontextid, $newcontextid);
$this->move_files_in_hints($questionid, $oldcontextid, $newcontextid);
// The parent method will move files from the question text and the general feedback.
parent::move_files($questionid, $oldcontextid, $newcontextid);
}
/**
* Delete all the files belonging to this question (and its parts).
*
* @param int $questionid the question being deleted.
* @param int $contextid the context the question is in.
*/
protected function delete_files($questionid, $contextid): void {
// Fetch the part IDs for every part of this question.
$partids = $this->fetch_part_ids_for_question($questionid);
// Delete files for all areas and all parts.
$fs = get_file_storage();
$areas = ['answersubqtext', 'answerfeedback', 'partcorrectfb', 'partpartiallycorrectfb', 'partincorrectfb'];
foreach ($areas as $area) {
$fs->delete_area_files($contextid, 'qtype_formulas', $area, $questionid);
foreach ($partids as $partid) {
$fs->delete_area_files($contextid, 'qtype_formulas', $area, $partid);
}
}
$this->delete_files_in_combined_feedback($questionid, $contextid);
$this->delete_files_in_hints($questionid, $contextid);
// The parent method will delete files from the question text and the general feedback.
parent::delete_files($questionid, $contextid);
}
/**
* Loads the question type specific options for the question.
* $question already contains the question's general data from the question table when
* this function is called.
*
* This function loads any question type specific options for the
* question from the database into the question object. This information
* is placed in the $question->options field. A question type is
* free, however, to decide on a internal structure of the options field.
* @param object $question The question object for the question. This object
* should be updated to include the question type
* specific information (it is passed by reference).
* @return bool Indicates success or failure.
*/
public function get_question_options($question): bool {
global $DB;
// Fetch options from the table qtype_formulas_options. The DB engine will automatically
// return a standard class where the attribute names match the column names.
$question->options = $DB->get_record('qtype_formulas_options', ['questionid' => $question->id]);
// In case of a DB error (e. g. missing record), get_record() returns false. In that case, we
// create default options.
if ($question->options === false) {
debugging(get_string('error_db_missing_options', 'qtype_formulas', $question->id), DEBUG_DEVELOPER);
$question->options = (object)[
'questionid' => $question->id,
'varsrandom' => '',
'varsglobal' => '',
'correctfeedback' => get_string('correctfeedbackdefault', 'question'),
'correctfeedbackformat' => FORMAT_HTML,
'partiallycorrectfeedback' => get_string('partiallycorrectfeedbackdefault', 'question'),
'partiallycorrectfeedbackformat' => FORMAT_HTML,
'incorrectfeedback' => get_string('incorrectfeedbackdefault', 'question'),
'incorrectfeedbackformat' => FORMAT_HTML,
'shownumcorrect' => 0,
'answernumbering' => 'none',
];
}
parent::get_question_options($question);
// Fetch parts' data and remove existing array indices (starting from first part's id) in order
// to have the array indices start from 0.
$question->options->answers = $DB->get_records('qtype_formulas_answers', ['questionid' => $question->id], 'partindex ASC');
$question->options->answers = array_values($question->options->answers);
// Correctly set the number of parts for this question.
$question->options->numparts = count($question->options->answers);
return true;
}
/**
* Helper function to save files that are embedded in e. g. part's text or
* feedback, avoids to set 'qtype_formulas' for every invocation.
*
* @param array $array the data from the form (or from import). This will
* normally have come from the formslib editor element, so it will be an
* array with keys 'text', 'format' and 'itemid'. However, when we are
* importing, it will be an array with keys 'text', 'format' and 'files'
* @param object $context the context the question is in.
* @param string $filearea indentifies the file area questiontext,
* generalfeedback, answerfeedback, etc.
* @param int $itemid part or question ID
*
* @return string the text for this field, after files have been processed.
*/
protected function save_file_helper(array $array, object $context, string $filearea, int $itemid): string {
return $this->import_or_save_files($array, $context, 'qtype_formulas', $filearea, $itemid);
}
/**
* Saves question-type specific options
*
* This is called by {@see save_question()} to save the question-type specific data
* @param object $formdata This holds the information from the editing form,
* it is not a standard question object.
* @return object $result->error or $result->notice
* @throws Exception
*/
public function save_question_options($formdata) {
global $DB;
// Fetch existing parts from the DB.
$existingparts = $DB->get_records('qtype_formulas_answers', ['questionid' => $formdata->id], 'partindex ASC');
// Validate the data from the edit form.
$filtered = $this->validate($formdata);
if (!empty($filtered->errors)) {
return (object)['error' => implode("\n", $filtered->errors)];
}
// Order the parts according to how they appear in the question.
$filtered->answers = $this->reorder_parts($formdata->questiontext, $filtered->answers);
// Get the question's context. We will need that for handling any files that might have
// been uploaded via the text editors.
$context = $formdata->context;
foreach ($filtered->answers as $i => $part) {
$part->questionid = $formdata->id;
$part->partindex = $i;
// Try to take the first existing part.
$parttoupdate = array_shift($existingparts);
// If there is currently no part, we create an empty one, store it in the DB
// and retrieve its ID.
if (empty($parttoupdate)) {
$config = get_config('qtype_formulas');
$parttoupdate = (object)[
'questionid' => $formdata->id,
'answermark' => $config->defaultanswermark,
'numbox' => 1,
'answer' => '',
'answernotunique' => 1,
'correctness' => '',
'ruleid' => 1,
'subqtext' => '',
'subqtextformat' => FORMAT_HTML,
'feedback' => '',
'feedbackformat' => FORMAT_HTML,
'partcorrectfb' => '',
'partcorrectfbformat' => FORMAT_HTML,
'partpartiallycorrectfb' => '',
'partpartiallycorrectfbformat' => FORMAT_HTML,
'partincorrectfb' => '',
'partincorrectfbformat' => FORMAT_HTML,
];
try {
$parttoupdate->id = $DB->insert_record('qtype_formulas_answers', $parttoupdate);
} catch (Exception $e) {
// TODO: change to non-capturing catch when dropping support for PHP 7.4.
return (object)['error' => get_string('error_db_write', 'qtype_formulas', 'qtype_formulas_answers')];
}
}
// Finally, set the ID for the newpart.
$part->id = $parttoupdate->id;
// Now that we have the ID, we can deal with the text fields that might contain files,
// i. e. the part's text and the feedbacks (general, correct, partially correct, incorrect).
// We must split up the form's text editor data (text and format in one array) into separate
// text and format properties. Moodle does its magic when saving the files, so we first do
// that and keep the modified text.
// Note that we store the files with the part ID for all text fields that belong to a part.
$tmp = $part->subqtext;
$part->subqtext = $this->save_file_helper($tmp, $context, 'answersubqtext', $part->id);
$part->subqtextformat = $tmp['format'];
$tmp = $part->feedback;
$part->feedback = $this->save_file_helper($tmp, $context, 'answerfeedback', $part->id);
$part->feedbackformat = $tmp['format'];
$tmp = $part->partcorrectfb;
$part->partcorrectfb = $this->save_file_helper($tmp, $context, 'partcorrectfb', $part->id);
$part->partcorrectfbformat = $tmp['format'];
$tmp = $part->partpartiallycorrectfb;
$part->partpartiallycorrectfb = $this->save_file_helper($tmp, $context, 'partpartiallycorrectfb', $part->id);
$part->partpartiallycorrectfbformat = $tmp['format'];
$tmp = $part->partincorrectfb;
$part->partincorrectfb = $this->save_file_helper($tmp, $context, 'partincorrectfb', $part->id);
$part->partincorrectfbformat = $tmp['format'];
try {
$DB->update_record('qtype_formulas_answers', $part);
} catch (Exception $e) {
// TODO: change to non-capturing catch when dropping support for PHP 7.4.
return (object)['error' => get_string('error_db_write', 'qtype_formulas', 'qtype_formulas_answers')];
}
}
$options = $DB->get_record('qtype_formulas_options', ['questionid' => $formdata->id]);
// If there are no options yet (i. e. we are saving a new question) or if the fetch was not
// successful, create new options with default values.
if (empty($options) || $options === false) {
$options = (object)[
'questionid' => $formdata->id,
'correctfeedback' => '',
'partiallycorrectfeedback' => '',
'incorrectfeedback' => '',
'answernumbering' => 'none',
];
try {
$options->id = $DB->insert_record('qtype_formulas_options', $options);
} catch (Exception $e) {
return (object)['error' => get_string('error_db_write', 'qtype_formulas', 'qtype_formulas_options')];
}
}
// Do all the magic for the question's combined feedback fields (correct, partially correct, incorrect).
$options = $this->save_combined_feedback_helper($options, $formdata, $context, true);
// Get the extra fields we have for our question type. Drop the first entry, because
// it contains the table name.
$extraquestionfields = $this->extra_question_fields();
array_shift($extraquestionfields);
// Assign the values from the form.
foreach ($extraquestionfields as $extrafield) {
if (isset($formdata->$extrafield)) {
$options->$extrafield = $formdata->$extrafield;
}
}
// Finally, update the existing (or just recently created) record with the values from the form.
try {
$DB->update_record('qtype_formulas_options', $options);
} catch (Exception $e) {
return (object)['error' => get_string('error_db_write', 'qtype_formulas', 'qtype_formulas_options')];
}
// Save the hints, if they exist.
$this->save_hints($formdata, true);
// If there are no existing parts left to be updated, we may leave.
if (!$existingparts) {
return;
}
// Still here? Then we must remove remaining parts and their files (if there are), because the
// user seems to have deleted them in the form. This is only important for Moodle 3.11 and lower,
// because from Moodle 4.0 on, the parts and their files will remain in the DB, linked to the
// old question version.
$fs = get_file_storage();
foreach ($existingparts as $leftover) {
$areas = ['answersubqtext', 'answerfeedback', 'partcorrectfb', 'partpartiallycorrectfb', 'partincorrectfb'];
foreach ($areas as $area) {
$fs->delete_area_files($context->id, 'qtype_formulas', $area, $leftover->id);
}
try {
$DB->delete_records('qtype_formulas_answers', ['id' => $leftover->id]);
} catch (Exception $e) {
return (object)['error' => get_string('error_db_delete', 'qtype_formulas', 'qtype_formulas_answers')];
}
}
}
/**
* Save a question. Overriding the parent method, because we have to calculate the
* defaultmark and we need to propagate the global settings for unitpenalty and ruleid
* to every part.
*
* @param object $question
* @param object $formdata
* @return object
*/
public function save_question($question, $formdata) {
// Question's default mark is the total of all non empty parts's marks.
$formdata->defaultmark = 0;
foreach (array_keys($formdata->answermark) as $key) {
$formdata->defaultmark += $formdata->answermark[$key];
}
// Add the global unitpenalty and ruleid to each part. Using the answertype field as
// the counter reference, because it is always set.
$count = count($formdata->answertype);
$formdata->unitpenalty = array_fill(0, $count, $formdata->globalunitpenalty);
$formdata->ruleid = array_fill(0, $count, $formdata->globalruleid);
// Preparation work is done, let the parent method do the rest.
return parent::save_question($question, $formdata);
}
/**
* Create a question_hint. Overriding the parent method, because our
* question type can have multiple parts.
*
* @param object $hint the DB row from the question hints table.
* @return question_hint
*/
protected function make_hint($hint) {
return question_hint_with_parts::load_from_record($hint);
}
/**
* Delete the question from the database, together with its options and parts.
*
* @param int $questionid
* @param int $contextid
* @return void
*/
public function delete_question($questionid, $contextid) {
global $DB;
// First, we call the parent method. It will delete the question itself (from question)
// and its options (from qtype_formulas_options).
// Note: This will also trigger the delete_files() method which, in turn, needs the question's
// parts to be available, so we MUST NOT remove the parts before this.
parent::delete_question($questionid, $contextid);
// Finally, remove the related parts from the qtype_formulas_answers table.
$DB->delete_records('qtype_formulas_answers', ['questionid' => $questionid]);
}
/**
* Split the main question text into fragments that will later enclose the various parts'
* text. As an example, 'foo {#1} bar' will become 'foo ' and ' bar'. The function will
* return one more fragment than the number of parts. The last fragment can be empty, e. g.
* if we have a part with no placeholder. Such parts are placed at the very end, so there will
* no fragment of the question's main text after them.
*
* @param string $questiontext main question tex
* @param formulas_part[] $parts
* @return string[] fragments (one more than the number of parts
*/
public function split_questiontext(string $questiontext, array $parts): array {
// Make sure the parts are ordered according to the position of their placeholders
// in the main question text.
$parts = $this->reorder_parts($questiontext, $parts);
$fragments = [];
foreach ($parts as $part) {
// Since the parts are ordered, we know that parts with placeholders come first.
// When we see the first part without a placeholder, we can add the remaining question
// text to the fragments. We then set the question text to the empty string, in order
// to add empty fragments for each subsequent part.
if (empty($part->placeholder)) {
$fragments[] = $questiontext;
$questiontext = '';
continue;
}
$pos = strpos($questiontext, "{{$part->placeholder}}");
$fragments[] = substr($questiontext, 0, $pos);
$questiontext = substr($questiontext, $pos + strlen($part->placeholder) + 2);
}
// Add the remainder of the question text after the last part; this might be an empty string.
$fragments[] = $questiontext;
return $fragments;
}
/**
* Initialise instante of the qtype_formulas_question class and its parts which, in turn,
* are instances of the formulas_part class.
*
* @param question_definition $question instance of a Formulas question (qtype_formulas_question)
* @param object $questiondata question data as stored in the DB
*/
protected function initialise_question_instance(question_definition $question, $questiondata) {
// All the classical fields (e. g. category, context or id) are filled by the parent method.
parent::initialise_question_instance($question, $questiondata);
// First, copy some data for the main question.
/** @var qtype_formulas_question $question */
$question->varsrandom = $questiondata->options->varsrandom;
$question->varsglobal = $questiondata->options->varsglobal;
$question->answernumbering = $questiondata->options->answernumbering;
$question->numparts = $questiondata->options->numparts;
// The attribute $questiondata->options->answers stores all information for the parts. Despite
// its name, it does not only contain the model answers, but also e.g. local or grading vars.
foreach ($questiondata->options->answers as $partdata) {
$questionpart = new formulas_part();
// Copy the data fields fetched from the DB to the question part object.
foreach ($partdata as $key => $value) {
$questionpart->{$key} = $value;
}
// And finally store the populated part in the main question instance.
$question->parts[$partdata->partindex] = $questionpart;
}
// Split the main question text into fragments that will later surround the parts' texts.
$question->textfragments = $this->split_questiontext($question->questiontext, $question->parts);
// The combined feedback will be initialised by the parent class, because we do not override
// this method.
$this->initialise_combined_feedback($question, $questiondata, true);
}
/**
* Return all possible types of response. They are used e. g. in reports.
*
* @param object $questiondata question definition data
* @return array possible responses for every part
*/
public function get_possible_responses($questiondata) {
$responses = [];
/** @var qtype_formulas_question $question */
$question = $this->make_question($questiondata);
foreach ($question->parts as $part) {
if ($part->postunit === '') {
$responses[$part->partindex] = [
'wrong' => new question_possible_response(get_string('response_wrong', 'qtype_formulas'), 0),
'right' => new question_possible_response(get_string('response_right', 'qtype_formulas'), 1),
null => question_possible_response::no_response(),
];
} else {
$responses[$part->partindex] = [
'wrong' => new question_possible_response(get_string('response_wrong', 'qtype_formulas'), 0),
'right' => new question_possible_response(get_string('response_right', 'qtype_formulas'), 1),
'wrongvalue' => new question_possible_response(get_string('response_wrong_value', 'qtype_formulas'), 0),
'wrongunit' => new question_possible_response(
get_string('response_wrong_unit', 'qtype_formulas'),
1 - $part->unitpenalty,
),
null => question_possible_response::no_response(),
];
}
}
return $responses;
}
/**
* Imports the question from Moodle XML format. Overriding the parent function is necessary,
* because a Formulas question contains subparts.
*
* @param array $xml structure containing the XML data
* @param object $question question object to fill
* @param qformat_xml $format format class exporting the question
* @param object $extra extra information (not required for importing this question in this format)
* @return object question object
*/
public function import_from_xml($xml, $question, qformat_xml $format, $extra = null) {
// Return if data type is not our own one.
if (!isset($xml['@']['type']) || $xml['@']['type'] != $this->name()) {
return false;
}
// Import the common question headers and set the corresponding field.
$question = $format->import_headers($xml);
$question->qtype = $this->name();
$format->import_combined_feedback($question, $xml, true);
$format->import_hints($question, $xml, true);
$question->varsrandom = $format->getpath($xml, ['#', 'varsrandom', 0, '#', 'text', 0, '#'], '', true);
$question->varsglobal = $format->getpath($xml, ['#', 'varsglobal', 0, '#', 'text', 0, '#'], '', true);
$question->answernumbering = $format->getpath($xml, ['#', 'answernumbering', 0, '#', 'text', 0, '#'], 'none', true);
// If there are no answers (parts) in the XML, fetch a pseudo-path in order to generate an error
// in the same format as for missing fields.
if (!isset($xml['#']['answers'])) {
$xml['#']['answers'] = [];
$errormessage = get_string('error_import_missing_parts', 'qtype_formulas', $question->name);
$format->getpath($xml, ['#', 'xxx'], null, false, $errormessage);
}
// Otherwise, loop over each answer block found in the XML.
foreach ($xml['#']['answers'] as $i => $part) {
$partindex = $format->getpath($part, ['#', 'partindex', 0, '#', 'text', 0, '#'], false);
if ($partindex !== false) {
$question->partindex[$i] = $partindex;
}
foreach (self::PART_BASIC_FIELDS as $field) {
// Older questions do not have this field, so we do not want to issue an error message.
// Also, for maximum backwards compatibility, we set the default value to 1. With this,
// nothing changes for old questions.
if ($field === 'answernotunique') {
$ifnotexists = '';
$default = '1';
} else {
$ifnotexists = get_string('error_import_missing_field', 'qtype_formulas', $field);
$default = '0';
}
$question->{$field}[$i] = $format->getpath(
$part,
['#', $field, 0, '#', 'text', 0, '#'],
$default,
false,
$ifnotexists,
);
}
$subqxml = $format->getpath($part, ['#', 'subqtext', 0], []);
$question->subqtext[$i] = $format->import_text_with_files(
$subqxml,
[],
'',
$format->get_format($question->questiontextformat),
);
$feedbackxml = $format->getpath($part, ['#', 'feedback', 0], []);
$question->feedback[$i] = $format->import_text_with_files(
$feedbackxml,
[],
'',
$format->get_format($question->questiontextformat),
);
$feedbackxml = $format->getpath($part, ['#', 'correctfeedback', 0], []);
$question->partcorrectfb[$i] = $format->import_text_with_files(
$feedbackxml,
[],
'',
$format->get_format($question->questiontextformat),
);
$feedbackxml = $format->getpath($part, ['#', 'partiallycorrectfeedback', 0], []);
$question->partpartiallycorrectfb[$i] = $format->import_text_with_files(
$feedbackxml,
[],
'',
$format->get_format($question->questiontextformat),
);
$feedbackxml = $format->getpath($part, ['#', 'incorrectfeedback', 0], []);
$question->partincorrectfb[$i] = $format->import_text_with_files(
$feedbackxml,
[],
'',
$format->get_format($question->questiontextformat),
);
}
// Make the defaultmark consistent if not specified.
$question->defaultmark = array_sum($question->answermark ?? []);
return $question;
}
/**
* Exports the question to Moodle XML format.
*
* @param object $question question to be exported into XML format
* @param qformat_xml $format format class exporting the question
* @param object $extra extra information (not required for exporting this question in this format)
* @return string containing the question data in XML format
*/
public function export_to_xml($question, qformat_xml $format, $extra = null) {
$output = '';
$contextid = $question->contextid;
$output .= $format->write_combined_feedback($question->options, $question->id, $question->contextid);
// Get the extra fields we have for our question type. Drop the first entry, because
// it contains the table name.
$extraquestionfields = $this->extra_question_fields();
array_shift($extraquestionfields);
foreach ($extraquestionfields as $extrafield) {
$output .= "<$extrafield>" . $format->writetext($question->options->$extrafield) . "</$extrafield>\n";
}
$fs = get_file_storage();
foreach ($question->options->answers as $part) {
$output .= "<answers>\n";
$output .= " <partindex>\n " . $format->writetext($part->partindex) . " </partindex>\n";
foreach (self::PART_BASIC_FIELDS as $tag) {
$output .= " <$tag>\n " . $format->writetext($part->$tag) . " </$tag>\n";
}
$subqfiles = $fs->get_area_files($contextid, 'qtype_formulas', 'answersubqtext', $part->id);
$subqtextformat = $format->get_format($part->subqtextformat);
$output .= " <subqtext format=\"$subqtextformat\">\n";
$output .= $format->writetext($part->subqtext);
$output .= $format->write_files($subqfiles);
$output .= " </subqtext>\n";
$fbfiles = $fs->get_area_files($contextid, 'qtype_formulas', 'answerfeedback', $part->id);
$feedbackformat = $format->get_format($part->feedbackformat);
$output .= " <feedback format=\"$feedbackformat\">\n";
$output .= $format->writetext($part->feedback);
$output .= $format->write_files($fbfiles);
$output .= " </feedback>\n";
$fbfiles = $fs->get_area_files($contextid, 'qtype_formulas', 'partcorrectfb', $part->id);
$feedbackformat = $format->get_format($part->partcorrectfbformat);
$output .= " <correctfeedback format=\"$feedbackformat\">\n";
$output .= $format->writetext($part->partcorrectfb);
$output .= $format->write_files($fbfiles);
$output .= " </correctfeedback>\n";
$fbfiles = $fs->get_area_files($contextid, 'qtype_formulas', 'partpartiallycorrectfb', $part->id);
$feedbackformat = $format->get_format($part->partpartiallycorrectfbformat);
$output .= " <partiallycorrectfeedback format=\"$feedbackformat\">\n";
$output .= $format->writetext($part->partpartiallycorrectfb);
$output .= $format->write_files($fbfiles);
$output .= " </partiallycorrectfeedback>\n";
$fbfiles = $fs->get_area_files($contextid, 'qtype_formulas', 'partincorrectfb', $part->id);
$feedbackformat = $format->get_format($part->partincorrectfbformat);
$output .= " <incorrectfeedback format=\"$feedbackformat\">\n";
$output .= $format->writetext($part->partincorrectfb);
$output .= $format->write_files($fbfiles);
$output .= " </incorrectfeedback>\n";
$output .= "</answers>\n";
}
return $output;
}
/**
* Check if part placeholders are correctly formatted and unique and if each
* placeholder appears exactly once in the main question text.
*
* @param string $questiontext main question text
* @param object[] $parts data relative to each part, coming from the edit form
* @return array $errors possible error messages for each part's placeholder field
*/
public function check_placeholders(string $questiontext, array $parts): array {
// Store possible error messages for every part.
$errors = [];
// List of placeholders in order to spot duplicates.
$knownplaceholders = [];
foreach ($parts as $i => $part) {
// No error if part's placeholder is empty.
if (empty($part->placeholder)) {
continue;
}
$errormsgs = [];
// Maximal length for placeholders is limited to 40.
if (strlen($part->placeholder) > 40) {
$errormsgs[] = get_string('error_placeholder_too_long', 'qtype_formulas');
}
// Placeholders must start with # and contain only alphanumeric characters or underscores.
if (!preg_match('/^#\w+$/', $part->placeholder)) {
$errormsgs[] = get_string('error_placeholder_format', 'qtype_formulas');
}
// Placeholders must be unique.
if (in_array($part->placeholder, $knownplaceholders)) {
$errormsgs[] = get_string('error_placeholder_sub_duplicate', 'qtype_formulas');
}
// Add this placeholder to the list of known values.
$knownplaceholders[] = $part->placeholder;
// Each placeholder must appear exactly once in the main question text.
$count = substr_count($questiontext, "{{$part->placeholder}}");
if ($count < 1) {
$errormsgs[] = get_string('error_placeholder_missing', 'qtype_formulas');
}
if ($count > 1) {
$errormsgs[] = get_string('error_placeholder_main_duplicate', 'qtype_formulas');
}
// Concatenate all error messages and store them, so they can be shown in the edit form.
// The corresponding field's name is 'placeholder[...]', so we use that as the array key.
if (!empty($errormsgs)) {
$errors["placeholder[$i]"] = implode(' ', $errormsgs);
}
}
// Return the errors. The array will be empty, if everything was fine.
return $errors;
}
/**
* For each part, check that all required fields have been filled and that they are valid.
* Return the filtered data for all parts.
*
* @param object $data data from the edit form (or an import)
* @return object stdClass with properties 'errors' (for errors) and 'parts' (array of stdClass, data for each part)
*/
public function check_and_filter_parts(object $data): object {
// This function is also called when importing a question.
$isfromimport = property_exists($data, 'import_process');
$partdata = [];
$errors = [];
$hasoneanswer = false;
// Note: If we are importing and the data is damaged, there might be no parts at all. Hence,
// it is safer to use the ?? operator.
foreach (array_keys($data->answermark ?? []) as $i) {
// The answermark must not be empty or 0.
$nomark = empty(trim($data->answermark[$i]));
// For answers, zero is not nothing... Note that PHP < 8.0 does not consider '1 ' as numeric,
// so we trim first. PHP 8.0+ makes no difference between leading or trailing whitespace.
$noanswer = empty(trim($data->answer[$i])) && !is_numeric(trim($data->answer[$i]));
if ($noanswer === false) {
$hasoneanswer = true;
}
// For maximum backwards compatibility, we consider a part as being "empty", if
// has no question text (subqtext), no general feedback (combined feedback was
// probably not taken into account at first, because it was added later) and no
// local vars.
// Note that data from the editors is stored in an array with the keys text, format and itemid.
// Also note that local vars are entered in a textarea (and not an editor) and are PARAM_RAW_TRIMMED.
$noparttext = strlen(trim($data->subqtext[$i]['text'])) === 0;
$nogeneralfb = strlen(trim($data->subqtext[$i]['text'])) === 0;
$nolocalvars = strlen(trim($data->vars1[$i])) === 0;
$emptypart = $noparttext && $nogeneralfb && $nolocalvars;
// Having no answermark is only allowed if the part is "empty" AND if there is no answer.
if ($nomark && !($emptypart && $noanswer)) {
$errors["answermark[$i]"] = get_string('error_mark', 'qtype_formulas');
}
// On the other hand, having no answer is allowed for "empty" parts even if they
// do have an answermark. We do this, because the answermark field is set by default when
// the user clicks the "Blanks for 2 more parts" button. But if they do that by accident
// and don't want those parts, they should not have to worry about them.
if ($noanswer && !$emptypart) {
$errors["answer[$i]"] = get_string('error_answer_missing', 'qtype_formulas');
}
// No need to validate the remainder of this part if there is no answer or no mark.
if ($noanswer || $nomark) {
continue;
}
// The mark must be strictly positive.
if (floatval($data->answermark[$i]) <= 0) {
$errors["answermark[$i]"] = get_string('error_mark', 'qtype_formulas');
}
// The grading criterion must not be empty. Also, if there is no grading criterion, it does
// not make sense to continue the validation.
if (empty(trim($data->correctness[$i])) && !is_numeric(trim($data->correctness[$i]))) {
$errors["correctness[$i]"] = get_string('error_criterion_empty', 'qtype_formulas');
continue;
}
// Create a stdClass for each part, start by setting the questionid property which is
// common for all parts.
$partdata[$i] = (object)['questionid' => $data->id];
// Set the basic fields, e.g. mark, placeholder or definition of local variables.
foreach (self::PART_BASIC_FIELDS as $field) {
// In the edit form, the part's 'unitpenalty' and 'ruleid' are set via the global options
// 'globalunitpenalty' and 'globalruleid'. When importing a question, they do not need
// special treatment, because they are already stored with the part. Also, all other fields
// are submitted by part and do not need special treatment either.
if (in_array($field, ['ruleid', 'unitpenalty']) && !$isfromimport) {
$partdata[$i]->$field = trim($data->{'global' . $field});
} else {
$partdata[$i]->$field = trim($data->{$field}[$i]);
}
}
// The various texts are stored as arrays with the keys 'text', 'format' and (if coming from
// the edit form) 'itemid'. We can just copy that over.
$partdata[$i]->subqtext = $data->subqtext[$i];
$partdata[$i]->feedback = $data->feedback[$i];
$partdata[$i]->partcorrectfb = $data->partcorrectfb[$i];
$partdata[$i]->partpartiallycorrectfb = $data->partpartiallycorrectfb[$i];
$partdata[$i]->partincorrectfb = $data->partincorrectfb[$i];
}
// If no part has survived the validation, we need to output an error message. There are three
// reasons why a part's validation can fail:
// (a) there is no answermark
// (b) there is no answer
// (c) there is no grading criterion
// If all parts are left empty, they will fail for case (a) and will not have an error message
// attached to the answer field (answer can be empty if part is empty). In that case, we need
// to output an error to the first answer field (and this one only) saying that at least one
// answer is needed. We do not, however, add that error if the first part failed for case (b) and
// thus already has an error message there.
if (count($partdata) === 0 && $hasoneanswer === false) {
if (empty($errors['answer[0]'])) {
$errors['answer[0]'] = get_string('error_no_answer', 'qtype_formulas');
}
// If the answermark was left empty or filled with rubbish, the parameter filtering
// will have changed the value to 0, which is not a valid value. If, in addition,
// the part was otherwise empty, that will not have triggered an error message so far,
// because it might have been on purpose (to delete the unused part). But now that
// there seems to be no part left, we should add an error message to the field.
if (empty($data->answermark[0])) {
$errors['answermark[0]'] = get_string('error_mark', 'qtype_formulas');
}
}
return (object)['errors' => $errors, 'parts' => $partdata];
}
/**
* Check the data from the edit form (or an XML import): parts, answer box placeholders,
* part placeholders and definitions of variables and expressions. At the same time, calculate
* the number of expected answers for every part.
*
* @param object $data
* @return object
*/
public function validate(object $data): object {
// Collect all error messages in an associative array of the form 'fieldname' => 'error'.
$errors = [];
// The fields 'globalunitpenalty' and 'globalruleid' must be validated separately,
// because they are defined at the question level, even though they affect the parts.
// If we are importing a question, those fields will not be present, because the values
// are already stored with the parts.
$isfromimport = property_exists($data, 'import_process');
if (!$isfromimport) {
$errors += $this->validate_global_unit_fields($data);
}
// Check the parts. We get a stdClass with the properties 'errors' (a possibly empty array)
// and 'parts' (an array of stdClass objects, one per part).
$partcheckresult = $this->check_and_filter_parts($data);
$errors += $partcheckresult->errors;
// If the basic check failed, we abort and output the error message, because the errors
// might cause other errors downstream.
if (!empty($errors)) {
return (object)['errors' => $errors, 'answers' => null];
}
// From now on, we continue with the checked and filtered parts.
$parts = $partcheckresult->parts;
// Make sure that answer box placeholders (if used) are unique for each part.
foreach ($parts as $i => $part) {
try {
formulas_part::scan_for_answer_boxes($part->subqtext['text'], true);
} catch (Exception $e) {
$errors["subqtext[$i]"] = $e->getMessage();
}
}
// Separately validate the part placeholders. If we are importing, the question text
// will be a string. If the data comes from the edit from, it is in the editor's
// array structure (text, format, itemid).
$errors += $this->check_placeholders(
is_array($data->questiontext) ? $data->questiontext['text'] : $data->questiontext,
$parts
);
// Finally, check definition of variables (local, grading), various expressions
// depending on those variables (model answers, correctness criterion) and unit
// stuff. This check also allows us to calculate the number of answers for each part,
// a value that we store as 'numbox'.
$evaluationresult = $this->check_variables_and_expressions($data, $parts, $isfromimport);
$errors += $evaluationresult->errors;
$parts = $evaluationresult->parts;
return (object)['errors' => $errors, 'answers' => $parts];
}