-
Notifications
You must be signed in to change notification settings - Fork 149
/
question.php
2215 lines (1953 loc) · 92.4 KB
/
question.php
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 Stack - http://stack.maths.ed.ac.uk/
//
// Stack 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.
//
// Stack 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 Stack. If not, see <http://www.gnu.org/licenses/>.
/**
* Stack question definition class.
*
* @package qtype_stack
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/stack/input/factory.class.php');
require_once(__DIR__ . '/stack/cas/keyval.class.php');
require_once(__DIR__ . '/stack/cas/castext2/castext2_evaluatable.class.php');
require_once(__DIR__ . '/stack/cas/cassecurity.class.php');
global $CFG;
if (!isset($CFG->stackapi)) {
require_once($CFG->dirroot . '/question/behaviour/adaptivemultipart/behaviour.php');
require_once(__DIR__ . '/questiontype.php');
}
require_once(__DIR__ . '/locallib.php');
require_once(__DIR__ . '/stack/cas/secure_loader.class.php');
require_once(__DIR__ . '/stack/prt.class.php');
require_once(__DIR__ . '/stack/prt.evaluatable.class.php');
require_once(__DIR__ . '/vle_specific.php');
/**
* Represents a Stack question.
*
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_stack_question extends question_graded_automatically_with_countback
implements question_automatically_gradable_with_multiple_parts {
/**
* @var string STACK specific: Holds the version of the question when it was last saved.
*/
public $stackversion;
/**
* @var string STACK specific: variables, as authored by the teacher.
*/
public $questionvariables;
/**
* @var string STACK specific: variables, as authored by the teacher.
*/
public $questionnote;
/** @var int one of the FORMAT_... constants */
public $questionnoteformat;
/**
* @var string STACK specific: allow a question to carry some description/discussion.
*/
public $questiondescription;
/** @var int one of the FORMAT_... constants */
public $questiondescriptionformat;
/**
* @var string Any specific feedback for this question. This is displayed
* in the 'yellow' feedback area of the question. It can contain PRTfeedback
* tags, but not IEfeedback.
*/
public $specificfeedback;
/** @var int one of the FORMAT_... constants */
public $specificfeedbackformat;
/** @var string Feedback that is displayed for any PRT that returns a score of 1. */
public $prtcorrect;
/** @var int one of the FORMAT_... constants */
public $prtcorrectformat;
/** @var string Feedback that is displayed for any PRT that returns a score between 0 and 1. */
public $prtpartiallycorrect;
/** @var int one of the FORMAT_... constants */
public $prtpartiallycorrectformat;
/** @var string Feedback that is displayed for any PRT that returns a score of 0. */
public $prtincorrect;
/** @var int one of the FORMAT_... constants */
public $prtincorrectformat;
/** @var string if set, this is used to control the pseudo-random generation of the seed. */
public $variantsselectionseed;
/**
* @var stack_input[] STACK specific: string name as it appears in the question text => stack_input
*/
public $inputs = [];
/**
* @var stack_potentialresponse_tree_lite[] STACK specific: respones tree number => ...
*/
public $prts = [];
/**
* @var stack_options STACK specific: question-level options.
*/
public $options;
/**
* @var int[] of seed values that have been deployed.
*/
public $deployedseeds;
/**
* @var int STACK specific: seeds Maxima's random number generator.
*/
public $seed = null;
/**
* @var stack_cas_session2 STACK specific: session of variables.
*/
protected $session;
/**
* @var stack_ast_container[] STACK specific: the teacher's answers for each input.
*/
private $tas;
/**
* @var stack_cas_security the question level common security
* settings, i.e. forbidden keys and wether units are in play.
* Note that the security-object is used to enforce read-only
* identifiers and therefore wether we are dealing with units
* is important to it, as obviously one should not redefine units.
*/
private $security;
/**
* @var castext2_evaluatable STACK specific: variant specifying castext fragment.
*/
protected $questionnoteinstantiated = null;
/**
* @var castext2_evaluatable STACK specific.
*/
protected $questiondescriptioninstantiated = null;
/**
* @var castext2_evaluatable instantiated version of questiontext.
* Initialised in start_attempt / apply_attempt_state.
*/
public $questiontextinstantiated;
/**
* @var castext2_evaluatable instantiated version of specificfeedback.
* Initialised in start_attempt / apply_attempt_state.
*/
public $specificfeedbackinstantiated;
/**
* @var castext2_evaluatable instantiated version of generalfeedback.
* Init depends of config.
*/
private $generalfeedbackinstantiated = null;
/**
* @var castext2_evaluatable instantiated version of prtcorrect.
* Initialised in start_attempt / apply_attempt_state.
* NOTE: used in rederer.php:standard_prt_feedback() in an uncommon way.
*/
public $prtcorrectinstantiated;
/**
* @var castext2_evaluatable instantiated version of prtpartiallycorrect.
* Initialised in start_attempt / apply_attempt_state.
*/
public $prtpartiallycorrectinstantiated;
/**
* @var castext2_evaluatable instantiated version of prtincorrect.
* Initialised in start_attempt / apply_attempt_state.
*/
public $prtincorrectinstantiated;
/**
* @var castext2_processor an accesspoint to the question attempt for
* the castext2 post-processing logic for pluginfile url-writing.
*/
public $castextprocessor = null;
/**
* @var array Errors generated at runtime.
* Any errors are stored as the keys to prevent duplicates. Values are ignored.
*/
public $runtimeerrors = [];
/**
* The next three fields cache the results of some expensive computations.
* The chache is only valid for a particular response, so we store the current
* response, so that we can learn the cached information in the result changes.
* See {@link validate_cache()}.
* @var array
*/
protected $lastresponse = null;
/**
* @var bool like $lastresponse, but for the $acceptvalid argument to {@link validate_cache()}.
*/
protected $lastacceptvalid = null;
/**
* @var stack_input_state[] input name => stack_input_state.
* This caches the results of validate_student_response for $lastresponse.
*/
protected $inputstates = [];
/**
* @var array prt name => result of evaluate_response, if known.
*/
protected $prtresults = [];
/**
* @var array set of expensive to evaluate but static things.
*/
public $compiledcache = [];
/**
* @var array included files - used in API only.
*/
public $pluginfiles = [];
/**
* Make sure the cache is valid for the current response. If not, clear it.
*
* @param array $response the response.
* @param bool $acceptvalid if this is true, then we will grade things even
* if the corresponding inputs are only VALID, and not SCORE.
*/
protected function validate_cache($response, $acceptvalid = null) {
if (is_null($this->lastresponse)) {
$this->lastresponse = $response;
$this->lastacceptvalid = $acceptvalid;
return;
}
// We really need the PHP === here, as "0.040" == "0.04", even as strings.
// See https://stackoverflow.com/questions/80646/ for details.
if ($this->lastresponse === $response && (
$this->lastacceptvalid === null || $acceptvalid === null || $this->lastacceptvalid === $acceptvalid)) {
if ($this->lastacceptvalid === null) {
$this->lastacceptvalid = $acceptvalid;
}
return; // Cache is good.
}
// Clear the cache.
$this->lastresponse = $response;
$this->lastacceptvalid = $acceptvalid;
$this->inputstates = [];
$this->prtresults = [];
}
/**
* @return bool do any of the inputs in this question require the student
* validate the input.
*/
protected function any_inputs_require_validation() {
foreach ($this->inputs as $name => $input) {
if ($input->requires_validation()) {
return true;
}
}
return false;
}
public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
if (empty($this->inputs)) {
return question_engine::make_behaviour('informationitem', $qa, $preferredbehaviour);
}
if (empty($this->prts)) {
return question_engine::make_behaviour('manualgraded', $qa, $preferredbehaviour);
}
if (!empty($this->inputs)) {
foreach ($this->inputs as $input) {
if ($input->get_extra_option('manualgraded')) {
return question_engine::make_behaviour('manualgraded', $qa, $preferredbehaviour);
}
}
}
if ($preferredbehaviour == 'adaptive' || $preferredbehaviour == 'adaptivenopenalty') {
return question_engine::make_behaviour('adaptivemultipart', $qa, $preferredbehaviour);
}
if ($preferredbehaviour == 'deferredfeedback' && $this->any_inputs_require_validation()) {
return question_engine::make_behaviour('dfexplicitvaildate', $qa, $preferredbehaviour);
}
if ($preferredbehaviour == 'deferredcbm' && $this->any_inputs_require_validation()) {
return question_engine::make_behaviour('dfcbmexplicitvaildate', $qa, $preferredbehaviour);
}
return parent::make_behaviour($qa, $preferredbehaviour);
}
public function start_attempt(question_attempt_step $step, $variant) {
// @codingStandardsIgnoreStart
// Work out the right seed to use.
if (!is_null($this->seed)) {
// This empty if statement is a hack, but if seed has already been set, then use that.
// This is used by the questiontestrun.php script to allow non-deployed
// variants to be browsed.
} else if (!$this->has_random_variants()) {
// Randomisation not used.
$this->seed = 1;
} else if (!empty($this->deployedseeds)) {
// Question has a fixed number of variants.
$this->seed = $this->deployedseeds[$variant - 1] + 0;
// Don't know why this is coming out as a string. + 0 converts to int.
} else {
// This question uses completely free randomisation.
$this->seed = $variant;
}
// @codingStandardsIgnoreEnd
$step->set_qt_var('_seed', $this->seed);
$this->initialise_question_from_seed();
}
/**
* Once we know the random seed, we can initialise all the other parts of the question.
*/
public function initialise_question_from_seed() {
// We can detect a logically faulty question by checking if the cache can
// return anything if it can't then we can simply skip to the output of errors.
if ($this->get_cached('units') !== null) {
// Build up the question session out of all the bits that need to go into it.
// 1. question variables.
$session = new stack_cas_session2([], $this->options, $this->seed);
// If we are using localisation we should tell the CAS side logic about it.
// For castext rendering and other tasks.
if (count($this->get_cached('langs')) > 0) {
$ml = new stack_multilang();
$selected = $ml->pick_lang($this->get_cached('langs'));
$session->add_statement(new stack_secure_loader('%_STACK_LANG:' .
stack_utils::php_string_to_maxima_string($selected), 'language setting'), false);
}
// Construct the security object. But first units declaration into the session.
$units = (boolean) $this->get_cached('units');
// If we have units we might as well include the units declaration in the session.
// To simplify authors work and remove the need to call that long function.
// TO-DO: Maybe add this to the preable to save lines, but for now documented here.
if ($units) {
$session->add_statement(new stack_secure_loader('stack_unit_si_declare(true)',
'automatic unit declaration'), false);
}
if ($this->get_cached('preamble-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('preamble-qv'), '/pb',
'blockexternal'));
}
// Context variables should be first.
if ($this->get_cached('contextvariables-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('contextvariables-qv'), '/qv'));
}
if ($this->get_cached('statement-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('statement-qv'), '/qv'));
}
// Note that at this phase the security object has no "words".
// The student's answer may not contain any of the variable names with which
// the teacher has defined question variables. Otherwise when it is evaluated
// in a PRT, the student's answer will take these values. If the teacher defines
// 'ta' to be the answer, the student could type in 'ta'! We forbid this.
// TO-DO: shouldn't we also protect variables used in PRT logic? Feedback vars
// and so on?
$forbiddenkeys = [];
if ($this->get_cached('forbiddenkeys') !== null) {
$forbiddenkeys = $this->get_cached('forbiddenkeys');
}
$this->security = new stack_cas_security($units, '', '', $forbiddenkeys);
// The session to keep. Note we do not need to reinstantiate the teachers answers.
$sessiontokeep = new stack_cas_session2($session->get_session(), $this->options, $this->seed);
// 2. correct answer for all inputs.
foreach ($this->inputs as $name => $input) {
$cs = stack_ast_container::make_from_teacher_source($input->get_teacher_answer(),
'', $this->security);
$this->tas[$name] = $cs;
$session->add_statement($cs);
}
// Check for signs of errors.
if ($this->get_cached('static-castext-strings') === null) {
throw new stack_exception(implode('; ', array_keys($this->runtimeerrors)));
}
// 3.0 setup common CASText2 staticreplacer.
$static = new castext2_static_replacer($this->get_cached('static-castext-strings'));
// 3. CAS bits inside the question text.
$questiontext = castext2_evaluatable::make_from_compiled($this->get_cached('castext-qt'), '/qt', $static);
if ($questiontext->requires_evaluation()) {
$session->add_statement($questiontext);
}
// 4. CAS bits inside the specific feedback.
$feedbacktext = castext2_evaluatable::make_from_compiled($this->get_cached('castext-sf'), '/sf', $static);
if ($feedbacktext->requires_evaluation()) {
$session->add_statement($feedbacktext);
}
// Add the context to the security, needs some unpacking of the cached.
if ($this->get_cached('security-context') === null) {
$this->security->set_context([]);
} else {
$this->security->set_context($this->get_cached('security-context'));
}
// The session to keep. Note we do not need to reinstantiate the teachers answers.
$sessiontokeep = new stack_cas_session2($session->get_session(), $this->options, $this->seed);
// 5. CAS bits inside the question note.
$notetext = castext2_evaluatable::make_from_compiled($this->get_cached('castext-qn'), '/qn', $static);
if ($notetext->requires_evaluation()) {
$session->add_statement($notetext);
}
// 6. The standard PRT feedback.
$prtcorrect = castext2_evaluatable::make_from_compiled($this->get_cached('castext-prt-c'),
'/pc', $static);
$prtpartiallycorrect = castext2_evaluatable::make_from_compiled($this->get_cached('castext-prt-pc'),
'/pp', $static);
$prtincorrect = castext2_evaluatable::make_from_compiled($this->get_cached('castext-prt-ic'),
'/pi', $static);
if ($prtcorrect->requires_evaluation()) {
$session->add_statement($prtcorrect);
}
if ($prtpartiallycorrect->requires_evaluation()) {
$session->add_statement($prtpartiallycorrect);
}
if ($prtincorrect->requires_evaluation()) {
$session->add_statement($prtincorrect);
}
// Now instantiate the session.
if ($session->get_valid()) {
$session->instantiate();
}
if ($session->get_errors()) {
// In previous versions we threw an exception here.
// Upgrade and import stops errors being caught during validation when the question was edited or deployed.
// This breaks bulk testing in a nasty way.
$this->runtimeerrors[$session->get_errors(true)] = true;
}
// Finally, store only those values really needed for later.
$this->questiontextinstantiated = $questiontext;
if ($questiontext->get_errors()) {
$s = stack_string('runtimefielderr',
['field' => stack_string('questiontext'), 'err' => $questiontext->get_errors()]);
$this->runtimeerrors[$s] = true;
}
$this->specificfeedbackinstantiated = $feedbacktext;
if ($feedbacktext->get_errors()) {
$s = stack_string('runtimefielderr',
['field' => stack_string('specificfeedback'), 'err' => $feedbacktext->get_errors()]);
$this->runtimeerrors[$s] = true;
}
$this->questionnoteinstantiated = $notetext;
if ($notetext->get_errors()) {
$s = stack_string('runtimefielderr',
['field' => stack_string('questionnote'), 'err' => $notetext->get_errors()]);
$this->runtimeerrors[$s] = true;
}
$this->prtcorrectinstantiated = $prtcorrect;
$this->prtpartiallycorrectinstantiated = $prtpartiallycorrect;
$this->prtincorrectinstantiated = $prtincorrect;
$this->session = $sessiontokeep;
if ($sessiontokeep->get_errors()) {
$s = stack_string('runtimefielderr',
['field' => stack_string('questionvariables'), 'err' => $sessiontokeep->get_errors(true)]);
$this->runtimeerrors[$s] = true;
}
// Allow inputs to update themselves based on the model answers.
$this->adapt_inputs();
}
if ($this->runtimeerrors) {
// It is quite possible that questions will, legitimately, throw some kind of error.
// For example, if one of the question variables is 1/0.
// This should not be a show stopper.
// Something has gone wrong here, and the student will be shown nothing.
$s = html_writer::tag('span', stack_string('runtimeerror'), ['class' => 'stackruntimeerrror']);
$errmsg = '';
foreach ($this->runtimeerrors as $key => $val) {
$errmsg .= html_writer::tag('li', $key);
}
$s .= html_writer::tag('ul', $errmsg);
// So we have this logic where a raw string needs to turn to a CASText2 object.
// As we do not know what it contains we escape it.
$this->questiontextinstantiated = castext2_evaluatable::make_from_source('[[escape]]' . $s . '[[/escape]]', '/qt');
// It is a static string and by calling this we make it look like it was evaluated.
$this->questiontextinstantiated->requires_evaluation();
// Do some setup for the features that do not work.
$this->security = new stack_cas_security();
$this->tas = [];
$this->session = new stack_cas_session2([]);
}
}
public function apply_attempt_state(question_attempt_step $step) {
$this->seed = (int) $step->get_qt_var('_seed');
$this->initialise_question_from_seed();
}
/**
* Give all the input elements a chance to configure themselves given the
* teacher's model answers.
*/
protected function adapt_inputs() {
foreach ($this->inputs as $name => $input) {
// TO-DO: again should we give the whole thing to the input.
$teacheranswer = '';
if ($this->tas[$name]->is_correctly_evaluated()) {
$teacheranswer = $this->tas[$name]->get_value();
}
if ($this->get_cached('preamble-qv') !== null) {
$input->add_contextsession(new stack_secure_loader($this->get_cached('preamble-qv'), '/pb',
'blockexternal'));
}
if ($this->get_cached('contextvariables-qv') !== null) {
$input->add_contextsession(new stack_secure_loader($this->get_cached('contextvariables-qv'), '/qv'));
}
$input->adapt_to_model_answer($teacheranswer);
}
}
/**
* Get the cattext for a hint, instantiated within the question's session.
* @param question_hint $hint the hint.
* @return stack_cas_text the castext.
*/
public function get_hint_castext(question_hint $hint) {
// TO-DO: These are not currently cached as compiled fragments, maybe they should be.
$hinttext = castext2_evaluatable::make_from_source($hint->hint, 'hint');
$session = null;
if ($this->session === null) {
$session = new stack_cas_session2([], $this->options, $this->seed);
} else {
$session = new stack_cas_session2($this->session->get_session(), $this->options, $this->seed);
}
if (count($this->get_cached('langs')) > 0) {
$ml = new stack_multilang();
$selected = $ml->pick_lang($this->get_cached('langs'));
$session->add_statement(new stack_secure_loader('%_STACK_LANG:' .
stack_utils::php_string_to_maxima_string($selected), 'language setting'), false);
}
$session->add_statement($hinttext);
$session->instantiate();
if ($hinttext->get_errors()) {
$this->runtimeerrors[$hinttext->get_errors()] = true;
}
return $hinttext;
}
/**
* Get the cattext for the general feedback, instantiated within the question's session.
* @return stack_cas_text the castext.
*/
public function get_generalfeedback_castext() {
// Could be that this is instantiated already.
if ($this->generalfeedbackinstantiated !== null) {
return $this->generalfeedbackinstantiated;
}
// We can have a failed question.
if ($this->get_cached('castext-gf') === null) {
$ct = castext2_evaluatable::make_from_compiled('"Broken question."', '/gf',
new castext2_static_replacer([])); // This mainly for the bulk-test script.
$ct->requires_evaluation(); // Makes it as if it were evaluated.
return $ct;
}
$this->generalfeedbackinstantiated = castext2_evaluatable::make_from_compiled($this->get_cached('castext-gf'),
'/gf', new castext2_static_replacer($this->get_cached('static-castext-strings')));
// Might not require any evaluation anyway.
if (!$this->generalfeedbackinstantiated->requires_evaluation()) {
return $this->generalfeedbackinstantiated;
}
// Init a session with question-variables and the related details.
$session = new stack_cas_session2([], $this->options, $this->seed);
if (count($this->get_cached('langs')) > 0) {
$ml = new stack_multilang();
$selected = $ml->pick_lang($this->get_cached('langs'));
$session->add_statement(new stack_secure_loader('%_STACK_LANG:' .
stack_utils::php_string_to_maxima_string($selected), 'language setting'), false);
}
if ($this->get_cached('preamble-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('preamble-qv'), '/pb', 'blockexternal'));
}
if ($this->get_cached('contextvariables-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('contextvariables-qv'), '/qv'));
}
if ($this->get_cached('statement-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('statement-qv'), '/qv'));
}
// Then add the general-feedback code.
$session->add_statement($this->generalfeedbackinstantiated);
$session->instantiate();
if ($this->generalfeedbackinstantiated->get_errors()) {
$this->runtimeerrors[$this->generalfeedbackinstantiated->get_errors()] = true;
}
return $this->generalfeedbackinstantiated;
}
/**
* Get the cattext for the question description, instantiated within the question's session.
* @return stack_cas_text the castext.
*/
public function get_questiondescription_castext() {
// Could be that this is instantiated already.
if ($this->questiondescriptioninstantiated !== null) {
return $this->questiondescriptioninstantiated;
}
// We can have a failed question.
if ($this->get_cached('castext-gf') === null) {
$ct = castext2_evaluatable::make_from_compiled('"Broken question."', '/gf',
new castext2_static_replacer([])); // This mainly for the bulk-test script.
$ct->requires_evaluation(); // Makes it as if it were evaluated.
return $ct;
}
$this->questiondescriptioninstantiated = castext2_evaluatable::make_from_compiled($this->get_cached('castext-qd'),
'/qd', new castext2_static_replacer($this->get_cached('static-castext-strings')));
// Might not require any evaluation anyway.
if (!$this->questiondescriptioninstantiated->requires_evaluation()) {
return $this->questiondescriptioninstantiated;
}
// Init a session with question-variables and the related details.
$session = new stack_cas_session2([], $this->options, $this->seed);
if (count($this->get_cached('langs')) > 0) {
$ml = new stack_multilang();
$selected = $ml->pick_lang($this->get_cached('langs'));
$session->add_statement(new stack_secure_loader('%_STACK_LANG:' .
stack_utils::php_string_to_maxima_string($selected), 'language setting'), false);
}
if ($this->get_cached('preamble-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('preamble-qv'), '/pb',
'blockexternal'));
}
if ($this->get_cached('contextvariables-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('contextvariables-qv'), '/qv'));
}
if ($this->get_cached('statement-qv') !== null) {
$session->add_statement(new stack_secure_loader($this->get_cached('statement-qv'), '/qv'));
}
// Then add the description code.
$session->add_statement($this->questiondescriptioninstantiated);
$session->instantiate();
if ($this->questiondescriptioninstantiated->get_errors()) {
$this->runtimeerrors[$this->questiondescriptioninstantiated->get_errors()] = true;
}
return $this->questiondescriptioninstantiated;
}
/**
* We need to make sure the inputs are displayed in the order in which they
* occur in the question text. This is not necessarily the order in which they
* are listed in the array $this->inputs.
*/
public function format_correct_response($qa) {
$feedback = '';
$inputs = stack_utils::extract_placeholders($this->questiontextinstantiated->get_rendered(), 'input');
foreach ($inputs as $name) {
$input = $this->inputs[$name];
$feedback .= html_writer::tag('p', $input->get_teacher_answer_display($this->tas[$name]->get_dispvalue(),
$this->tas[$name]->get_latex()));
}
return stack_ouput_castext($feedback);
}
public function get_expected_data() {
$expected = ['step_lang' => 'raw'];
foreach ($this->inputs as $input) {
$expected += $input->get_expected_data();
}
return $expected;
}
public function get_question_summary() {
$processor = new castext2_qa_processor(new stack_outofcontext_process());
if ($this->questionnoteinstantiated !== null &&
'' !== $this->questionnoteinstantiated->get_rendered($processor)) {
return $this->questionnoteinstantiated->get_rendered($processor);
}
return stack_string('questionnote_missing');
}
public function get_question_todos() {
$hastodos = false;
$tags = [];
$fields = [$this->questiontext, $this->questionnote, $this->generalfeedback,
$this->specificfeedback, $this->questiondescription, ];
$pat = '/\[\[todo/';
foreach ($fields as $field) {
// We _should_ use castext2_parser_utils::has_todoblocks($field) really, but this
// involves parsing the castext which is too slow.
if (preg_match($pat, $field ?? '')) {
$hastodos = true;
$tags = array_merge($tags, castext2_parser_utils::get_todoblocks($field));
}
}
// Unique tags, sorted.
$tags = array_unique($tags);
sort($tags);
return [$hastodos, $tags];
}
public function summarise_response(array $response) {
// Provide seed information on student's version via the normal moodle quiz report.
$bits = ['Seed: ' . $this->seed];
foreach ($this->inputs as $name => $input) {
$state = $this->get_input_state($name, $response);
if (stack_input::BLANK != $state->status) {
$bits[] = $input->summarise_response($name, $state, $response);
}
}
// Add in the answer note for this response.
foreach ($this->prts as $name => $prt) {
$state = $this->get_prt_result($name, $response, false);
$note = implode(' | ', array_map('trim', $state->get_answernotes()));
$score = '';
if (trim($note) == '') {
$note = '!';
} else {
$score = "# = " . $state->get_score();
if ($prt->is_formative()) {
$score .= ' [formative]';
}
$score .= " | ";
}
if ($state->get_errors()) {
$score = '[RUNTIME_ERROR] ' . $score . implode("|", $state->get_errors());
}
if ($state->get_fverrors()) {
$score = '[RUNTIME_FV_ERROR] ' . $score . implode("|", $state->get_fverrors()) . ' | ';
}
$bits[] = $name . ": " . $score . $note;
}
return implode('; ', $bits);
}
// Used in reporting - needs to return an array.
public function summarise_response_data(array $response) {
$bits = [];
foreach ($this->inputs as $name => $input) {
$state = $this->get_input_state($name, $response);
$bits[$name] = $state->status;
}
return $bits;
}
public function get_correct_response() {
$teacheranswer = [];
if ($this->runtimeerrors || $this->get_cached('units') === null) {
return [];
}
foreach ($this->inputs as $name => $input) {
$teacheranswer = array_merge($teacheranswer,
$input->get_correct_response($this->tas[$name]->get_dispvalue()));
}
return $teacheranswer;
}
/*
* This function returns an array of values for inputs which could be typed into Maxima.
* Used in the caschat function as possible input values.
*/
public function get_correct_response_testcase() {
$teacheranswer = [];
if ($this->runtimeerrors || $this->get_cached('units') === null) {
return [];
}
foreach ($this->inputs as $name => $input) {
$teacheranswer[$name] = $input->get_teacher_answer_testcase($this->tas[$name]->get_dispvalue());
}
return $teacheranswer;
}
public function is_same_response(array $prevresponse, array $newresponse) {
foreach ($this->get_expected_data() as $name => $notused) {
if (!question_utils::arrays_same_at_key_missing_is_blank(
$prevresponse, $newresponse, $name)) {
return false;
}
}
return true;
}
public function is_same_response_for_part($index, array $prevresponse, array $newresponse) {
$previnput = $this->get_prt_input($index, $prevresponse, true);
$newinput = $this->get_prt_input($index, $newresponse, true);
return $this->is_same_prt_input($index, $previnput, $newinput);
}
/**
* Get the results of validating one of the input elements.
* @param string $name the name of one of the input elements.
* @param array $response the response, in Maxima format.
* @param bool $rawinput the response in raw form. Needs converting to Maxima format by the input.
* @return stack_input_state|string the result of calling validate_student_response() on the input.
*/
public function get_input_state($name, $response, $rawinput=false) {
$this->validate_cache($response, null);
if (array_key_exists($name, $this->inputstates)) {
return $this->inputstates[$name];
}
$lang = null;
if ($this->get_cached('langs') !== null && count($this->get_cached('langs')) > 0) {
$ml = new stack_multilang();
$lang = $ml->pick_lang($this->get_cached('langs'));
}
// TO-DO: we should probably give the whole ast_container to the input.
// Direct access to LaTeX and the AST might be handy.
$teacheranswer = '';
if (array_key_exists($name, $this->tas)) {
if ($this->tas[$name]->is_correctly_evaluated()) {
$teacheranswer = $this->tas[$name]->get_value();
}
}
if (array_key_exists($name, $this->inputs)) {
$qv = [];
$qv['preamble-qv'] = $this->get_cached('preamble-qv');
$qv['contextvariables-qv'] = $this->get_cached('contextvariables-qv');
$qv['statement-qv'] = $this->get_cached('statement-qv');
$this->inputstates[$name] = $this->inputs[$name]->validate_student_response(
$response, $this->options, $teacheranswer, $this->security, $rawinput,
$this->castextprocessor, $qv, $lang);
return $this->inputstates[$name];
}
return '';
}
/**
* @param array $response the current response being processed.
* @return boolean whether any of the inputs are blank.
*/
public function is_any_input_blank(array $response) {
foreach ($this->inputs as $name => $input) {
if (stack_input::BLANK == $this->get_input_state($name, $response)->status) {
return true;
}
}
return false;
}
public function is_any_part_invalid(array $response) {
// Invalid if any input is invalid, ...
foreach ($this->inputs as $name => $input) {
if (stack_input::INVALID == $this->get_input_state($name, $response)->status) {
return true;
}
}
// ... or any PRT gives an error.
foreach ($this->prts as $name => $prt) {
$result = $this->get_prt_result($name, $response, false);
if ($result->get_errors()) {
return true;
}
}
return false;
}
public function is_complete_response(array $response) {
// If all PRTs are gradable, then the question is complete. Optional inputs may be blank.
foreach ($this->prts as $prt) {
// Formative PRTs do not contribute to complete responses.
if (!$prt->is_formative() && !$this->can_execute_prt($prt, $response, false)) {
return false;
}
}
// If there are no PRTs, then check that all inputs are complete.
if (!$this->prts) {
foreach ($this->inputs as $name => $notused) {
if (stack_input::SCORE != $this->get_input_state($name, $response)->status) {
return false;
}
}
}
return true;
}
public function is_gradable_response(array $response) {
// Manually graded answers are always gradable.
if (!empty($this->inputs)) {
foreach ($this->inputs as $input) {
if ($input->get_extra_option('manualgraded')) {
return true;
}
}
}
// If any PRT is gradable, then we can grade the question.
$noprts = true;
foreach ($this->prts as $index => $prt) {
$noprts = false;
// Whether formative PRTs can be executed is not relevant to gradability.
if (!$prt->is_formative() && $this->can_execute_prt($prt, $response, true)) {
return true;
}
}
// In the case of no PRTs, questions are in state "is_gradable" if we have
// at least one input in the "score" or "valid" state.
if ($noprts) {
foreach ($this->inputstates as $key => $inputstate) {
if ($inputstate->status == 'score' || $inputstate->status == 'valid') {
return true;
}
}
}
// Otherwise we are not "is_gradable".
return false;
}
public function get_validation_error(array $response) {
if ($this->is_any_part_invalid($response)) {
// There will already be a more specific validation error displayed.
return '';
} else if ($this->is_any_input_blank($response)) {
return stack_string('pleaseananswerallparts');
} else {
return stack_string('pleasecheckyourinputs');
}
}
public function grade_response(array $response) {
$fraction = 0;
// If we have one or more notes input which needs manual grading, then mark it as needs grading.
if (!empty($this->inputs)) {
foreach ($this->inputs as $input) {
if ($input->get_extra_option('manualgraded')) {
return question_state::$needsgrading;
}
}
}
foreach ($this->prts as $name => $prt) {
if (!$prt->is_formative()) {
$results = $this->get_prt_result($name, $response, true);
$fraction += $results->get_fraction();
}
}