forked from maths/moodle-qtype_stack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
questiontype.php
2166 lines (1887 loc) · 105 KB
/
questiontype.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/>.
/**
* Question type class for the Stack question type.
*
* @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($CFG->libdir . '/questionlib.php');
require_once(__DIR__ . '/stack/input/factory.class.php');
require_once(__DIR__ . '/stack/answertest/controller.class.php');
require_once(__DIR__ . '/stack/cas/keyval.class.php');
require_once(__DIR__ . '/stack/cas/castext.class.php');
require_once(__DIR__ . '/stack/questiontest.php');
require_once(__DIR__ . '/stack/graphlayout/graph.php');
require_once(__DIR__ . '/lang/multilang.php');
/**
* Stack question type class.
*
* @copyright 2012 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_stack extends question_type {
/** @var int array key into the results of get_input_names_from_question_text for the count of input placeholders. */
const INPUTS = 0;
/** @var int array key into the results of get_input_names_from_question_text for the count of validation placeholders. */
const VALIDATIONS = 1;
/** @var int the CAS seed using during validation. */
protected $seed = 1;
/** @var stack_options the CAS options using during validation. */
protected $options;
/**
* @var array prt name => stack_abstract_graph caches the result of
* {@link get_prt_graph()}.
*/
protected $prtgraph = array();
public function save_question($question, $fromform) {
if (!empty($fromform->fixdollars)) {
$this->fix_dollars_in_form_data($fromform);
}
$fromform->penalty = stack_utils::fix_approximate_thirds($fromform->penalty);
return parent::save_question($question, $fromform);
}
/**
* Replace any $...$ and $$...$$ delimiters in the question text from the
* form with the recommended delimiters.
* @param object $fromform the data from the form.
*/
protected function fix_dollars_in_form_data($fromform) {
$questionfields = array('questiontext', 'generalfeedback', 'specificfeedback',
'prtcorrect', 'prtpartiallycorrect', 'prtincorrect');
foreach ($questionfields as $field) {
$fromform->{$field}['text'] = stack_maths::replace_dollars($fromform->{$field}['text']);
}
$fromform->questionnote = stack_maths::replace_dollars($fromform->questionnote);
$prtnames = array_keys($this->get_prt_names_from_question($fromform->questiontext['text'],
$fromform->specificfeedback['text']));
foreach ($prtnames as $prt) {
foreach ($fromform->{$prt . 'truefeedback'} as &$feedback) {
$feedback['text'] = stack_maths::replace_dollars($feedback['text']);
}
foreach ($fromform->{$prt . 'falsefeedback'} as &$feedback) {
$feedback['text'] = stack_maths::replace_dollars($feedback['text']);
}
}
foreach ($fromform->hint as &$hint) {
$hint['text'] = stack_maths::replace_dollars($hint['text']);
}
}
public function save_question_options($fromform) {
global $DB;
$context = $fromform->context;
parent::save_question_options($fromform);
$options = $DB->get_record('qtype_stack_options', array('questionid' => $fromform->id));
if (!$options) {
$options = new stdClass();
$options->questionid = $fromform->id;
$options->stackversion = '';
$options->questionvariables = '';
$options->questionnote = '';
$options->specificfeedback = '';
$options->prtcorrect = '';
$options->prtpartiallycorrect = '';
$options->prtincorrect = '';
$options->stackversion = get_config('qtype_stack', 'version');
$options->id = $DB->insert_record('qtype_stack_options', $options);
}
$options->stackversion = $fromform->stackversion;
$options->questionvariables = $fromform->questionvariables;
$options->specificfeedback = $this->import_or_save_files($fromform->specificfeedback,
$context, 'qtype_stack', 'specificfeedback', $fromform->id);
$options->specificfeedbackformat = $fromform->specificfeedback['format'];
$options->questionnote = $fromform->questionnote;
$options->questionsimplify = $fromform->questionsimplify;
$options->assumepositive = $fromform->assumepositive;
$options->assumereal = $fromform->assumereal;
$options->prtcorrect = $this->import_or_save_files($fromform->prtcorrect,
$context, 'qtype_stack', 'prtcorrect', $fromform->id);
$options->prtcorrectformat = $fromform->prtcorrect['format'];
$options->prtpartiallycorrect = $this->import_or_save_files($fromform->prtpartiallycorrect,
$context, 'qtype_stack', 'prtpartiallycorrect', $fromform->id);
$options->prtpartiallycorrectformat = $fromform->prtpartiallycorrect['format'];
$options->prtincorrect = $this->import_or_save_files($fromform->prtincorrect,
$context, 'qtype_stack', 'prtincorrect', $fromform->id);
$options->prtincorrectformat = $fromform->prtincorrect['format'];
$options->multiplicationsign = $fromform->multiplicationsign;
$options->sqrtsign = $fromform->sqrtsign;
$options->complexno = $fromform->complexno;
$options->inversetrig = $fromform->inversetrig;
$options->matrixparens = $fromform->matrixparens;
$options->variantsselectionseed = $fromform->variantsselectionseed;
$DB->update_record('qtype_stack_options', $options);
$inputnames = array_keys($this->get_input_names_from_question_text_lang($fromform->questiontext));
$inputs = $DB->get_records('qtype_stack_inputs',
array('questionid' => $fromform->id), '', 'name, id, questionid');
$questionhasinputs = false;
foreach ($inputnames as $inputname) {
if (array_key_exists($inputname, $inputs)) {
$input = $inputs[$inputname];
unset($inputs[$inputname]);
} else {
$input = new stdClass();
$input->questionid = $fromform->id;
$input->name = $inputname;
$input->options = '';
$input->id = $DB->insert_record('qtype_stack_inputs', $input);
}
$input->type = $fromform->{$inputname . 'type'};
$input->tans = $fromform->{$inputname . 'modelans'};
$input->boxsize = $fromform->{$inputname . 'boxsize'};
$input->strictsyntax = $fromform->{$inputname . 'strictsyntax'};
$input->insertstars = $fromform->{$inputname . 'insertstars'};
$input->syntaxhint = $fromform->{$inputname . 'syntaxhint'};
$input->syntaxattribute = $fromform->{$inputname . 'syntaxattribute'};
$input->forbidwords = $fromform->{$inputname . 'forbidwords'};
$input->allowwords = $fromform->{$inputname . 'allowwords'};
$input->forbidfloat = $fromform->{$inputname . 'forbidfloat'};
$input->requirelowestterms = $fromform->{$inputname . 'requirelowestterms'};
$input->checkanswertype = $fromform->{$inputname . 'checkanswertype'};
$input->mustverify = $fromform->{$inputname . 'mustverify'};
$input->showvalidation = $fromform->{$inputname . 'showvalidation'};
$input->options = $fromform->{$inputname . 'options'};
$questionhasinputs = true;
$DB->update_record('qtype_stack_inputs', $input);
}
if ($inputs) {
list($test, $params) = $DB->get_in_or_equal(array_keys($inputs));
$params[] = $fromform->id;
$DB->delete_records_select('qtype_stack_inputs',
'name ' . $test . ' AND questionid = ?', $params);
}
if (!$questionhasinputs) {
// A question with no inputs is an information item.
$DB->set_field('question', 'length', 0, array('id' => $fromform->id));
}
$prtnames = array_keys($this->get_prt_names_from_question($fromform->questiontext, $options->specificfeedback));
$prts = $DB->get_records('qtype_stack_prts',
array('questionid' => $fromform->id), '', 'name, id, questionid');
foreach ($prtnames as $prtname) {
if (array_key_exists($prtname, $prts)) {
$prt = $prts[$prtname];
unset($prts[$prtname]);
} else {
$prt = new stdClass();
$prt->questionid = $fromform->id;
$prt->name = $prtname;
$prt->feedbackvariables = '';
$prt->firstnodename = 0;
$prt->id = $DB->insert_record('qtype_stack_prts', $prt);
}
// Find the root node of the PRT.
// Otherwise, if an existing question is being edited, and this is an
// existing PRT, base things on the existing question definition.
$graph = new stack_abstract_graph();
foreach ($fromform->{$prtname . 'answertest'} as $nodename => $notused) {
$truenextnode = $fromform->{$prtname . 'truenextnode'}[$nodename];
$falsenextnode = $fromform->{$prtname . 'falsenextnode'}[$nodename];
if ($truenextnode == -1) {
$left = null;
} else {
$left = $truenextnode + 1;
}
if ($falsenextnode == -1) {
$right = null;
} else {
$right = $falsenextnode + 1;
}
$graph->add_node($nodename + 1, $left, $right);
}
$graph->layout();
$roots = $graph->get_roots();
if (count($roots) != 1 || $graph->get_broken_cycles()) {
throw new coding_exception('The PRT ' . $prtname . ' is malformed.');
}
reset($roots);
$firstnode = key($roots) - 1;
$prt->value = $fromform->{$prtname . 'value'};
$prt->autosimplify = $fromform->{$prtname . 'autosimplify'};
$prt->feedbackvariables = $fromform->{$prtname . 'feedbackvariables'};
$prt->firstnodename = $firstnode;
$DB->update_record('qtype_stack_prts', $prt);
$nodes = $DB->get_records('qtype_stack_prt_nodes',
array('questionid' => $fromform->id, 'prtname' => $prtname),
'', 'nodename, id, questionid, prtname');
foreach ($fromform->{$prtname . 'answertest'} as $nodename => $notused) {
if (array_key_exists($nodename, $nodes)) {
$node = $nodes[$nodename];
unset($nodes[$nodename]);
} else {
$node = new stdClass();
$node->questionid = $fromform->id;
$node->prtname = $prtname;
$node->nodename = $nodename;
$node->truefeedback = '';
$node->falsefeedback = '';
$node->id = $DB->insert_record('qtype_stack_prt_nodes', $node);
}
$node->answertest = $fromform->{$prtname . 'answertest'}[$nodename];
$node->sans = $fromform->{$prtname . 'sans'}[$nodename];
$node->tans = $fromform->{$prtname . 'tans'}[$nodename];
$node->testoptions = $fromform->{$prtname . 'testoptions'}[$nodename];
$node->quiet = $fromform->{$prtname . 'quiet'}[$nodename];
$node->truescoremode = $fromform->{$prtname . 'truescoremode'}[$nodename];
$node->truescore = $fromform->{$prtname . 'truescore'}[$nodename];
$node->truepenalty = stack_utils::fix_approximate_thirds(
$fromform->{$prtname . 'truepenalty'}[$nodename]);
$node->truenextnode = $fromform->{$prtname . 'truenextnode'}[$nodename];
$node->trueanswernote = $fromform->{$prtname . 'trueanswernote'}[$nodename];
$node->truefeedback = $this->import_or_save_files(
$fromform->{$prtname . 'truefeedback'}[$nodename],
$context, 'qtype_stack', 'prtnodetruefeedback', $node->id);
$node->truefeedbackformat = $fromform->{$prtname . 'truefeedback'}[$nodename]['format'];
$node->falsescoremode = $fromform->{$prtname . 'falsescoremode'}[$nodename];
$node->falsescore = $fromform->{$prtname . 'falsescore'}[$nodename];
$node->falsepenalty = stack_utils::fix_approximate_thirds(
$fromform->{$prtname . 'falsepenalty'}[$nodename]);
$node->falsenextnode = $fromform->{$prtname . 'falsenextnode'}[$nodename];
$node->falseanswernote = $fromform->{$prtname . 'falseanswernote'}[$nodename];
$node->falsefeedback = $this->import_or_save_files(
$fromform->{$prtname . 'falsefeedback'}[$nodename],
$context, 'qtype_stack', 'prtnodefalsefeedback', $node->id);
$node->falsefeedbackformat = $fromform->{$prtname . 'falsefeedback'}[$nodename]['format'];
if ('' === $node->truepenalty) {
$node->truepenalty = null;
}
if ('' === $node->falsepenalty) {
$node->falsepenalty = null;
}
$DB->update_record('qtype_stack_prt_nodes', $node);
}
if ($nodes) {
list($test, $params) = $DB->get_in_or_equal(array_keys($nodes));
$params[] = $fromform->id;
$params[] = $prt->name;
$DB->delete_records_select('qtype_stack_prt_nodes',
'nodename ' . $test . ' AND questionid = ? AND prtname = ?', $params);
}
}
if ($prts) {
list($test, $params) = $DB->get_in_or_equal(array_keys($prts));
$params[] = $fromform->id;
$DB->delete_records_select('qtype_stack_prt_nodes',
'prtname ' . $test . ' AND questionid = ?', $params);
$DB->delete_records_select('qtype_stack_prts',
'name ' . $test . ' AND questionid = ?', $params);
}
$this->save_hints($fromform);
if (isset($fromform->deployedseeds)) {
$DB->delete_records('qtype_stack_deployed_seeds', array('questionid' => $fromform->id));
foreach ($fromform->deployedseeds as $deployedseed) {
$record = new stdClass();
$record->questionid = $fromform->id;
$record->seed = $deployedseed;
$DB->insert_record('qtype_stack_deployed_seeds', $record, false);
}
}
// This is a bit of a hack. If doing 'Make a copy' when saving the
// editing form, then detect that here, and try to copy the question
// tests from the original question.
if (!isset($fromform->testcases) && !empty($fromform->makecopy)) {
$oldquestionid = optional_param('id', 0, PARAM_INT);
if ($oldquestionid) {
$fromform->testcases = $this->load_question_tests($oldquestionid);
}
}
if (isset($fromform->testcases)) {
// If the data includes the defintion of the question tests that there
// should be (i.e. when doing import) then replace the existing set
// of tests with the new one.
$this->save_question_tests($fromform->id, $fromform->testcases);
}
// Irrespective of what else has happened, ensure there is no garbage
// in the database, for example if we delete a PRT, remove the expected
// values for that PRT while leaving the rest of the testcases alone.
list($nametest, $params) = $DB->get_in_or_equal($inputnames, SQL_PARAMS_NAMED, 'input', false, null);
$params['questionid'] = $fromform->id;
$DB->delete_records_select('qtype_stack_qtest_inputs',
'questionid = :questionid AND inputname ' . $nametest, $params);
list($nametest, $params) = $DB->get_in_or_equal($prtnames, SQL_PARAMS_NAMED, 'prt', false, null);
$params['questionid'] = $fromform->id;
$DB->delete_records_select('qtype_stack_qtest_expected',
'questionid = :questionid AND prtname ' . $nametest, $params);
}
public function get_question_options($question) {
global $DB;
parent::get_question_options($question);
$question->options = $DB->get_record('qtype_stack_options',
array('questionid' => $question->id), '*', MUST_EXIST);
$question->inputs = $DB->get_records('qtype_stack_inputs',
array('questionid' => $question->id), 'name',
'name, id, questionid, type, tans, boxsize, strictsyntax, insertstars, ' .
'syntaxhint, syntaxattribute, forbidwords, allowwords, forbidfloat, requirelowestterms, ' .
'checkanswertype, mustverify, showvalidation, options');
$question->prts = $DB->get_records('qtype_stack_prts',
array('questionid' => $question->id), 'name',
'name, id, questionid, value, autosimplify, feedbackvariables, firstnodename');
$noders = $DB->get_recordset('qtype_stack_prt_nodes',
array('questionid' => $question->id),
'prtname, ' . $DB->sql_cast_char2int('nodename'));
foreach ($noders as $node) {
$question->prts[$node->prtname]->nodes[$node->nodename] = $node;
}
$noders->close();
$question->deployedseeds = $DB->get_fieldset_sql('
SELECT seed
FROM {qtype_stack_deployed_seeds}
WHERE questionid = ?
ORDER BY id', array($question->id));
return true;
}
protected function initialise_question_instance(question_definition $question, $questiondata) {
parent::initialise_question_instance($question, $questiondata);
$question->stackversion = $questiondata->options->stackversion;
$question->questionvariables = $questiondata->options->questionvariables;
$question->questionnote = $questiondata->options->questionnote;
$question->specificfeedback = $questiondata->options->specificfeedback;
$question->specificfeedbackformat = $questiondata->options->specificfeedbackformat;
$question->prtcorrect = $questiondata->options->prtcorrect;
$question->prtcorrectformat = $questiondata->options->prtcorrectformat;
$question->prtpartiallycorrect = $questiondata->options->prtpartiallycorrect;
$question->prtpartiallycorrectformat = $questiondata->options->prtpartiallycorrectformat;
$question->prtincorrect = $questiondata->options->prtincorrect;
$question->prtincorrectformat = $questiondata->options->prtincorrectformat;
$question->variantsselectionseed = $questiondata->options->variantsselectionseed;
$question->options = new stack_options();
$question->options->set_option('multiplicationsign', $questiondata->options->multiplicationsign);
$question->options->set_option('complexno', $questiondata->options->complexno);
$question->options->set_option('inversetrig', $questiondata->options->inversetrig);
$question->options->set_option('matrixparens', $questiondata->options->matrixparens);
$question->options->set_option('sqrtsign', (bool) $questiondata->options->sqrtsign);
$question->options->set_option('simplify', (bool) $questiondata->options->questionsimplify);
$question->options->set_option('assumepos', (bool) $questiondata->options->assumepositive);
$question->options->set_option('assumereal', (bool) $questiondata->options->assumereal);
$requiredparams = stack_input_factory::get_parameters_used();
foreach (array_keys($this->get_input_names_from_question_text($question->questiontext)) as $name) {
$inputdata = $questiondata->inputs[$name];
$allparameters = array(
'boxWidth' => $inputdata->boxsize,
'strictSyntax' => (bool) $inputdata->strictsyntax,
'insertStars' => (int) $inputdata->insertstars,
'syntaxHint' => $inputdata->syntaxhint,
'syntaxAttribute' => $inputdata->syntaxattribute,
'forbidWords' => $inputdata->forbidwords,
'allowWords' => $inputdata->allowwords,
'forbidFloats' => (bool) $inputdata->forbidfloat,
'lowestTerms' => (bool) $inputdata->requirelowestterms,
'sameType' => (bool) $inputdata->checkanswertype,
'mustVerify' => (bool) $inputdata->mustverify,
'showValidation' => $inputdata->showvalidation,
'options' => $inputdata->options,
);
$parameters = array();
foreach ($requiredparams[$inputdata->type] as $paramname) {
if ($paramname == 'inputType') {
continue;
}
$parameters[$paramname] = $allparameters[$paramname];
}
$question->inputs[$name] = stack_input_factory::make(
$inputdata->type, $inputdata->name, $inputdata->tans, $question->options, $parameters);
}
$totalvalue = 0;
foreach ($questiondata->prts as $name => $prtdata) {
$totalvalue += $prtdata->value;
}
if ($questiondata->prts && $totalvalue < 0.0000001) {
throw new coding_exception('There is an error authoring your question. ' .
'The $totalvalue, the marks available for the question, must be positive in question ' .
$question->name);
}
$prtnames = array_keys($this->get_prt_names_from_question($question->questiontext, $question->specificfeedback));
foreach ($prtnames as $name) {
$prtdata = $questiondata->prts[$name];
$nodes = array();
foreach ($prtdata->nodes as $nodedata) {
$sans = new stack_cas_casstring($nodedata->sans);
$sans->get_valid('t');
$tans = new stack_cas_casstring($nodedata->tans);
$tans->get_valid('t');
if (is_null($nodedata->falsepenalty) || $nodedata->falsepenalty === '') {
$falsepenalty = $questiondata->penalty;
} else {
$falsepenalty = $nodedata->falsepenalty;
}
if (is_null($nodedata->truepenalty) || $nodedata->truepenalty === '') {
$truepenalty = $questiondata->penalty;
} else {
$truepenalty = $nodedata->truepenalty;
}
$node = new stack_potentialresponse_node($sans, $tans,
$nodedata->answertest, $nodedata->testoptions, (bool) $nodedata->quiet, '', $nodedata->id);
$node->add_branch(0, $nodedata->falsescoremode, $nodedata->falsescore,
$falsepenalty, $nodedata->falsenextnode,
$nodedata->falsefeedback, $nodedata->falsefeedbackformat, $nodedata->falseanswernote);
$node->add_branch(1, $nodedata->truescoremode, $nodedata->truescore,
$truepenalty, $nodedata->truenextnode,
$nodedata->truefeedback, $nodedata->truefeedbackformat, $nodedata->trueanswernote);
$nodes[$nodedata->nodename] = $node;
}
// TODO $feedbackvariables, and $sans, $tans, should probably still be strings
// here, and should be converted to CAS stuff later, only if needed.
if ($prtdata->feedbackvariables) {
$feedbackvariables = new stack_cas_keyval($prtdata->feedbackvariables, null, null, 't');
$feedbackvariables = $feedbackvariables->get_session();
} else {
$feedbackvariables = null;
}
$question->prts[$name] = new stack_potentialresponse_tree($name, '',
(bool) $prtdata->autosimplify, $prtdata->value / $totalvalue,
$feedbackvariables, $nodes, $prtdata->firstnodename);
}
$question->deployedseeds = array_values($questiondata->deployedseeds);
}
public function delete_question($questionid, $contextid) {
global $DB;
$this->delete_question_tests($questionid);
$DB->delete_records('qtype_stack_deployed_seeds', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_prt_nodes', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_prts', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_inputs', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_options', array('questionid' => $questionid));
parent::delete_question($questionid, $contextid);
}
public function move_files($questionid, $oldcontextid, $newcontextid) {
global $DB;
$fs = get_file_storage();
parent::move_files($questionid, $oldcontextid, $newcontextid);
$this->move_files_in_hints($questionid, $oldcontextid, $newcontextid);
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'specificfeedback', $questionid);
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'prtcorrect', $questionid);
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'prtpartiallycorrect', $questionid);
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'prtincorrect', $questionid);
$nodeids = $DB->get_records_menu('qtype_stack_prt_nodes', array('questionid' => $questionid), 'id', 'id,1');
foreach ($nodeids as $nodeid => $notused) {
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'prtnodetruefeedback', $nodeid);
$fs->move_area_files_to_new_context($oldcontextid, $newcontextid,
'qtype_stack', 'prtnodefalsefeedback', $nodeid);
}
}
protected function delete_files($questionid, $contextid) {
global $DB;
$fs = get_file_storage();
parent::delete_files($questionid, $contextid);
$this->delete_files_in_hints($questionid, $contextid);
$fs->delete_area_files($contextid, 'qtype_stack', 'specificfeedback', $questionid);
$fs->delete_area_files($contextid, 'qtype_stack', 'prtcorrect', $questionid);
$fs->delete_area_files($contextid, 'qtype_stack', 'prtpartiallycorrect', $questionid);
$fs->delete_area_files($contextid, 'qtype_stack', 'prtincorrect', $questionid);
$nodeids = $DB->get_records_menu('qtype_stack_prt_nodes', array('questionid' => $questionid), 'id', 'id,1');
foreach ($nodeids as $nodeid => $notused) {
$fs->delete_area_files($oldcontextid, $newcontextid,
'qtype_stack', 'prtnodetruefeedback', $nodeid);
$fs->delete_area_files($oldcontextid, $newcontextid,
'qtype_stack', 'prtnodefalsefeedback', $nodeid);
}
}
/**
* Save a set of question tests for a question, replacing any existing tests.
* @param int $questionid the question id of the question we are manipulating the tests for.
* @param array $testcases testcase number => stack_question_test
*/
public function save_question_tests($questionid, $testcases) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$this->delete_question_tests($questionid);
foreach ($testcases as $number => $testcase) {
$this->save_question_test($questionid, $testcase, $number);
}
$transaction->allow_commit();
}
/**
* Save a question tests for a question, either replacing the test at a given
* number, or adding a new test, either with a given number, or taking the
* first unused number.
* @param int $questionid the question id of the question we are manipulating the tests for.
* @param stack_question_test $qtest
* @param int $testcases testcase number to replace/add. If not given, the first unused number is found.
*/
public function save_question_test($questionid, stack_question_test $qtest, $testcase = null) {
global $DB;
$transaction = $DB->start_delegated_transaction();
if (!$testcase || !$DB->record_exists('qtype_stack_qtests',
array('questionid' => $questionid, 'testcase' => $testcase))) {
// Find the first unused testcase number.
$testcase = $DB->get_field_sql('
SELECT MIN(qt.testcase) + 1
FROM (
SELECT testcase FROM {qtype_stack_qtests} WHERE questionid = ?
UNION
SELECT 0
) qt
LEFT JOIN {qtype_stack_qtests} qt2 ON qt2.questionid = ? AND
qt2.testcase = qt.testcase + 1
WHERE qt2.id IS NULL
', array($questionid, $questionid));
$testcasedata = new stdClass();
$testcasedata->questionid = $questionid;
$testcasedata->testcase = $testcase;
$testcasedata->timemodified = time();
$DB->insert_record('qtype_stack_qtests', $testcasedata);
} else {
$DB->set_field('qtype_stack_qtests', 'timemodified', time(),
array('questionid' => $questionid, 'testcase' => $testcase));
}
// Save the input data.
$DB->delete_records('qtype_stack_qtest_inputs', array('questionid' => $questionid, 'testcase' => $testcase));
foreach ($qtest->inputs as $name => $value) {
$testinput = new stdClass();
$testinput->questionid = $questionid;
$testinput->testcase = $testcase;
$testinput->inputname = $name;
$testinput->value = $value;
$DB->insert_record('qtype_stack_qtest_inputs', $testinput);
}
// Save the expected outcome data.
$DB->delete_records('qtype_stack_qtest_expected', array('questionid' => $questionid, 'testcase' => $testcase));
foreach ($qtest->expectedresults as $prtname => $expectedresults) {
$expected = new stdClass();
$expected->questionid = $questionid;
$expected->testcase = $testcase;
$expected->prtname = $prtname;
if ($expectedresults->score === '' || $expectedresults->score === null) {
$expected->expectedscore = null;
} else {
$expected->expectedscore = (float) $expectedresults->score;
}
if ($expectedresults->penalty === '' || $expectedresults->penalty === null) {
$expected->expectedpenalty = null;
} else {
$expected->expectedpenalty = stack_utils::fix_approximate_thirds(
(float) $expectedresults->penalty);
}
$expected->expectedanswernote = $expectedresults->answernotes[0];
$DB->insert_record('qtype_stack_qtest_expected', $expected);
}
$transaction->allow_commit();
}
/**
* Deploy a variant of a question.
* @param int $questionid the question id.
* @param int $seed the seed to deploy.
*/
public function deploy_variant($questionid, $seed) {
global $DB;
$record = new stdClass();
$record->questionid = $questionid;
$record->seed = $seed;
$DB->insert_record('qtype_stack_deployed_seeds', $record);
$this->notify_question_edited($questionid);
}
/**
* Un-deploy a variant of a question.
* @param int $questionid the question id.
* @param int $seed the seed to un-deploy.
*/
public function undeploy_variant($questionid, $seed) {
global $DB;
$DB->delete_records('qtype_stack_deployed_seeds',
array('questionid' => $questionid, 'seed' => $seed));
$this->notify_question_edited($questionid);
}
/**
* Rename an input in the question data. It is the caller's responsibility
* to ensure that the $to name will not violate any unique constraints.
* @param int $questionid the question id.
* @param string $from the input to rename.
* @param string $to the new name to give it.
*/
public function rename_input($questionid, $from, $to) {
global $DB;
$transaction = $DB->start_delegated_transaction();
// Place-holders in the question text.
$questiontext = $DB->get_field('question', 'questiontext', array('id' => $questionid));
$questiontext = str_replace(array("[[input:{$from}]]", "[[validation:{$from}]]"),
array("[[input:{$to}]]", "[[validation:{$to}]]"), $questiontext);
$DB->set_field('question', 'questiontext', $questiontext, array('id' => $questionid));
// Input names in question test data.
$DB->set_field('qtype_stack_qtest_inputs', 'inputname', $to,
array('questionid' => $questionid, 'inputname' => $from));
// The input itself.
$DB->set_field('qtype_stack_inputs', 'name', $to,
array('questionid' => $questionid, 'name' => $from));
$regex = '~\b' . preg_quote($from, '~') . '\b~';
// Where the input name appears in expressions in PRTs.
$prts = $DB->get_records('qtype_stack_prts', array('questionid' => $questionid),
'id, feedbackvariables');
foreach ($prts as $prt) {
$prt->feedbackvariables = preg_replace($regex, $to, $prt->feedbackvariables, -1, $changes);
if ($changes) {
$DB->update_record('qtype_stack_prts', $prt);
}
}
// Where the input name appears in expressions in PRT node.
$nodes = $DB->get_records('qtype_stack_prt_nodes', array('questionid' => $questionid),
'id, sans, tans, testoptions, truefeedback, falsefeedback');
foreach ($nodes as $node) {
$changes = false;
$node->sans = preg_replace($regex, $to, $node->sans, -1, $count);
$changes = $changes || $count;
$node->tans = preg_replace($regex, $to, $node->tans, -1, $count);
$changes = $changes || $count;
$node->testoptions = preg_replace($regex, $to, $node->testoptions, -1, $count);
$changes = $changes || $count;
$node->truefeedback = preg_replace($regex, $to, $node->truefeedback, -1, $count);
$changes = $changes || $count;
$node->falsefeedback = preg_replace($regex, $to, $node->falsefeedback, -1, $count);
$changes = $changes || $count;
if ($changes) {
$DB->update_record('qtype_stack_prt_nodes', $node);
}
}
$transaction->allow_commit();
$this->notify_question_edited($questionid);
}
/**
* Rename a PRT in the question data. It is the caller's responsibility
* to ensure that the $to name will not violate any unique constraints.
* @param int $questionid the question id.
* @param string $from the PRT to rename.
* @param string $to the new name to give it.
*/
public function rename_prt($questionid, $from, $to) {
global $DB;
$transaction = $DB->start_delegated_transaction();
// Place-holders in the question text.
$questiontext = $DB->get_field('question', 'questiontext', array('id' => $questionid));
$questiontext = str_replace("[[feedback:{$from}]]", "[[feedback:{$to}]]", $questiontext);
$DB->set_field('question', 'questiontext', $questiontext, array('id' => $questionid));
// Place-holders in the specific feedback.
$specificfeedback = $DB->get_field('qtype_stack_options', 'specificfeedback',
array('questionid' => $questionid));
$specificfeedback = str_replace("[[feedback:{$from}]]", "[[feedback:{$to}]]", $specificfeedback);
$DB->set_field('qtype_stack_options', 'specificfeedback', $specificfeedback,
array('questionid' => $questionid));
// PRT names in question test data.
$DB->set_field('qtype_stack_qtest_expected', 'prtname', $to,
array('questionid' => $questionid, 'prtname' => $from));
// The PRT name in its nodes.
$DB->set_field('qtype_stack_prt_nodes', 'prtname', $to,
array('questionid' => $questionid, 'prtname' => $from));
// The PRT itself.
$DB->set_field('qtype_stack_prts', 'name', $to,
array('questionid' => $questionid, 'name' => $from));
$transaction->allow_commit();
$this->notify_question_edited($questionid);
}
/**
* Rename a PRT node in the question data. It is the caller's responsibility
* to ensure that the $to name will not violate any unique constraints.
* @param int $questionid the question id.
* @param string $prtname the PRT that the node belongs to.
* @param string $from the input to rename.
* @param string $to the new name to give it.
*/
public function rename_prt_node($questionid, $prtname, $from, $to) {
global $DB;
$transaction = $DB->start_delegated_transaction();
// The PRT node itself.
$DB->set_field('qtype_stack_prt_nodes', 'nodename', $to,
array('questionid' => $questionid, 'prtname' => $prtname, 'nodename' => $from));
// True next node links.
$DB->set_field('qtype_stack_prt_nodes', 'truenextnode', $to,
array('questionid' => $questionid, 'prtname' => $prtname, 'truenextnode' => $from));
// False next node links.
$DB->set_field('qtype_stack_prt_nodes', 'falsenextnode', $to,
array('questionid' => $questionid, 'prtname' => $prtname, 'falsenextnode' => $from));
// PRT first node link.
$DB->set_field('qtype_stack_prts', 'firstnodename', $to,
array('questionid' => $questionid, 'name' => $prtname, 'firstnodename' => $from));
$transaction->allow_commit();
$this->notify_question_edited($questionid);
}
/**
* From Moodle 2.4 onwards, we need to clear the entry from the question
* cache if a question definition changes. This method deals with doing
* that without causing errors on earlier versions of Moodle.
* @param int $questionid the question id to clear from the cache.
*/
protected function notify_question_edited($questionid) {
if (method_exists('question_bank', 'notify_question_edited')) {
call_user_func(array('question_bank', 'notify_question_edited'), $questionid);
}
}
/**
* Load all the question tests for a question.
* @param int $questionid the id of the question to load the tests for.
* @return array testcase number => stack_question_test
*/
public function load_question_tests($questionid) {
global $DB;
$testinputdata = $DB->get_records('qtype_stack_qtest_inputs',
array('questionid' => $questionid), 'testcase, inputname');
$testinputs = array();
foreach ($testinputdata as $data) {
$testinputs[$data->testcase][$data->inputname] = $data->value;
}
$testcasenumbers = $DB->get_records_menu('qtype_stack_qtests',
array('questionid' => $questionid), 'testcase', 'testcase, 1');
$testcases = array();
foreach ($testcasenumbers as $number => $notused) {
if (!array_key_exists($number, $testinputs)) {
$testinputs[$number] = array();
}
$testcase = new stack_question_test($testinputs[$number], $number);
$testcases[$number] = $testcase;
}
$expecteddata = $DB->get_records('qtype_stack_qtest_expected',
array('questionid' => $questionid), 'testcase, prtname');
foreach ($expecteddata as $data) {
$testcases[$data->testcase]->add_expected_result($data->prtname,
new stack_potentialresponse_tree_state(1, true,
$data->expectedscore, $data->expectedpenalty,
'', array($data->expectedanswernote)));
}
return $testcases;
}
/**
* Load one particular question tests for a question.
* @param int $questionid the id of the question to load the tests for.
* @param int $testcase the testcase nubmer to load.
* @return stack_question_test the test-case
*/
public function load_question_test($questionid, $testcase) {
global $DB;
// Verify that this testcase exists.
$DB->get_record('qtype_stack_qtests',
array('questionid' => $questionid, 'testcase' => $testcase), '*', MUST_EXIST);
// Load the inputs.
$inputs = $DB->get_records_menu('qtype_stack_qtest_inputs',
array('questionid' => $questionid, 'testcase' => $testcase),
'inputname', 'inputname, value');
$qtest = new stack_question_test($inputs, $testcase);
// Load the expectations.
$expectations = $DB->get_records('qtype_stack_qtest_expected',
array('questionid' => $questionid, 'testcase' => $testcase), 'prtname',
'prtname, expectedscore, expectedpenalty, expectedanswernote');
foreach ($expectations as $prtname => $expected) {
$qtest->add_expected_result($prtname, new stack_potentialresponse_tree_state(
1, true, $expected->expectedscore, $expected->expectedpenalty,
'', array($expected->expectedanswernote)));
}
return $qtest;
}
/**
* Delete all the question tests for a question.
* @param int $questionid the id of the question to load the tests for.
*/
protected function delete_question_tests($questionid) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$DB->delete_records('qtype_stack_qtest_expected', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_qtest_inputs', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_qtests', array('questionid' => $questionid));
$DB->delete_records('qtype_stack_qtest_results', array('questionid' => $questionid));
$transaction->allow_commit();
}
/**
* Delete one particular question test for a question.
* @param int $questionid the id of the question to load the tests for.
* @param int $testcase the testcase nubmer to load.
*/
public function delete_question_test($questionid, $testcase) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$DB->delete_records('qtype_stack_qtest_expected',
array('questionid' => $questionid, 'testcase' => $testcase));
$DB->delete_records('qtype_stack_qtest_inputs',
array('questionid' => $questionid, 'testcase' => $testcase));
$DB->delete_records('qtype_stack_qtests',
array('questionid' => $questionid, 'testcase' => $testcase));
$DB->delete_records('qtype_stack_qtest_results',
array('questionid' => $questionid, 'testcase' => $testcase));
$transaction->allow_commit();
}
public function get_possible_responses($questiondata) {
$parts = array();
$q = $this->make_question($questiondata);
foreach ($q->prts as $index => $prt) {
foreach ($prt->get_nodes_summary() as $nodeid => $choices) {
$parts[$index . '-' . $nodeid] = array(
$choices->falsenote => new question_possible_response(
$choices->falsenote, $choices->falsescore * $prt->get_value()),
$choices->truenote => new question_possible_response(
$choices->truenote, $choices->truescore * $prt->get_value()),
null => question_possible_response::no_response(),
);
}
}
return $parts;
}
/**
* Helper method used by {@link export_to_xml()}.
* @param qformat_xml $format the importer/exporter object.
* @param string $tag the XML tag to use.
* @param string $text the text to output.
* @param int $textformat the text's format.
* @param int $itemid the itemid for any files.
* @param int $contextid the context id that the text belongs to.
* @param string $indent the amount of indent to add at the start of the line.
* @return string XML fragment.
*/
protected function export_xml_text(qformat_xml $format, $tag, $text, $textformat,
$contextid, $filearea, $itemid, $indent = ' ') {
$fs = get_file_storage();
$files = $fs->get_area_files($contextid, 'qtype_stack', $filearea, $itemid);
$output = '';
$output .= $indent . "<{$tag} {$format->format($textformat)}>\n";
$output .= $indent . ' ' . $format->writetext($text);
$output .= $format->write_files($files);
$output .= $indent . "</{$tag}>\n";
return $output;
}
public function export_to_xml($questiondata, qformat_xml $format, $notused = null) {
$contextid = $questiondata->contextid;
if (!isset($questiondata->testcases)) {
// The method get_question_options does not load the testcases, because
// they are not normally needed, so we have to load them manually here.
// However, we only do it conditionally, so that the unit tests can
// just pass the data in.
$questiondata->testcases = $this->load_question_tests($questiondata->id);
}
$output = '';
$options = $questiondata->options;
$output .= " <stackversion>\n";
$output .= " " . $format->writetext($options->stackversion, 0);
$output .= " </stackversion>\n";
$output .= " <questionvariables>\n";
$output .= " " . $format->writetext($options->questionvariables, 0);
$output .= " </questionvariables>\n";
$output .= $this->export_xml_text($format, 'specificfeedback', $options->specificfeedback,
$options->specificfeedbackformat, $contextid, 'specificfeedback', $questiondata->id);