forked from gbateson/moodle-qtype_ordering
-
Notifications
You must be signed in to change notification settings - Fork 1
/
question.php
1013 lines (904 loc) · 40.1 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 Moodle - http://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 <http://www.gnu.org/licenses/>.
/**
* Ordering question definition classes.
*
* @package qtype_ordering
*
* @copyright 2013 Gordon Bateson (gordon.bateson@gmail.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Prevent direct access to this script.
/**
* Represents an ordering question.
*
* @copyright 2013 Gordon Bateson (gordon.bateson@gmail.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_ordering_question extends question_graded_automatically {
/** Select all answers */
const SELECT_ALL = 0;
/** Select random set of answers */
const SELECT_RANDOM = 1;
/** Select contiguous subset of answers */
const SELECT_CONTIGUOUS = 2;
/** Show answers in vertical list */
const LAYOUT_VERTICAL = 0;
/** Show answers in one horizontal line */
const LAYOUT_HORIZONTAL = 1;
/** Default value for numberingstyle */
const NUMBERING_STYLE_DEFAULT = 'none';
/** @var int Zero grade on any error */
const GRADING_ALL_OR_NOTHING = -1;
/** @var int Counts items, placed into right absolute place */
const GRADING_ABSOLUTE_POSITION = 0;
/** @var int Every sequential pair in right order is graded (last pair is excluded) */
const GRADING_RELATIVE_NEXT_EXCLUDE_LAST = 1;
/** @var int Every sequential pair in right order is graded (last pair is included) */
const GRADING_RELATIVE_NEXT_INCLUDE_LAST = 2;
/** @var int Single answers that are placed before and after each answer is graded if in right order*/
const GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT = 3;
/** @var int All answers that are placed before and after each answer is graded if in right order*/
const GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT = 4;
/** @var int Only longest ordered subset is graded */
const GRADING_LONGEST_ORDERED_SUBSET = 5;
/** @var int Only longest ordered and contiguous subset is graded */
const GRADING_LONGEST_CONTIGUOUS_SUBSET = 6;
/** @var int Items are graded relative to their position in the correct answer */
const GRADING_RELATIVE_TO_CORRECT = 7;
/** @var int {@see LAYOUT_VERTICAL} or {@see LAYOUT_HORIZONTAL}. */
public $layouttype;
/** @var int {@see SELECT_ALL}, {@see SELECT_RANDOM} or {@see SELECT_CONTIGUOUS}. */
public $selecttype;
/** @var int if {@see $selecttype} is not SELECT_ALL, then the number to select. */
public $selectcount;
/** @var int Which grading strategy to use. One of the GRADING_... constants. */
public $gradingtype;
/** @var bool Should details of the grading calculation be shown to students. */
public $showgrading;
/** @var string How to number the items. A key from the array returned by {@see get_numbering_styles()}. */
public $numberingstyle;
// Fields from "qtype_ordering_options" table.
/** @var string */
public $correctfeedback;
/** @var int */
public $correctfeedbackformat;
/** @var string */
public $incorrectfeedback;
/** @var int */
public $incorrectfeedbackformat;
/** @var string */
public $partiallycorrectfeedback;
/** @var int */
public $partiallycorrectfeedbackformat;
/** @var array Records from "question_answers" table */
public $answers;
/** @var stdClass Records from "qtype_ordering_options" table */
public $options;
/** @var array of answerids in correct order */
public $correctresponse;
/** @var array contatining current order of answerids */
public $currentresponse;
/**
* Start a new attempt at this question, storing any information that will
* be needed later in the step.
*
* This is where the question can do any initialisation required on a
* per-attempt basis. For example, this is where the multiple choice
* question type randomly shuffles the choices (if that option is set).
*
* Any information about how the question has been set up for this attempt
* should be stored in the $step, by calling $step->set_qt_var(...).
*
* @param question_attempt_step $step The first step of the {@link question_attempt}
* being started. Can be used to store state.
* @param int $variant which variant of this question to start. Will be between
* 1 and {@link get_num_variants()} inclusive.
*/
public function start_attempt(question_attempt_step $step, $variant) {
$countanswers = count($this->answers);
// Sanitize "selecttype".
$selecttype = $this->options->selecttype;
$selecttype = max(0, $selecttype);
$selecttype = min(2, $selecttype);
// Sanitize "selectcount".
$selectcount = $this->options->selectcount;
$selectcount = max(3, $selectcount);
$selectcount = min($countanswers, $selectcount);
// Ensure consistency between "selecttype" and "selectcount".
switch (true) {
case ($selecttype == self::SELECT_ALL):
$selectcount = $countanswers;
break;
case ($selectcount == $countanswers):
$selecttype = self::SELECT_ALL;
break;
}
// Extract answer ids.
switch ($selecttype) {
case self::SELECT_ALL:
$answerids = array_keys($this->answers);
break;
case self::SELECT_RANDOM:
$answerids = array_rand($this->answers, $selectcount);
break;
case self::SELECT_CONTIGUOUS:
$answerids = array_keys($this->answers);
$offset = mt_rand(0, $countanswers - $selectcount);
$answerids = array_slice($answerids, $offset, $selectcount);
break;
}
$this->correctresponse = $answerids;
$step->set_qt_var('_correctresponse', implode(',', $this->correctresponse));
shuffle($answerids);
$this->currentresponse = $answerids;
$step->set_qt_var('_currentresponse', implode(',', $this->currentresponse));
}
/**
* When an in-progress {@link question_attempt} is re-loaded from the
* database, this method is called so that the question can re-initialise
* its internal state as needed by this attempt.
*
* For example, the multiple choice question type needs to set the order
* of the choices to the order that was set up when start_attempt was called
* originally. All the information required to do this should be in the
* $step object, which is the first step of the question_attempt being loaded.
*
* @param question_attempt_step $step The first step of the {@link question_attempt}
* being loaded.
*/
public function apply_attempt_state(question_attempt_step $step) {
$this->currentresponse = array_filter(explode(',', $step->get_qt_var('_currentresponse')));
$this->correctresponse = array_filter(explode(',', $step->get_qt_var('_correctresponse')));
}
public function validate_can_regrade_with_other_version(question_definition $otherversion): ?string {
$basemessage = parent::validate_can_regrade_with_other_version($otherversion);
if ($basemessage) {
return $basemessage;
}
if (count($this->answers) != count($otherversion->answers)) {
return get_string('regradeissuenumitemschanged', 'qtype_ordering');
}
return null;
}
public function update_attempt_state_data_for_new_version(
question_attempt_step $oldstep, question_definition $otherversion) {
parent::update_attempt_state_data_for_new_version($oldstep, $otherversion);
$mapping = array_combine(array_keys($otherversion->answers), array_keys($this->answers));
$oldorder = explode(',', $oldstep->get_qt_var('_currentresponse'));
$neworder = [];
foreach ($oldorder as $oldid) {
$neworder[] = $mapping[$oldid] ?? $oldid;
}
$oldcorrect = explode(',', $oldstep->get_qt_var('_correctresponse'));
$newcorrect = [];
foreach ($oldcorrect as $oldid) {
$newcorrect[] = $mapping[$oldid] ?? $oldid;
}
return [
'_currentresponse' => implode(',', $neworder),
'_correctresponse' => implode(',', $newcorrect),
];
}
/**
* What data may be included in the form submission when a student submits
* this question in its current state?
*
* This information is used in calls to optional_param. The parameter name
* has {@link question_attempt::get_field_prefix()} automatically prepended.
*
* @return array|string variable name => PARAM_... constant, or, as a special case
* that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
* meaning take all the raw submitted data belonging to this question.
*/
public function get_expected_data() {
$name = $this->get_response_fieldname();
return array($name => PARAM_TEXT);
}
/**
* What data would need to be submitted to get this question correct.
* If there is more than one correct answer, this method should just
* return one possibility. If it is not possible to compute a correct
* response, this method should return null.
*
* @return array|null parameter name => value.
*/
public function get_correct_response() {
$correctresponse = $this->correctresponse;
foreach ($correctresponse as $position => $answerid) {
$answer = $this->answers[$answerid];
$correctresponse[$position] = $answer->md5key;
}
$name = $this->get_response_fieldname();
return array($name => implode(',', $correctresponse));
}
/**
* Produce a plain text summary of a response.
*
* @param array $response a response, as might be passed to {@link grade_response()}.
* @return string a plain text summary of that response, that could be used in reports.
*/
public function summarise_response(array $response) {
$name = $this->get_response_fieldname();
if (array_key_exists($name, $response)) {
$items = explode(',', $response[$name]);
} else {
$items = array(); // Shouldn't happen !!
}
$answerids = array();
foreach ($this->answers as $answer) {
$answerids[$answer->md5key] = $answer->id;
}
foreach ($items as $i => $item) {
if (array_key_exists($item, $answerids)) {
$item = $this->answers[$answerids[$item]];
$item = $this->html_to_text($item->answer, $item->answerformat);
$item = shorten_text($item, 10, true); // Force truncate at 10 chars.
$items[$i] = $item;
} else {
$items[$i] = ''; // Shouldn't happen !!
}
}
return implode('; ', array_filter($items));
}
/**
* Categorise the student's response according to the categories defined by
* get_possible_responses.
*
* @param array $response a response, as might be passed to {@link grade_response()}.
* @return array subpartid => {@link question_classified_response} objects.
* returns an empty array if no analysis is possible.
*/
public function classify_response(array $response) {
$this->update_current_response($response);
$fraction = 1 / count($this->correctresponse);
$classifiedresponse = array();
foreach ($this->correctresponse as $position => $answerid) {
if (in_array($answerid, $this->currentresponse)) {
$currentposition = array_search($answerid, $this->currentresponse);
}
$answer = $this->answers[$answerid];
$subqid = question_utils::to_plain_text($answer->answer, $answer->answerformat);
// Truncate responses longer than 100 bytes because they cannot be stored in the database.
// CAUTION: This will mess up answers which are not unique within the first 100 chars !!
$maxbytes = 100;
if (strlen($subqid) > $maxbytes) {
// If the truncation point is in the middle of a multi-byte unicode char,
// we remove the incomplete part with a preg_match() that is unicode aware.
$subqid = substr($subqid, 0, $maxbytes);
if (preg_match('/^(.|\n)*/u', '', $subqid, $match)) {
$subqid = $match[0];
}
}
$classifiedresponse[$subqid] = new question_classified_response(
$currentposition + 1,
get_string('positionx', 'qtype_ordering', $currentposition + 1),
($currentposition == $position) * $fraction
);
}
return $classifiedresponse;
}
/**
* Used by many of the behaviours, to work out whether the student's
* response to the question is complete. That is, whether the question attempt
* should move to the COMPLETE or INCOMPLETE state.
*
* @param array $response responses, as returned by
* {@link question_attempt_step::get_qt_data()}.
* @return bool whether this response is a complete answer to this question.
*/
public function is_complete_response(array $response) {
return true;
}
/**
* Use by many of the behaviours to determine whether the student
* has provided enough of an answer for the question to be graded automatically,
* or whether it must be considered aborted.
*
* @param array $response responses, as returned by
* {@link question_attempt_step::get_qt_data()}.
* @return bool whether this response can be graded.
*/
public function is_gradable_response(array $response) {
return true;
}
/**
* In situations where is_gradable_response() returns false, this method
* should generate a description of what the problem is.
* @param array $response
* @return string the message
*/
public function get_validation_error(array $response) {
return '';
}
/**
* Use by many of the behaviours to determine whether the student's
* response has changed. This is normally used to determine that a new set
* of responses can safely be discarded.
*
* @param array $old the responses previously recorded for this question,
* as returned by {@link question_attempt_step::get_qt_data()}
* @param array $new the new responses, in the same format.
* @return bool whether the two sets of responses are the same - that is
* whether the new set of responses can safely be discarded.
*/
public function is_same_response(array $old, array $new) {
$name = $this->get_response_fieldname();
return (isset($old[$name]) && isset($new[$name]) && $old[$name] == $new[$name]);
}
/**
* Grade a response to the question, returning a fraction between
* get_min_fraction() and get_max_fraction(), and the corresponding {@link question_state}
* right, partial or wrong.
*
* @param array $response responses, as returned by
* {@link question_attempt_step::get_qt_data()}.
* @return array (float, integer) the fraction, and the state.
*/
public function grade_response(array $response) {
$this->update_current_response($response);
$countcorrect = 0;
$countanswers = 0;
$gradingtype = $this->options->gradingtype;
switch ($gradingtype) {
case self::GRADING_ALL_OR_NOTHING:
case self::GRADING_ABSOLUTE_POSITION:
$correctresponse = $this->correctresponse;
$currentresponse = $this->currentresponse;
foreach ($correctresponse as $position => $answerid) {
if (array_key_exists($position, $currentresponse)) {
if ($currentresponse[$position] == $answerid) {
$countcorrect++;
}
}
$countanswers++;
}
if ($gradingtype == self::GRADING_ALL_OR_NOTHING && $countcorrect < $countanswers) {
$countcorrect = 0;
}
break;
case self::GRADING_RELATIVE_NEXT_EXCLUDE_LAST:
case self::GRADING_RELATIVE_NEXT_INCLUDE_LAST:
$lastitem = ($gradingtype == self::GRADING_RELATIVE_NEXT_INCLUDE_LAST);
$currentresponse = $this->get_next_answerids($this->currentresponse, $lastitem);
$correctresponse = $this->get_next_answerids($this->correctresponse, $lastitem);
foreach ($correctresponse as $thisanswerid => $nextanswerid) {
if (array_key_exists($thisanswerid, $currentresponse)) {
if ($currentresponse[$thisanswerid] == $nextanswerid) {
$countcorrect++;
}
}
$countanswers++;
}
break;
case self::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT:
case self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT:
$all = ($gradingtype == self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT);
$currentresponse = $this->get_previous_and_next_answerids($this->currentresponse, $all);
$correctresponse = $this->get_previous_and_next_answerids($this->correctresponse, $all);
foreach ($correctresponse as $thisanswerid => $answerids) {
if (array_key_exists($thisanswerid, $currentresponse)) {
$prev = $currentresponse[$thisanswerid]->prev;
$prev = array_intersect($prev, $answerids->prev);
$countcorrect += count($prev);
$next = $currentresponse[$thisanswerid]->next;
$next = array_intersect($next, $answerids->next);
$countcorrect += count($next);
}
$countanswers += count($answerids->prev);
$countanswers += count($answerids->next);
}
break;
case self::GRADING_LONGEST_ORDERED_SUBSET:
case self::GRADING_LONGEST_CONTIGUOUS_SUBSET:
$contiguous = ($gradingtype == self::GRADING_LONGEST_CONTIGUOUS_SUBSET);
$subset = $this->get_ordered_subset($contiguous);
$countcorrect = count($subset);
$countanswers = count($this->currentresponse);
break;
case self::GRADING_RELATIVE_TO_CORRECT:
$correctresponse = $this->correctresponse;
$currentresponse = $this->currentresponse;
$count = (count($correctresponse) - 1);
foreach ($correctresponse as $position => $answerid) {
if (in_array($answerid, $currentresponse)) {
$currentposition = array_search($answerid, $currentresponse);
$currentscore = ($count - abs($position - $currentposition));
if ($currentscore > 0) {
$countcorrect += $currentscore;
}
}
$countanswers += $count;
}
break;
}
if ($countanswers == 0) {
$fraction = 0;
} else {
$fraction = ($countcorrect / $countanswers);
}
return array($fraction, question_state::graded_state_for_fraction($fraction));
}
/**
* Checks whether the user has permission to access a particular file.
*
* @param question_attempt $qa the question attempt being displayed.
* @param question_display_options $options the options that control display of the question.
* @param string $component the name of the component we are serving files for.
* @param string $filearea the name of the file area.
* @param array $args the remaining bits of the file path.
* @param bool $forcedownload whether the user must be forced to download the file.
* @return bool true if the user can access this file.
*/
public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
if ($component == 'question') {
if ($filearea == 'answer') {
$answerid = reset($args); // Value of "itemid" is answer id.
return array_key_exists($answerid, $this->answers);
}
if (in_array($filearea, $this->qtype->feedbackfields)) {
return $this->check_combined_feedback_file_access($qa, $options, $filearea, $args);
}
if ($filearea == 'hint') {
return $this->check_hint_file_access($qa, $options, $args);
}
}
return parent::check_file_access($qa, $options, $component, $filearea, $args, $forcedownload);
}
// Methods from "question_graded_automatically" class.
// See "question/type/questionbase.php".
/**
* Check a request for access to a file belonging to a combined feedback field.
*
* Fix a bug in Moodle 2.9 & 3.0, in which this method does not declare $args,
* so trying to use $args[0] always fails and images in feedback are not shown.
*
* @param question_attempt $qa the question attempt being displayed.
* @param question_display_options $options the options that control display of the question.
* @param string $filearea the name of the file area.
* @param array $args the remaining bits of the file path.
* @return bool whether access to the file should be allowed.
*/
protected function check_combined_feedback_file_access($qa, $options, $filearea, $args = null) {
$state = $qa->get_state();
if (! $state->is_finished()) {
$response = $qa->get_last_qt_data();
if (! $this->is_gradable_response($response)) {
return false;
}
list($fraction, $state) = $this->grade_response($response);
}
if ($state->get_feedback_class().'feedback' == $filearea) {
return ($this->id == reset($args));
} else {
return false;
}
}
// Custom methods.
/**
* Returns response mform field name
*
* @return string
*/
public function get_response_fieldname() {
return 'response_'.$this->id;
}
/**
* Convert response data from mform into array
*
* @param array $response Form data
* @return array
*/
public function update_current_response($response) {
$name = $this->get_response_fieldname();
if (array_key_exists($name, $response)) {
$ids = explode(',', $response[$name]);
foreach ($ids as $i => $id) {
foreach ($this->answers as $answer) {
if ($id == $answer->md5key) {
$ids[$i] = $answer->id;
break;
}
}
}
$this->currentresponse = $ids;
}
}
/**
* Returns layoutclass
*
* @return string
*/
public function get_ordering_layoutclass() {
switch ($this->options->layouttype) {
case self::LAYOUT_VERTICAL:
return 'vertical';
case self::LAYOUT_HORIZONTAL:
return 'horizontal';
default:
return ''; // Shouldn't happen !!
}
}
/**
* Returns array of next answers
*
* @param array $answerids array of answers id
* @param bool $lastitem Include last item?
* @return array of id of next answer
*/
public function get_next_answerids($answerids, $lastitem = false) {
$nextanswerids = array();
$imax = count($answerids);
$imax--;
if ($lastitem) {
$nextanswerid = 0;
} else {
$nextanswerid = $answerids[$imax];
$imax--;
}
for ($i = $imax; $i >= 0; $i--) {
$thisanswerid = $answerids[$i];
$nextanswerids[$thisanswerid] = $nextanswerid;
$nextanswerid = $thisanswerid;
}
return $nextanswerids;
}
/**
* Returns prev and next answers array
*
* @param array $answerids array of answers id
* @param bool $all include all answers
* @return array of array('prev' => previd, 'next' => nextid)
*/
public function get_previous_and_next_answerids($answerids, $all = false) {
$prevnextanswerids = array();
$next = $answerids;
$prev = array();
while ($answerid = array_shift($next)) {
if ($all) {
$prevnextanswerids[$answerid] = (object)array(
'prev' => $prev,
'next' => $next
);
} else {
$prevnextanswerids[$answerid] = (object)array(
'prev' => array(empty($prev) ? 0 : $prev[0]),
'next' => array(empty($next) ? 0 : $next[0])
);
}
array_unshift($prev, $answerid);
}
return $prevnextanswerids;
}
/**
* Search for best ordered subset
*
* @param bool $contiguous
* @return array
*/
public function get_ordered_subset($contiguous) {
$positions = $this->get_ordered_positions($this->correctresponse,
$this->currentresponse);
$subsets = $this->get_ordered_subsets($positions, $contiguous);
// The best subset (longest and leftmost).
$bestsubset = array();
// The length of the best subset
// initializing this to 1 means
// we ignore single item subsets.
$bestcount = 1;
foreach ($subsets as $subset) {
$count = count($subset);
if ($count > $bestcount) {
$bestcount = $count;
$bestsubset = $subset;
}
}
return $bestsubset;
}
/**
* Get array of right answer positions for current response
*
* @param array $correctresponse
* @param array $currentresponse
* @return array
*/
public function get_ordered_positions($correctresponse, $currentresponse) {
$positions = array();
foreach ($currentresponse as $answerid) {
$positions[] = array_search($answerid, $correctresponse);
}
return $positions;
}
/**
* Get all ordered subsets in the positions array
*
* @param array $positions maps an item's current position to its correct position
* @param boolean $contiguous TRUE if searching only for contiguous subsets; otherwise FALSE
*
* @return array of ordered subsets from within the $positions array
*/
public function get_ordered_subsets($positions, $contiguous) {
// Var $subsets is the collection of all subsets within $positions.
$subsets = array();
// Loop through the values at each position.
foreach ($positions as $p => $value) {
// Is $value a "new" value that cannot be added to any $subsets found so far?
$isnew = true;
// An array of new and saved subsets to be added to $subsets.
$new = array();
// Append the current value to any subsets to which it belongs
// i.e. any subset whose end value is less than the current value.
foreach ($subsets as $s => $subset) {
// Get value at end of $subset.
$end = $positions[end($subset)];
switch (true) {
case ($value == ($end + 1)):
// For a contiguous value, we simply append $p to the subset.
$isnew = false;
$subsets[$s][] = $p;
break;
case $contiguous:
// If the $contiguous flag is set, we ignore non-contiguous values.
break;
case ($value > $end):
// For a non-contiguous value, we save the subset so far,
// because a value between $end and $value may be found later,
// and then append $p to the subset.
$isnew = false;
$new[] = $subset;
$subsets[$s][] = $p;
break;
}
}
// If this is a "new" value, add it as a new subset.
if ($isnew) {
$new[] = array($p);
}
// Append any "new" subsets that were found during this iteration.
if (count($new)) {
$subsets = array_merge($subsets, $new);
}
}
return $subsets;
}
/**
* Helper function for get_select_types, get_layout_types, get_grading_types
*
* @param array $types
* @param int $type
* @return array|string array if $type is not specified and single string if $type is specified
*/
public static function get_types($types, $type) {
if ($type === null) {
return $types; // Return all $types.
}
if (array_key_exists($type, $types)) {
return $types[$type]; // One $type.
}
return $type; // Shouldn't happen !!
}
/**
* Returns available values and descriptions for field "selecttype"
*
* @param int $type
* @return array|string array if $type is not specified and single string if $type is specified
*/
public static function get_select_types($type=null) {
$plugin = 'qtype_ordering';
$types = array(
self::SELECT_ALL => get_string('selectall', $plugin),
self::SELECT_RANDOM => get_string('selectrandom', $plugin),
self::SELECT_CONTIGUOUS => get_string('selectcontiguous', $plugin)
);
return self::get_types($types, $type);
}
/**
* Returns available values and descriptions for field "layouttype"
*
* @param int $type
* @return array|string array if $type is not specified and single string if $type is specified
*/
public static function get_layout_types($type=null) {
$plugin = 'qtype_ordering';
$types = array(
self::LAYOUT_VERTICAL => get_string('vertical', $plugin),
self::LAYOUT_HORIZONTAL => get_string('horizontal', $plugin)
);
return self::get_types($types, $type);
}
/**
* Returns available values and descriptions for field "gradingtype"
*
* @param int $type
* @return array|string array if $type is not specified and single string if $type is specified
*/
public static function get_grading_types($type=null) {
$plugin = 'qtype_ordering';
$types = array(
self::GRADING_ALL_OR_NOTHING => get_string('allornothing', $plugin),
self::GRADING_ABSOLUTE_POSITION => get_string('absoluteposition', $plugin),
self::GRADING_RELATIVE_TO_CORRECT => get_string('relativetocorrect', $plugin),
self::GRADING_RELATIVE_NEXT_EXCLUDE_LAST => get_string('relativenextexcludelast', $plugin),
self::GRADING_RELATIVE_NEXT_INCLUDE_LAST => get_string('relativenextincludelast', $plugin),
self::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT => get_string('relativeonepreviousandnext', $plugin),
self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT => get_string('relativeallpreviousandnext', $plugin),
self::GRADING_LONGEST_ORDERED_SUBSET => get_string('longestorderedsubset', $plugin),
self::GRADING_LONGEST_CONTIGUOUS_SUBSET => get_string('longestcontiguoussubset', $plugin)
);
return self::get_types($types, $type);
}
/**
* @param string $style
* @return array of the numbering styles supported. For each one, there
* should be a lang string numberingstylexxx in the qtype_ordering
* language file, and a case in the switch statement in number_in_style,
* and it should be listed in the definition of this column in install.xml.
*/
public static function get_numbering_styles($style=null) {
$plugin = 'qtype_ordering';
$styles = array('none' => get_string('numberingstylenone', $plugin),
'abc' => get_string('numberingstyleabc', $plugin),
'ABCD' => get_string('numberingstyleABCD', $plugin),
'123' => get_string('numberingstyle123', $plugin),
'iii' => get_string('numberingstyleiii', $plugin),
'IIII' => get_string('numberingstyleIIII', $plugin));
return self::get_types($styles, $style);
}
/**
* Return the number of subparts of this response that are correct|partial|incorrect.
*
* @param array $response A response.
* @return array Array of three elements: the number of correct subparts,
* the number of partial correct subparts and the number of incorrect subparts.
*/
public function get_num_parts_right(array $response) {
$this->update_current_response($response);
$gradingtype = $this->options->gradingtype;
$numright = 0;
$numpartial = 0;
$numincorrect = 0;
list($correctresponse, $currentresponse) = $this->get_response_depend_on_grading_type($gradingtype);
foreach ($this->currentresponse as $position => $answerid) {
$fraction = $this->get_fraction_of_item($position, $answerid, $correctresponse, $currentresponse);
if (is_null($fraction)) {
continue;
}
if ($fraction > 0.999999) {
$numright++;
} else if ($fraction < 0.000001) {
$numincorrect++;
} else {
$numpartial++;
}
}
return [$numright, $numpartial, $numincorrect];
}
/**
* Returns the grade for one item, base on the fraction scale.
*
* @param int $position The position of the current response.
* @param int $answerid The answerid of the current response.
* @param array $correctresponse The correct response list base on grading type.
* @param array $currentresponse The current response list base on grading type.
* @return float|null Float if the grade, base on the fraction scale and null if the item is not in the correct response.
*/
protected function get_fraction_of_item(int $position, int $answerid, array $correctresponse, array $currentresponse) {
$gradingtype = $this->options->gradingtype;
$score = 0;
$maxscore = null;
switch ($gradingtype) {
case self::GRADING_ALL_OR_NOTHING:
case self::GRADING_ABSOLUTE_POSITION:
if (isset($correctresponse[$position])) {
if ($correctresponse[$position] == $answerid) {
$score = 1;
}
$maxscore = 1;
}
break;
case self::GRADING_RELATIVE_NEXT_EXCLUDE_LAST:
case self::GRADING_RELATIVE_NEXT_INCLUDE_LAST:
if (isset($correctresponse[$answerid])) {
if (isset($currentresponse[$answerid]) && $currentresponse[$answerid] == $correctresponse[$answerid]) {
$score = 1;
}
$maxscore = 1;
}
break;
case self::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT:
case self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT:
if (isset($correctresponse[$answerid])) {
$maxscore = 0;
$prev = $correctresponse[$answerid]->prev;
$maxscore += count($prev);
$prev = array_intersect($prev, $currentresponse[$answerid]->prev);
$score += count($prev);
$next = $correctresponse[$answerid]->next;
$maxscore += count($next);
$next = array_intersect($next, $currentresponse[$answerid]->next);
$score += count($next);
}
break;
case self::GRADING_LONGEST_ORDERED_SUBSET:
case self::GRADING_LONGEST_CONTIGUOUS_SUBSET:
if (isset($correctresponse[$position])) {
if (isset($currentresponse[$position])) {
$score = $currentresponse[$position];
}
$maxscore = 1;
}
break;
case self::GRADING_RELATIVE_TO_CORRECT:
if (isset($correctresponse[$position])) {
$maxscore = (count($correctresponse) - 1);
$answerid = $currentresponse[$position];
$correctposition = array_search($answerid, $correctresponse);
$score = ($maxscore - abs($correctposition - $position));
if ($score < 0) {
$score = 0;
}
}
break;
}
$fraction = $maxscore ? $score / $maxscore : $maxscore;
return $fraction;
}
/**
* Get correcresponse and currentinfo depending on grading type.
*
* @param string $gradingtype The kind of grading.
* @return array Correctresponse and currentresponsescore in one array.
*/
protected function get_response_depend_on_grading_type(string $gradingtype): array {
$correctresponse = [];
$currentresponse = [];
switch ($gradingtype) {
case self::GRADING_ALL_OR_NOTHING:
case self::GRADING_ABSOLUTE_POSITION:
case self::GRADING_RELATIVE_TO_CORRECT:
$correctresponse = $this->correctresponse;
$currentresponse = $this->currentresponse;
break;
case self::GRADING_RELATIVE_NEXT_EXCLUDE_LAST:
case self::GRADING_RELATIVE_NEXT_INCLUDE_LAST:
$lastitem = ($gradingtype == self::GRADING_RELATIVE_NEXT_INCLUDE_LAST);
$correctresponse = $this->get_next_answerids($this->correctresponse, $lastitem);
$currentresponse = $this->get_next_answerids($this->currentresponse, $lastitem);
break;
case self::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT:
case self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT:
$all = ($gradingtype == self::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT);
$correctresponse = $this->get_previous_and_next_answerids($this->correctresponse, $all);
$currentresponse = $this->get_previous_and_next_answerids($this->currentresponse, $all);
break;
case self::GRADING_LONGEST_ORDERED_SUBSET:
case self::GRADING_LONGEST_CONTIGUOUS_SUBSET:
$correctresponse = $this->correctresponse;
$currentresponse = $this->currentresponse;
$contiguous = ($gradingtype == self::GRADING_LONGEST_CONTIGUOUS_SUBSET);
$subset = $this->get_ordered_subset($contiguous);