forked from gbateson/moodle-qtype_ordering
-
Notifications
You must be signed in to change notification settings - Fork 1
/
questiontype.php
1019 lines (886 loc) · 39.1 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 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/>.
/**
* The questiontype class for the multiple choice question type.
*
* @package qtype_ordering
* @copyright 2013 Gordon Bateson (gordon.bateson@gmail.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use qtype_ordering\question_hint_ordering;
/**
* The ordering question type.
*
* @copyright 2013 Gordon Bateson (gordon.bateson@gmail.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_ordering extends question_type {
/** @var int Number of hints default. */
const DEFAULT_NUM_HINTS = 2;
/** @var array Combined feedback fields */
public $feedbackfields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
/**
* @return bool whether the question_answers.answer field needs to have
* restore_decode_content_links_worker called on it.
*/
public function has_html_answers() {
return true;
}
/**
* If your question type has a table that extends the question table, and
* you want the base class to automatically save, backup and restore the extra fields,
* override this method to return an array wherer the first element is the table name,
* and the subsequent entries are the column names (apart from id and questionid).
*
* @return mixed array as above, or null to tell the base class to do nothing.
*/
public function extra_question_fields() {
return array('qtype_ordering_options',
'layouttype', 'selecttype', 'selectcount',
'gradingtype', 'showgrading', 'numberingstyle');
}
/**
* Initialise the common question_definition fields.
* @param question_definition $question the question_definition we are creating.
* @param object $questiondata the question data loaded from the database.
*/
protected function initialise_question_instance(question_definition $question, $questiondata) {
global $CFG;
parent::initialise_question_instance($question, $questiondata);
$question->answers = $questiondata->options->answers;
foreach ($question->answers as $answerid => $answer) {
$question->answers[$answerid]->md5key =
'ordering_item_' . md5(($CFG->passwordsaltmain ?? '') . $answer->answer);
}
$question->options = clone($questiondata->options);
unset($question->options->answers);
$this->initialise_combined_feedback($question, $questiondata, true);
}
/**
* Saves question-type specific options
*
* This is called by {@link save_question()} to save the question-type specific data
* @return object $result->error or $result->notice
* @param object $question This holds the information from the editing form,
* it is not a standard question object.
*/
public function save_question_options($question) {
global $DB;
$result = new stdClass();
$context = $question->context;
// Remove empty answers.
$question->answer = array_filter($question->answer, array($this, 'is_not_blank'));
$question->answer = array_values($question->answer); // Make keys sequential.
// Count how many answers we have.
$countanswers = count($question->answer);
// Search/replace strings to reduce simple <p>...</p> to plain text.
$psearch = '/^\s*<p>\s*(.*?)(\s*<br\s*\/?>)*\s*<\/p>\s*$/';
$preplace = '$1';
// Search/replace strings to standardize vertical align of <img> tags.
$imgsearch = '/(<img[^>]*)\bvertical-align:\s*[a-zA-Z0-9_-]+([^>]*>)/';
$imgreplace = '$1'.'vertical-align:text-top'.'$2';
// Check at least two answers exist.
if ($countanswers < 2) {
$result->notice = get_string('notenoughanswers', 'qtype_ordering', '2');
return $result;
}
$question->feedback = range(1, $countanswers);
if ($answerids = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC', 'id,question')) {
$answerids = array_keys($answerids);
} else {
$answerids = array();
}
// Insert all the new answers.
foreach ($question->answer as $i => $answer) {
$answertext = '';
$answerformat = 0;
$answeritemid = null;
// Extract $answer fields.
if (is_string($answer)) {
// Import from file.
$answertext = $answer;
} else if (is_array($answer)) {
// Input from browser.
if (isset($answer['text'])) {
$answertext = $answer['text'];
}
if (isset($answer['format'])) {
$answerformat = $answer['format'];
}
if (isset($answer['itemid'])) {
$answeritemid = $answer['itemid'];
}
}
// Reduce simple <p>...</p> to plain text.
if (substr_count($answertext, '<p>') == 1) {
$answertext = preg_replace($psearch, $preplace, $answertext);
}
$answertext = trim($answertext);
// Skip empty answers.
if ($answertext == '') {
continue;
}
// Standardize vertical align of img tags.
$answertext = preg_replace($imgsearch, $imgreplace, $answertext);
// Prepare the $answer object.
$answer = (object)array(
'question' => $question->id,
'fraction' => ($i + 1), // Start at 1.
'answer' => $answertext,
'answerformat' => $answerformat,
'feedback' => '',
'feedbackformat' => FORMAT_MOODLE,
);
// Add/insert $answer into the database.
if ($answer->id = array_shift($answerids)) {
if (! $DB->update_record('question_answers', $answer)) {
$result->error = get_string('cannotupdaterecord', 'error', 'question_answers (id='.$answer->id.')');
return $result;
}
} else {
unset($answer->id);
if (! $answer->id = $DB->insert_record('question_answers', $answer)) {
$result->error = get_string('cannotinsertrecord', 'error', 'question_answers');
return $result;
}
}
// Copy files across from draft files area.
// Note: we must do this AFTER inserting the answer record
// because the answer id is used as the file's "itemid".
if ($answeritemid) {
$answertext = file_save_draft_area_files($answeritemid, $context->id, 'question', 'answer', $answer->id,
$this->fileoptions, $answertext);
$DB->set_field('question_answers', 'answer', $answertext, array('id' => $answer->id));
}
}
// Create $options for this ordering question.
$options = (object)array(
'questionid' => $question->id,
'layouttype' => $question->layouttype,
'selecttype' => $question->selecttype,
'selectcount' => $question->selectcount,
'gradingtype' => $question->gradingtype,
'showgrading' => $question->showgrading,
'numberingstyle' => $question->numberingstyle
);
$options = $this->save_combined_feedback_helper($options, $question, $context, true);
$this->save_hints($question, true);
// Add/update $options for this ordering question.
if ($options->id = $DB->get_field('qtype_ordering_options', 'id', array('questionid' => $question->id))) {
if (! $DB->update_record('qtype_ordering_options', $options)) {
$result->error = get_string('cannotupdaterecord', 'error', 'qtype_ordering_options (id='.$options->id.')');
return $result;
}
} else {
unset($options->id);
if (! $options->id = $DB->insert_record('qtype_ordering_options', $options)) {
$result->error = get_string('cannotinsertrecord', 'error', 'qtype_ordering_options');
return $result;
}
}
// Delete old answer records, if any.
if (count($answerids)) {
$fs = get_file_storage();
foreach ($answerids as $answerid) {
$fs->delete_area_files($context->id, 'question', 'answer', $answerid);
$DB->delete_records('question_answers', array('id' => $answerid));
}
}
return true;
}
/**
* Count number of hints on the form.
*
* @param object $formdata The data from the form.
* @param bool $withparts Whether to take into account clearwrong and shownumcorrect options.
* @return int Count of hints on the form.
*/
protected function count_hints_on_form($formdata, $withparts) {
$numhints = parent::count_hints_on_form($formdata, $withparts);
if (!empty($formdata->hintoptions)) {
$numhints = max($numhints, max(array_keys($formdata->hintoptions)) + 1);
}
return $numhints;
}
/**
* Determine if the hint with specified number is not empty and should be saved.
* Overload if you use custom hint controls.
*
* @param object $formdata the data from the form.
* @param int $number number of hint under question.
* @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
* @return bool is this particular hint data empty.
*/
protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
return parent::is_hint_empty_in_form_data($formdata, $number, $withparts) &&
empty($formdata->hintoptions[$number]);
}
/**
* Save additional question type data into the hint optional field.
* Overload if you use custom hint information.
* @param object $formdata the data from the form.
* @param int $number number of hint to get options from.
* @param bool $withparts whether question have parts.
* @return string value to save into the options field of question_hints table.
*/
protected function save_hint_options($formdata, $number, $withparts) {
return !empty($formdata->hintoptions[$number]);
}
/**
* Create a question_hint, or an appropriate subclass for this question, from a row loaded from the database.
*
* @param object $hint The DB row from the question hints table.
* @return question_hint_ordering Hints of question from record.
*/
protected function make_hint($hint) {
return question_hint_ordering::load_from_record($hint);
}
/**
* This method should return all the possible types of response that are
* recognised for this question.
*
* The question is modelled as comprising one or more subparts. For each
* subpart, there are one or more classes that that students response
* might fall into, each of those classes earning a certain score.
*
* For example, in a shortanswer question, there is only one subpart, the
* text entry field. The response the student gave will be classified according
* to which of the possible $question->options->answers it matches.
*
* For the matching question type, there will be one subpart for each
* question stem, and for each stem, each of the possible choices is a class
* of student's response.
*
* A response is an object with two fields, ->responseclass is a string
* presentation of that response, and ->fraction, the credit for a response
* in that class.
*
* Array keys have no specific meaning, but must be unique, and must be
* the same if this function is called repeatedly.
*
* @param object $questiondata the question definition data.
* @return array keys are subquestionid, values are arrays of possible
* responses to that subquestion.
*/
public function get_possible_responses($questiondata) {
$responseclasses = array();
$itemcount = count($questiondata->options->answers);
$position = 0;
foreach ($questiondata->options->answers as $answerid => $answer) {
$position += 1;
$classes = array();
for ($i = 1; $i <= $itemcount; $i++) {
$classes[$i] = new question_possible_response(
get_string('positionx', 'qtype_ordering', $i),
($i === $position) / $itemcount);
}
$subqid = question_utils::to_plain_text($answer->answer, $answer->answerformat);
$subqid = core_text::substr($subqid, 0, 100); // Ensure not more than 100 chars.
$responseclasses[$subqid] = $classes;
}
return $responseclasses;
}
/**
* Callback function for filtering answers with array_filter
*
* @param mixed $value
* @return bool If true, this item should be saved.
*/
public function is_not_blank($value) {
if (is_array($value)) {
$value = $value['text'];
}
$value = trim($value);
return ($value || $value === '0');
}
/**
* Loads the question type specific options for the question.
*
* This function loads any question type specific options for the
* question from the database into the question object. This information
* is placed in the $question->options field. A question type is
* free, however, to decide on a internal structure of the options field.
* @return bool Indicates success or failure.
* @param object $question The question object for the question. This object
* should be updated to include the question type
* specific information (it is passed by reference).
*/
public function get_question_options($question) {
global $DB, $OUTPUT;
// Load the options.
if (!$question->options = $DB->get_record('qtype_ordering_options', array('questionid' => $question->id))) {
echo $OUTPUT->notification('Error: Missing question options!');
return false;
}
// Load the answers - "fraction" is used to signify the order of the answers,
// with id as a tie-break which should not be required.
if (!$question->options->answers = $DB->get_records('question_answers',
array('question' => $question->id), 'fraction, id')) {
echo $OUTPUT->notification('Error: Missing question answers for ordering question ' . $question->id . '!');
return false;
}
parent::get_question_options($question);
return true;
}
/**
* Deletes the question-type specific data when a question is deleted.
*
* @param int $questionid The id of question being deleted.
* @param int $contextid the context this quesiotn belongs to.
*/
public function delete_question($questionid, $contextid) {
global $DB;
$DB->delete_records('qtype_ordering_options', array('questionid' => $questionid));
parent::delete_question($questionid, $contextid);
}
/**
* Import question from GIFT format
*
* @param array $lines
* @param object $question
* @param qformat_gift $format
* @param string $extra (optional, default=null)
* @return object Question instance
*/
public function import_from_gift($lines, $question, $format, $extra=null) {
global $CFG;
require_once($CFG->dirroot.'/question/type/ordering/question.php');
// Extract question info from GIFT file $lines.
$questionname = '[^{]*';
$selectcount = '\d+';
$selecttype = '(?:ALL|EXACT|'.
'RANDOM|REL|'.
'CONTIGUOUS|CONTIG)?';
$layouttype = '(?:HORIZONTAL|HORI|H|1|'.
'VERTICAL|VERT|V|0)?';
$gradingtype = '(?:ALL_OR_NOTHING|'.
'ABSOLUTE_POSITION|'.
'ABSOLUTE|ABS|'.
'RELATIVE_NEXT_EXCLUDE_LAST|'.
'RELATIVE_NEXT_INCLUDE_LAST|'.
'RELATIVE_ONE_PREVIOUS_AND_NEXT|'.
'RELATIVE_ALL_PREVIOUS_AND_NEXT|'.
'RELATIVE_TO_CORRECT|'.
'RELATIVE|REL'.
'LONGEST_ORDERED_SUBSET|'.
'LONGEST_CONTIGUOUS_SUBSET)?';
$showgrading = '(?:SHOW|TRUE|YES|1|HIDE|FALSE|NO|0)?';
$numberingstyle = '(?:none|123|abc|ABCD|iii|IIII)?';
$search = '/^\s*>\s*('.$selectcount.')\s*'.
'('.$selecttype.')\s*'.
'('.$layouttype.')\s*'.
'('.$gradingtype.')\s*'.
'('.$showgrading.')\s*'.
'('.$numberingstyle.')\s*'.
'(.*?)\s*$/s';
// Item $1 the number of items to be shown.
// Item $2 the extraction/grading type.
// Item $3 the layout type.
// Item $4 the grading type.
// Item $5 show the grading details (SHOW/HIDE).
// Item $6 the numbering style (none/123/abc/...).
// Item $7 the lines of items to be ordered.
if (! $extra) {
return false; // Format not recognized.
}
if (! preg_match($search, $extra, $matches)) {
return false; // Format not recognized.
}
$selectcount = trim($matches[1]);
$selecttype = trim($matches[2]);
$layouttype = trim($matches[3]);
$gradingtype = trim($matches[4]);
$showgrading = trim($matches[5]);
$numberingstyle = trim($matches[6]);
$answers = preg_split('/[\r\n]+/', $matches[7]);
$answers = array_filter($answers);
if (empty($question)) {
$text = implode(PHP_EOL, $lines);
$text = trim($text);
if ($pos = strpos($text, '{')) {
$text = substr($text, 0, $pos);
}
// Extract name.
$name = false;
if (substr($text, 0, 2) == '::') {
$text = substr($text, 2);
$pos = strpos($text, '::');
if (is_numeric($pos)) {
$name = substr($text, 0, $pos);
$name = $format->clean_question_name($name);
$text = trim(substr($text, $pos + 2));
}
}
// Extract question text format.
$format = FORMAT_MOODLE;
if (substr($text, 0, 1) == '[') {
$text = substr($text, 1);
$pos = strpos($text, ']');
if (is_numeric($pos)) {
$format = substr($text, 0, $pos);
switch ($format) {
case 'html':
$format = FORMAT_HTML;
break;
case 'plain':
$format = FORMAT_PLAIN;
break;
case 'markdown':
$format = FORMAT_MARKDOWN;
break;
case 'moodle':
$format = FORMAT_MOODLE;
break;
}
$text = trim(substr($text, $pos + 1)); // Remove name from text.
}
}
$question = new stdClass();
$question->name = $name;
$question->questiontext = $text;
$question->questiontextformat = $format;
$question->generalfeedback = '';
$question->generalfeedbackformat = FORMAT_MOODLE;
}
$question->qtype = 'ordering';
// Set "selectcount" field from $selectcount.
if (is_numeric($selectcount) && $selectcount > 2 && $selectcount <= count($answers)) {
$selectcount = intval($selectcount);
} else {
$selectcount = min(6, count($answers));
}
$this->set_options_for_import($question, $layouttype, $selecttype, $selectcount,
$gradingtype, $showgrading, $numberingstyle);
// Remove blank items.
$answers = array_map('trim', $answers);
$answers = array_filter($answers); // Remove blanks.
// Set up answer arrays.
$question->answer = array();
$question->answerformat = array();
$question->fraction = array();
$question->feedback = array();
$question->feedbackformat = array();
// Note that "fraction" field is used to denote sort order
// "fraction" fields will be set to correct values later
// in the save_question_options() method of this class.
foreach ($answers as $i => $answer) {
$question->answer[$i] = $answer;
$question->answerformat[$i] = FORMAT_MOODLE;
$question->fraction[$i] = 1; // Will be reset later in save_question_options().
$question->feedback[$i] = '';
$question->feedbackformat[$i] = FORMAT_MOODLE;
}
// Check that the required feedback fields exist.
$this->check_ordering_combined_feedback($question);
return $question;
}
/**
* Check that the required feedback fields exist
*
* @param object $question
*/
protected function check_ordering_combined_feedback(&$question) {
foreach ($this->feedbackfields as $field) {
if (empty($question->$field)) {
$question->$field = array('text' => '', 'format' => FORMAT_MOODLE, 'itemid' => 0, 'files' => null);
}
}
}
/**
* Given question object, returns array with array layouttype, selecttype, selectcount, gradingtype, showgrading
* where layouttype, selecttype, gradingtype and showgrading are string representations.
*
* @param object $question
* @return array(layouttype, selecttype, selectcount, gradingtype, $showgrading, $numberingstyle)
*/
public function extract_options_for_export($question) {
switch ($question->options->layouttype) {
case qtype_ordering_question::LAYOUT_VERTICAL:
$layouttype = 'VERTICAL';
break;
case qtype_ordering_question::LAYOUT_HORIZONTAL:
$layouttype = 'HORIZONTAL';
break;
default:
$layouttype = ''; // Shouldn't happen !!
}
switch ($question->options->selecttype) {
case qtype_ordering_question::SELECT_ALL:
$selecttype = 'ALL';
break;
case qtype_ordering_question::SELECT_RANDOM:
$selecttype = 'RANDOM';
break;
case qtype_ordering_question::SELECT_CONTIGUOUS:
$selecttype = 'CONTIGUOUS';
break;
default:
$selecttype = ''; // Shouldn't happen !!
}
switch ($question->options->gradingtype) {
case qtype_ordering_question::GRADING_ALL_OR_NOTHING:
$gradingtype = 'ALL_OR_NOTHING';
break;
case qtype_ordering_question::GRADING_ABSOLUTE_POSITION:
$gradingtype = 'ABSOLUTE_POSITION';
break;
case qtype_ordering_question::GRADING_RELATIVE_NEXT_EXCLUDE_LAST:
$gradingtype = 'RELATIVE_NEXT_EXCLUDE_LAST';
break;
case qtype_ordering_question::GRADING_RELATIVE_NEXT_INCLUDE_LAST:
$gradingtype = 'RELATIVE_NEXT_INCLUDE_LAST';
break;
case qtype_ordering_question::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT:
$gradingtype = 'RELATIVE_ONE_PREVIOUS_AND_NEXT';
break;
case qtype_ordering_question::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT:
$gradingtype = 'RELATIVE_ALL_PREVIOUS_AND_NEXT';
break;
case qtype_ordering_question::GRADING_LONGEST_ORDERED_SUBSET:
$gradingtype = 'LONGEST_ORDERED_SUBSET';
break;
case qtype_ordering_question::GRADING_LONGEST_CONTIGUOUS_SUBSET:
$gradingtype = 'LONGEST_CONTIGUOUS_SUBSET';
break;
case qtype_ordering_question::GRADING_RELATIVE_TO_CORRECT:
$gradingtype = 'RELATIVE_TO_CORRECT';
break;
default:
$gradingtype = ''; // Shouldn't happen !!
}
switch ($question->options->showgrading) {
case 0:
$showgrading = 'HIDE';
break;
case 1:
$showgrading = 'SHOW';
break;
default:
$showgrading = ''; // Shouldn't happen !!
}
if (empty($question->options->numberingstyle)) {
$numberingstyle = qtype_ordering_question::NUMBERING_STYLE_DEFAULT;
} else {
$numberingstyle = $question->options->numberingstyle;
}
// Note: this used to be (selectcount + 2).
$selectcount = $question->options->selectcount;
return array($layouttype, $selecttype, $selectcount, $gradingtype, $showgrading, $numberingstyle);
}
/**
* Exports question to GIFT format
*
* @param object $question
* @param qformat_gift $format
* @param string $extra (optional, default=null)
* @return string GIFT representation of question
*/
public function export_to_gift($question, $format, $extra=null) {
global $CFG;
require_once($CFG->dirroot.'/question/type/ordering/question.php');
$output = '';
if ($question->name) {
$output .= '::'.$question->name.'::';
}
switch ($question->questiontextformat) {
case FORMAT_HTML:
$output .= '[html]';
break;
case FORMAT_PLAIN:
$output .= '[plain]';
break;
case FORMAT_MARKDOWN:
$output .= '[markdown]';
break;
case FORMAT_MOODLE:
$output .= '[moodle]';
break;
}
$output .= $question->questiontext.'{';
list($layouttype, $selecttype, $selectcount, $gradingtype, $showgrading, $numberingstyle) =
$this->extract_options_for_export($question);
$output .= ">$selectcount $selecttype $layouttype $gradingtype $showgrading $numberingstyle".PHP_EOL;
foreach ($question->options->answers as $answer) {
$output .= $answer->answer.PHP_EOL;
}
$output .= '}';
return $output;
}
/**
* Exports question to XML format
*
* @param object $question
* @param qformat_xml $format
* @param string $extra (optional, default=null)
* @return string XML representation of question
*/
public function export_to_xml($question, qformat_xml $format, $extra=null) {
global $CFG;
require_once($CFG->dirroot.'/question/type/ordering/question.php');
list($layouttype, $selecttype, $selectcount, $gradingtype, $showgrading, $numberingstyle) =
$this->extract_options_for_export($question);
$output = '';
$output .= " <layouttype>$layouttype</layouttype>\n";
$output .= " <selecttype>$selecttype</selecttype>\n";
$output .= " <selectcount>$selectcount</selectcount>\n";
$output .= " <gradingtype>$gradingtype</gradingtype>\n";
$output .= " <showgrading>$showgrading</showgrading>\n";
$output .= " <numberingstyle>$numberingstyle</numberingstyle>\n";
$output .= $format->write_combined_feedback($question->options, $question->id, $question->contextid);
$shownumcorrect = $question->options->shownumcorrect;
if (!empty($question->options->shownumcorrect)) {
$output = str_replace(" <shownumcorrect/>\n", "", $output);
}
$output .= " <shownumcorrect>$shownumcorrect</shownumcorrect>\n";
foreach ($question->options->answers as $answer) {
$output .= ' <answer fraction="'.$answer->fraction.'" '.$format->format($answer->answerformat).">\n";
$output .= $format->writetext($answer->answer, 3);
if ($feedback = trim($answer->feedback)) { // Usually there is no feedback.
$output .= ' <feedback '.$format->format($answer->feedbackformat).">\n";
$output .= $format->writetext($answer->feedback, 4);
$output .= $format->write_files($answer->feedbackfiles);
$output .= " </feedback>\n";
}
$output .= " </answer>\n";
}
return $output;
}
/**
* Imports question from the Moodle XML format
*
* Imports question using information from extra_question_fields function
* If some of you fields contains id's you'll need to reimplement this
*
* @param array $data
* @param qtype_ordering $question (or null)
* @param qformat_xml $format
* @param string $extra (optional, default=null)
* @return object New question object
*/
public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
global $CFG;
require_once($CFG->dirroot.'/question/type/ordering/question.php');
$questiontype = $format->getpath($data, array('@', 'type'), '');
if ($questiontype != 'ordering') {
return false;
}
$newquestion = $format->import_headers($data);
$newquestion->qtype = $questiontype;
// Fix empty or long question name.
$newquestion->name = $this->fix_questionname($newquestion->name, $newquestion->questiontext);
// Extra fields - "selecttype" and "selectcount"
// (these fields used to be called "logical" and "studentsee").
if (isset($data['#']['selecttype'])) {
$selecttype = 'selecttype';
$selectcount = 'selectcount';
} else {
$selecttype = 'logical';
$selectcount = 'studentsee';
}
$layouttype = $format->getpath($data, array('#', 'layouttype', 0, '#'), 'VERTICAL');
$selecttype = $format->getpath($data, array('#', $selecttype, 0, '#'), 'RANDOM');
$selectcount = $format->getpath($data, array('#', $selectcount, 0, '#'), 6);
$gradingtype = $format->getpath($data, array('#', 'gradingtype', 0, '#'), 'RELATIVE');
$showgrading = $format->getpath($data, array('#', 'showgrading', 0, '#'), '1');
$numberingstyle = $format->getpath($data, array('#', 'numberingstyle', 0, '#'), '1');
$this->set_options_for_import($newquestion, $layouttype, $selecttype, $selectcount,
$gradingtype, $showgrading, $numberingstyle);
$newquestion->answer = array();
$newquestion->answerformat = array();
$newquestion->fraction = array();
$newquestion->feedback = array();
$newquestion->feedbackformat = array();
$i = 0;
while ($answer = $format->getpath($data, array('#', 'answer', $i), '')) {
$ans = $format->import_answer($answer, true, $format->get_format($newquestion->questiontextformat));
$newquestion->answer[$i] = $ans->answer;
$newquestion->fraction[$i] = 1; // Will be reset later in save_question_options().
$newquestion->feedback[$i] = $ans->feedback;
$i++;
}
$format->import_combined_feedback($newquestion, $data, false);
$newquestion->shownumcorrect = $format->getpath($data, ['#', 'shownumcorrect', 0, '#'], null);
// Check that the required feedback fields exist.
$this->check_ordering_combined_feedback($newquestion);
$format->import_hints($newquestion, $data, true, true);
if (!isset($newquestion->shownumcorrect)) {
$newquestion->shownumcorrect = 1;
$counthintshownumcorrect = self::DEFAULT_NUM_HINTS;
$counthintoptions = self::DEFAULT_NUM_HINTS;
if (isset($newquestion->hintshownumcorrect)) {
$counthintshownumcorrect = max(self::DEFAULT_NUM_HINTS, count($newquestion->hintshownumcorrect));
}
if (isset($newquestion->hintoptions)) {
$counthintoptions = max(self::DEFAULT_NUM_HINTS, count($newquestion->hintoptions));
}
$newquestion->hintshownumcorrect = array_fill(0, $counthintshownumcorrect, 1);
$newquestion->hintoptions = array_fill(0, $counthintoptions, 1);
}
return $newquestion;
}
/**
* Fix empty or long question name
*
* @param string $name
* @param string $defaultname (optional, default='')
* @param integer $maxnamelength (optional, default=42)
* @return string Fixed name
*/
public function fix_questionname($name, $defaultname='', $maxnamelength = 42) {
if (trim($name) == '') {
if ($defaultname) {
$name = $defaultname;
} else {
$name = get_string('defaultquestionname', 'qtype_ordering');
}
}
if (strlen($name) > $maxnamelength) {
$name = substr($name, 0, $maxnamelength);
if ($pos = strrpos($name, ' ')) {
$name = substr($name, 0, $pos);
}
$name .= ' ...';
}
return $name;
}
/**
* Set layouttype, selecttype, selectcount, gradingtype, showgrading based on their textual representation
*
* @param object $question (passed by reference)
* @param string $layout the layout type
* @param string $select the select type
* @param string $count the number of items to display
* @param string $grading the grading type
* @param string $show the grading details or not
*/
public function set_options_for_import(&$question, $layouttype, $selecttype, $selectcount,
$gradingtype, $showgrading, $numberingstyle) {
// Set "layouttype" option.
switch (strtoupper($layouttype)) {
case 'HORIZONTAL':
case 'HORI':
case 'H':
case '1':
$question->layouttype = qtype_ordering_question::LAYOUT_HORIZONTAL;
break;
case 'VERTICAL':
case 'VERT':
case 'V':
case '0':
$question->layouttype = qtype_ordering_question::LAYOUT_VERTICAL;
break;
default:
$question->layouttype = qtype_ordering_question::LAYOUT_VERTICAL;
}
// Set "selecttype" option.
switch (strtoupper($selecttype)) {
case 'ALL':
case 'EXACT':
$question->selecttype = qtype_ordering_question::SELECT_ALL;
break;
case 'RANDOM':
case 'REL':
$question->selecttype = qtype_ordering_question::SELECT_RANDOM;
break;
case 'CONTIGUOUS':
case 'CONTIG':
$question->selecttype = qtype_ordering_question::SELECT_CONTIGUOUS;
break;
default:
$question->selecttype = qtype_ordering_question::SELECT_RANDOM;
}
// Set "selectcount" option - this used to be ($count - 2).
if (is_numeric($selectcount)) {
$question->selectcount = intval($selectcount);
} else {
$question->selectcount = 3; // Default!
}
// Set "gradingtype" option.
switch (strtoupper($gradingtype)) {
case 'ALL_OR_NOTHING':
$question->gradingtype = qtype_ordering_question::GRADING_ALL_OR_NOTHING;
break;
case 'ABS':
case 'ABSOLUTE':
case 'ABSOLUTE_POSITION':
$question->gradingtype = qtype_ordering_question::GRADING_ABSOLUTE_POSITION;
break;
case 'REL':
case 'RELATIVE':
case 'RELATIVE_NEXT_EXCLUDE_LAST':
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_NEXT_EXCLUDE_LAST;
break;
case 'RELATIVE_NEXT_INCLUDE_LAST':
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_NEXT_INCLUDE_LAST;
break;
case 'RELATIVE_ONE_PREVIOUS_AND_NEXT':
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_ONE_PREVIOUS_AND_NEXT;
break;
case 'RELATIVE_ALL_PREVIOUS_AND_NEXT':
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_ALL_PREVIOUS_AND_NEXT;
break;
case 'LONGEST_ORDERED_SUBSET':
$question->gradingtype = qtype_ordering_question::GRADING_LONGEST_ORDERED_SUBSET;
break;
case 'LONGEST_CONTIGUOUS_SUBSET':
$question->gradingtype = qtype_ordering_question::GRADING_LONGEST_CONTIGUOUS_SUBSET;
break;
case 'RELATIVE_TO_CORRECT':
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_TO_CORRECT;
break;
default:
$question->gradingtype = qtype_ordering_question::GRADING_RELATIVE_NEXT_EXCLUDE_LAST;
}
// Set "showgrading" option.
switch (strtoupper($showgrading)) {
case 'SHOW':
case 'TRUE':
case 'YES':
$question->showgrading = 1;
break;
case 'HIDE':
case 'FALSE':
case 'NO':
$question->showgrading = 0;
break;
default:
$question->showgrading = 1;
break;
}
// Set "numberingstyle" option.
switch ($numberingstyle) {
case 'none':
case '123':
case 'abc':
case 'ABCD':
case 'iii':