mirrored from git://git.moodle.org/moodle.git
/
datalib.php
2062 lines (1816 loc) · 74.2 KB
/
datalib.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/>.
/**
* Code for loading and saving question attempts to and from the database.
*
* Note that many of the methods of this class should be considered private to
* the question engine. They should be accessed through the
* {@link question_engine} class. For example, you should call
* {@link question_engine::save_questions_usage_by_activity()} rather than
* {@link question_engine_data_mapper::insert_questions_usage_by_activity()}.
* The exception to this is some of the reporting methods, like
* {@link question_engine_data_mapper::load_attempts_at_question()}.
*
* A note for future reference. This code is pretty efficient but there are some
* potential optimisations that could be contemplated, at the cost of making the
* code more complex:
*
* 1. (This is probably not worth doing.) In the unit-of-work save method, we
* could get all the ids for steps due to be deleted or modified,
* and delete all the question_attempt_step_data for all of those steps in one
* query. That would save one DB query for each ->stepsupdated. However that number
* is 0 except when re-grading, and when regrading, there are many more inserts
* into question_attempt_step_data than deletes, so it is really hardly worth it.
*
* @package core_question
* @copyright 2009 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* This class controls the loading and saving of question engine data to and from
* the database.
*
* @copyright 2009 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class question_engine_data_mapper {
/**
* @var moodle_database normally points to global $DB, but I prefer not to
* use globals if I can help it.
*/
protected $db;
/**
* @param moodle_database $db a database connectoin. Defaults to global $DB.
*/
public function __construct(moodle_database $db = null) {
if (is_null($db)) {
global $DB;
$this->db = $DB;
} else {
$this->db = $db;
}
}
/**
* Store an entire {@link question_usage_by_activity} in the database,
* including all the question_attempts that comprise it.
*
* You should not call this method directly. You should use
* @link question_engine::save_questions_usage_by_activity()}.
*
* @param question_usage_by_activity $quba the usage to store.
*/
public function insert_questions_usage_by_activity(question_usage_by_activity $quba) {
$record = new stdClass();
$record->contextid = $quba->get_owning_context()->id;
$record->component = $quba->get_owning_component();
$record->preferredbehaviour = $quba->get_preferred_behaviour();
$newid = $this->db->insert_record('question_usages', $record);
$quba->set_id_from_database($newid);
// Initially an array of array of question_attempt_step_objects.
// Built as a nested array for efficiency, then flattened.
$stepdata = array();
foreach ($quba->get_attempt_iterator() as $qa) {
$stepdata[] = $this->insert_question_attempt($qa, $quba->get_owning_context());
}
$this->insert_all_step_data($this->combine_step_data($stepdata));
$quba->set_observer(new question_engine_unit_of_work($quba));
}
/**
* Store an entire {@link question_attempt} in the database,
* including all the question_attempt_steps that comprise it.
*
* You should not call this method directly. You should use
* @link question_engine::save_questions_usage_by_activity()}.
*
* @param question_attempt $qa the question attempt to store.
* @param context $context the context of the owning question_usage_by_activity.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
public function insert_question_attempt(question_attempt $qa, $context) {
$record = new stdClass();
$record->questionusageid = $qa->get_usage_id();
$record->slot = $qa->get_slot();
$record->behaviour = $qa->get_behaviour_name();
$record->questionid = $qa->get_question_id();
$record->variant = $qa->get_variant();
$record->maxmark = $qa->get_max_mark();
$record->minfraction = $qa->get_min_fraction();
$record->maxfraction = $qa->get_max_fraction();
$record->flagged = $qa->is_flagged();
$record->questionsummary = $qa->get_question_summary();
if (core_text::strlen($record->questionsummary) > question_bank::MAX_SUMMARY_LENGTH) {
// It seems some people write very long quesions! MDL-30760
$record->questionsummary = core_text::substr($record->questionsummary,
0, question_bank::MAX_SUMMARY_LENGTH - 3) . '...';
}
$record->rightanswer = $qa->get_right_answer_summary();
$record->responsesummary = $qa->get_response_summary();
$record->timemodified = time();
$record->id = $this->db->insert_record('question_attempts', $record);
$qa->set_database_id($record->id);
// Initially an array of array of question_attempt_step_objects.
// Built as a nested array for efficiency, then flattened.
$stepdata = array();
foreach ($qa->get_step_iterator() as $seq => $step) {
$stepdata[] = $this->insert_question_attempt_step($step, $record->id, $seq, $context);
}
return $this->combine_step_data($stepdata);
}
/**
* Helper method used by insert_question_attempt_step and update_question_attempt_step
*
* @param question_attempt_step $step the step to store.
* @param int $questionattemptid the question attept id this step belongs to.
* @param int $seq the sequence number of this stop.
* @return stdClass data to insert into the database.
*/
protected function make_step_record(question_attempt_step $step, $questionattemptid, $seq) {
$record = new stdClass();
$record->questionattemptid = $questionattemptid;
$record->sequencenumber = $seq;
$record->state = $step->get_state()?->__toString();
$record->fraction = $step->get_fraction();
$record->timecreated = $step->get_timecreated();
$record->userid = $step->get_user_id();
return $record;
}
/**
* Take an array of arrays, and flatten it, even if the outer array is empty.
*
* Only public so it can be called from the unit of work. Not part of the
* public API of this class.
*
* @param array $stepdata array of zero or more arrays.
* @return array made by concatenating all the separate arrays.
*/
public function combine_step_data(array $stepdata): array {
if (empty($stepdata)) {
return [];
}
return call_user_func_array('array_merge', $stepdata);
}
/**
* Helper method used by insert_question_attempt_step and update_question_attempt_step
* @param question_attempt_step $step the step to store.
* @param int $stepid the id of the step.
* @param context $context the context of the owning question_usage_by_activity.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
protected function prepare_step_data(question_attempt_step $step, $stepid, $context) {
$rows = array();
foreach ($step->get_all_data() as $name => $value) {
if ($value instanceof question_file_saver) {
$value->save_files($stepid, $context);
}
if ($value instanceof question_response_files) {
$value = (string) $value;
}
$data = new stdClass();
$data->attemptstepid = $stepid;
$data->name = $name;
$data->value = $value;
$rows[] = $data;
}
return $rows;
}
/**
* Insert a lot of records into question_attempt_step_data in one go.
*
* Private method, only for use by other parts of the question engine.
*
* @param array $rows the rows to insert.
*/
public function insert_all_step_data(array $rows) {
if (!$rows) {
return;
}
$this->db->insert_records('question_attempt_step_data', $rows);
}
/**
* Store a {@link question_attempt_step} in the database.
*
* Private method, only for use by other parts of the question engine.
*
* @param question_attempt_step $step the step to store.
* @param int $questionattemptid the question attept id this step belongs to.
* @param int $seq the sequence number of this stop.
* @param context $context the context of the owning question_usage_by_activity.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
public function insert_question_attempt_step(question_attempt_step $step,
$questionattemptid, $seq, $context) {
$record = $this->make_step_record($step, $questionattemptid, $seq);
$record->id = $this->db->insert_record('question_attempt_steps', $record);
return $this->prepare_step_data($step, $record->id, $context);
}
/**
* Update a {@link question_attempt_step} in the database.
*
* Private method, only for use by other parts of the question engine.
*
* @param question_attempt_step $step the step to store.
* @param int $questionattemptid the question attept id this step belongs to.
* @param int $seq the sequence number of this stop.
* @param context $context the context of the owning question_usage_by_activity.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
public function update_question_attempt_step(question_attempt_step $step,
$questionattemptid, $seq, $context) {
$record = $this->make_step_record($step, $questionattemptid, $seq);
$record->id = $step->get_id();
$this->db->update_record('question_attempt_steps', $record);
$this->db->delete_records('question_attempt_step_data',
array('attemptstepid' => $record->id));
return $this->prepare_step_data($step, $record->id, $context);
}
/**
* Store new metadata for an existing {@link question_attempt} in the database.
*
* Private method, only for use by other parts of the question engine.
*
* @param question_attempt $qa the question attempt to store meta data for.
* @param array $names the names of the metadata variables to store.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
public function insert_question_attempt_metadata(question_attempt $qa, array $names) {
$firststep = $qa->get_step(0);
$rows = array();
foreach ($names as $name) {
$data = new stdClass();
$data->attemptstepid = $firststep->get_id();
$data->name = ':_' . $name;
$data->value = $firststep->get_metadata_var($name);
$rows[] = $data;
}
return $rows;
}
/**
* Updates existing metadata for an existing {@link question_attempt} in the database.
*
* Private method, only for use by other parts of the question engine.
*
* @param question_attempt $qa the question attempt to store meta data for.
* @param array $names the names of the metadata variables to store.
* @return array of question_attempt_step_data rows, that still need to be inserted.
*/
public function update_question_attempt_metadata(question_attempt $qa, array $names) {
global $DB;
if (!$names) {
return [];
}
// Use case-sensitive function sql_equal() and not get_in_or_equal().
// Some databases may use case-insensitive collation, we don't want to delete 'X' instead of 'x'.
$sqls = [];
$params = [$qa->get_step(0)->get_id()];
foreach ($names as $name) {
$sqls[] = $DB->sql_equal('name', '?');
$params[] = $name;
}
$DB->delete_records_select('question_attempt_step_data',
'attemptstepid = ? AND (' . join(' OR ', $sqls) . ')', $params);
return $this->insert_question_attempt_metadata($qa, $names);
}
/**
* Load a {@link question_attempt_step} from the database.
*
* Private method, only for use by other parts of the question engine.
*
* @param int $stepid the id of the step to load.
* @return question_attempt_step the step that was loaded.
*/
public function load_question_attempt_step($stepid) {
$records = $this->db->get_recordset_sql("
SELECT
quba.contextid,
COALESCE(q.qtype, 'missingtype') AS qtype,
qas.id AS attemptstepid,
qas.questionattemptid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid,
qasd.name,
qasd.value
FROM {question_attempt_steps} qas
JOIN {question_attempts} qa ON qa.id = qas.questionattemptid
JOIN {question_usages} quba ON quba.id = qa.questionusageid
LEFT JOIN {question} q ON q.id = qa.questionid
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
WHERE
qas.id = :stepid
", array('stepid' => $stepid));
if (!$records->valid()) {
throw new coding_exception('Failed to load question_attempt_step ' . $stepid);
}
$step = question_attempt_step::load_from_records($records, $stepid);
$records->close();
return $step;
}
/**
* Load a {@link question_attempt} from the database, including all its
* steps.
*
* Normally, you should use {@link question_engine::load_questions_usage_by_activity()}
* but there may be rare occasions where for performance reasons, you only
* wish to load one qa, in which case you may call this method.
*
* @param int $questionattemptid the id of the question attempt to load.
* @return question_attempt the question attempt that was loaded.
*/
public function load_question_attempt($questionattemptid) {
$records = $this->db->get_recordset_sql("
SELECT
quba.contextid,
quba.preferredbehaviour,
qa.id AS questionattemptid,
qa.questionusageid,
qa.slot,
qa.behaviour,
qa.questionid,
qa.variant,
qa.maxmark,
qa.minfraction,
qa.maxfraction,
qa.flagged,
qa.questionsummary,
qa.rightanswer,
qa.responsesummary,
qa.timemodified,
qas.id AS attemptstepid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid,
qasd.name,
qasd.value
FROM {question_attempts} qa
JOIN {question_usages} quba ON quba.id = qa.questionusageid
LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
WHERE
qa.id = :questionattemptid
ORDER BY
qas.sequencenumber
", array('questionattemptid' => $questionattemptid));
if (!$records->valid()) {
throw new coding_exception('Failed to load question_attempt ' . $questionattemptid);
}
$record = $records->current();
$qa = question_attempt::load_from_records($records, $questionattemptid,
new question_usage_null_observer(), $record->preferredbehaviour);
$records->close();
return $qa;
}
/**
* Load a {@link question_usage_by_activity} from the database, including
* all its {@link question_attempt}s and all their steps.
*
* You should call {@link question_engine::load_questions_usage_by_activity()}
* rather than calling this method directly.
*
* @param int $qubaid the id of the usage to load.
* @return question_usage_by_activity the usage that was loaded.
*/
public function load_questions_usage_by_activity($qubaid) {
$records = $this->db->get_recordset_sql("
SELECT
quba.id AS qubaid,
quba.contextid,
quba.component,
quba.preferredbehaviour,
qa.id AS questionattemptid,
qa.questionusageid,
qa.slot,
qa.behaviour,
qa.questionid,
qa.variant,
qa.maxmark,
qa.minfraction,
qa.maxfraction,
qa.flagged,
qa.questionsummary,
qa.rightanswer,
qa.responsesummary,
qa.timemodified,
qas.id AS attemptstepid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid,
qasd.name,
qasd.value
FROM {question_usages} quba
LEFT JOIN {question_attempts} qa ON qa.questionusageid = quba.id
LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
WHERE
quba.id = :qubaid
ORDER BY
qa.slot,
qas.sequencenumber
", array('qubaid' => $qubaid));
if (!$records->valid()) {
throw new coding_exception('Failed to load questions_usage_by_activity ' . $qubaid);
}
$quba = question_usage_by_activity::load_from_records($records, $qubaid);
$records->close();
return $quba;
}
/**
* Load all {@link question_usage_by_activity} from the database for one qubaid_condition
* Include all its {@link question_attempt}s and all their steps.
*
* This method may be called publicly.
*
* @param qubaid_condition $qubaids the condition that tells us which usages to load.
* @return question_usage_by_activity[] the usages that were loaded.
*/
public function load_questions_usages_by_activity($qubaids) {
$records = $this->db->get_recordset_sql("
SELECT
quba.id AS qubaid,
quba.contextid,
quba.component,
quba.preferredbehaviour,
qa.id AS questionattemptid,
qa.questionusageid,
qa.slot,
qa.behaviour,
qa.questionid,
qa.variant,
qa.maxmark,
qa.minfraction,
qa.maxfraction,
qa.flagged,
qa.questionsummary,
qa.rightanswer,
qa.responsesummary,
qa.timemodified,
qas.id AS attemptstepid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid,
qasd.name,
qasd.value
FROM {question_usages} quba
LEFT JOIN {question_attempts} qa ON qa.questionusageid = quba.id
LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
WHERE
quba.id {$qubaids->usage_id_in()}
ORDER BY
quba.id,
qa.slot,
qas.sequencenumber
", $qubaids->usage_id_in_params());
$qubas = array();
while ($records->valid()) {
$record = $records->current();
$qubas[$record->qubaid] = question_usage_by_activity::load_from_records($records, $record->qubaid);
}
$records->close();
return $qubas;
}
/**
* Load information about the latest state of each question from the database.
*
* This method may be called publicly.
*
* @param qubaid_condition $qubaids used to restrict which usages are included
* in the query. See {@link qubaid_condition}.
* @param array|null $slots (optional) list of slots for which to return information. Default all slots.
* @param string|null $fields
* @return array of records. See the SQL in this function to see the fields available.
*/
public function load_questions_usages_latest_steps(qubaid_condition $qubaids, $slots = null, $fields = null) {
if ($slots === []) {
return [];
} else if ($slots !== null) {
[$slottest, $params] = $this->db->get_in_or_equal($slots, SQL_PARAMS_NAMED, 'slot');
$slotwhere = " AND qa.slot {$slottest}";
} else {
$slotwhere = '';
$params = [];
}
if ($fields === null) {
$fields = "qas.id,
qa.id AS questionattemptid,
qa.questionusageid,
qa.slot,
qa.behaviour,
qa.questionid,
qa.variant,
qa.maxmark,
qa.minfraction,
qa.maxfraction,
qa.flagged,
qa.questionsummary,
qa.rightanswer,
qa.responsesummary,
qa.timemodified,
qas.id AS attemptstepid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid";
}
$records = $this->db->get_records_sql("
SELECT
{$fields}
FROM {$qubaids->from_question_attempts('qa')}
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
WHERE
{$qubaids->where()}
$slotwhere
", $params + $qubaids->from_where_params());
return $records;
}
/**
* Load summary information about the state of each question in a group of
* attempts. This is used, for example, by the quiz manual grading report,
* to show how many attempts at each question need to be graded.
*
* This method may be called publicly.
*
* @param qubaid_condition $qubaids used to restrict which usages are included
* in the query. See {@link qubaid_condition}.
* @param array|null $slots (optional) list of slots for which to return information. Default all slots.
* @return array The array keys are 'slot,questionid'. The values are objects with
* fields $slot, $questionid, $inprogress, $name, $needsgrading, $autograded,
* $manuallygraded and $all.
*/
public function load_questions_usages_question_state_summary(qubaid_condition $qubaids, $slots = null) {
if ($slots !== null) {
[$slottest, $params] = $this->db->get_in_or_equal($slots, SQL_PARAMS_NAMED, 'slot');
$slotwhere = " AND qa.slot {$slottest}";
} else {
$slotwhere = '';
$params = [];
}
$rs = $this->db->get_recordset_sql("
SELECT
qa.slot,
qa.questionid,
q.name,
CASE qas.state
{$this->full_states_to_summary_state_sql()}
END AS summarystate,
COUNT(1) AS numattempts
FROM {$qubaids->from_question_attempts('qa')}
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
JOIN {question} q ON q.id = qa.questionid
WHERE
{$qubaids->where()}
$slotwhere
GROUP BY
qa.slot,
qa.questionid,
q.name,
q.id,
CASE qas.state
{$this->full_states_to_summary_state_sql()}
END
ORDER BY
qa.slot,
qa.questionid,
q.name,
q.id
", $params + $qubaids->from_where_params());
$results = array();
foreach ($rs as $row) {
$index = $row->slot . ',' . $row->questionid;
if (!array_key_exists($index, $results)) {
$res = new stdClass();
$res->slot = $row->slot;
$res->questionid = $row->questionid;
$res->name = $row->name;
$res->inprogress = 0;
$res->needsgrading = 0;
$res->autograded = 0;
$res->manuallygraded = 0;
$res->all = 0;
$results[$index] = $res;
}
$results[$index]->{$row->summarystate} = $row->numattempts;
$results[$index]->all += $row->numattempts;
}
$rs->close();
return $results;
}
/**
* Get a list of usage ids where the question with slot $slot, and optionally
* also with question id $questionid, is in summary state $summarystate. Also
* return the total count of such states.
*
* Only a subset of the ids can be returned by using $orderby, $limitfrom and
* $limitnum. A special value 'random' can be passed as $orderby, in which case
* $limitfrom is ignored.
*
* This method may be called publicly.
*
* @param qubaid_condition $qubaids used to restrict which usages are included
* in the query. See {@link qubaid_condition}.
* @param int $slot The slot for the questions you want to know about.
* @param int $questionid (optional) Only return attempts that were of this specific question.
* @param string $summarystate the summary state of interest, or 'all'.
* @param string $orderby the column to order by.
* @param array $params any params required by any of the SQL fragments.
* @param int $limitfrom implements paging of the results.
* Ignored if $orderby = random or $limitnum is null.
* @param int $limitnum implements paging of the results. null = all.
* @param string $extraselect anything passed here will be added to the SELECT list, use this to return extra data.
* @return array with two elements, an array of usage ids, and a count of the total number.
*/
public function load_questions_usages_where_question_in_state(
qubaid_condition $qubaids, $summarystate, $slot, $questionid = null,
$orderby = 'random', $params = array(), $limitfrom = 0, $limitnum = null, $extraselect = '') {
$extrawhere = '';
if ($questionid) {
$extrawhere .= ' AND qa.questionid = :questionid';
$params['questionid'] = $questionid;
}
if ($summarystate !== 'all') {
list($test, $sparams) = $this->in_summary_state_test($summarystate);
$extrawhere .= ' AND qas.state ' . $test;
$params += $sparams;
}
if (!empty($extraselect)) {
$extraselect = ', ' . $extraselect;
}
if ($orderby === 'random') {
$sqlorderby = '';
} else if ($orderby) {
$sqlorderby = 'ORDER BY ' . $orderby;
} else {
$sqlorderby = '';
}
// We always want the total count, as well as the partcular list of ids
// based on the paging and sort order. Because the list of ids is never
// going to be too ridiculously long. My worst-case scenario is
// 10,000 students in the course, each doing 5 quiz attempts. That
// is a 50,000 element int => int array, which PHP seems to use 5MB
// memory to store on a 64 bit server.
$qubaidswhere = $qubaids->where(); // Must call this before params.
$params += $qubaids->from_where_params();
$params['slot'] = $slot;
$sql = "SELECT qa.questionusageid,
1
$extraselect
FROM {$qubaids->from_question_attempts('qa')}
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
JOIN {question} q ON q.id = qa.questionid
WHERE {$qubaidswhere}
AND qa.slot = :slot
$extrawhere
$sqlorderby";
$qubaids = $this->db->get_records_sql_menu($sql, $params);
$qubaids = array_keys($qubaids);
$count = count($qubaids);
if ($orderby === 'random') {
shuffle($qubaids);
$limitfrom = 0;
}
if (!is_null($limitnum)) {
$qubaids = array_slice($qubaids, $limitfrom, $limitnum);
}
return array($qubaids, $count);
}
/**
* Load the average mark, and number of attempts, for each slot in a set of
* question usages..
*
* This method may be called publicly.
*
* @param qubaid_condition $qubaids used to restrict which usages are included
* in the query. See {@link qubaid_condition}.
* @param array|null $slots if null, load info for all quesitions, otherwise only
* load the averages for the specified questions.
* @return array of objects with fields ->slot, ->averagefraction and ->numaveraged.
*/
public function load_average_marks(qubaid_condition $qubaids, $slots = null) {
if (!empty($slots)) {
list($slottest, $slotsparams) = $this->db->get_in_or_equal(
$slots, SQL_PARAMS_NAMED, 'slot');
$slotwhere = " AND qa.slot {$slottest}";
} else {
$slotwhere = '';
$slotsparams = array();
}
list($statetest, $stateparams) = $this->db->get_in_or_equal(array(
(string) question_state::$gaveup,
(string) question_state::$gradedwrong,
(string) question_state::$gradedpartial,
(string) question_state::$gradedright,
(string) question_state::$mangaveup,
(string) question_state::$mangrwrong,
(string) question_state::$mangrpartial,
(string) question_state::$mangrright), SQL_PARAMS_NAMED, 'st');
return $this->db->get_records_sql("
SELECT
qa.slot,
AVG(COALESCE(qas.fraction, 0)) AS averagefraction,
COUNT(1) AS numaveraged
FROM {$qubaids->from_question_attempts('qa')}
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
WHERE
{$qubaids->where()}
$slotwhere
AND qas.state $statetest
GROUP BY qa.slot
ORDER BY qa.slot
", $slotsparams + $stateparams + $qubaids->from_where_params());
}
/**
* Load all the attempts at a given queston from a set of question_usages.
* steps.
*
* This method may be called publicly.
*
* @param int $questionid the question to load all the attempts fors.
* @param qubaid_condition $qubaids used to restrict which usages are included
* in the query. See {@link qubaid_condition}.
* @return question_attempt[] array of question_attempts that were loaded.
*/
public function load_attempts_at_question($questionid, qubaid_condition $qubaids) {
$sql = "
SELECT
quba.contextid,
quba.preferredbehaviour,
qa.id AS questionattemptid,
qa.questionusageid,
qa.slot,
qa.behaviour,
qa.questionid,
qa.variant,
qa.maxmark,
qa.minfraction,
qa.maxfraction,
qa.flagged,
qa.questionsummary,
qa.rightanswer,
qa.responsesummary,
qa.timemodified,
qas.id AS attemptstepid,
qas.sequencenumber,
qas.state,
qas.fraction,
qas.timecreated,
qas.userid,
qasd.name,
qasd.value
FROM {$qubaids->from_question_attempts('qa')}
JOIN {question_usages} quba ON quba.id = qa.questionusageid
LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
WHERE
{$qubaids->where()} AND
qa.questionid = :questionid
ORDER BY
quba.id,
qa.id,
qas.sequencenumber";
// For qubaid_list must call this after calling methods that generate sql.
$params = $qubaids->from_where_params();
$params['questionid'] = $questionid;
$records = $this->db->get_recordset_sql($sql, $params);
$questionattempts = array();
while ($records->valid()) {
$record = $records->current();
$questionattempts[$record->questionattemptid] =
question_attempt::load_from_records($records,
$record->questionattemptid, new question_usage_null_observer(),
$record->preferredbehaviour);
}
$records->close();
return $questionattempts;
}
/**
* Update a question_usages row to refect any changes in a usage (but not
* any of its question_attempts.
*
* You should not call this method directly. You should use
* @link question_engine::save_questions_usage_by_activity()}.
*
* @param question_usage_by_activity $quba the usage that has changed.
*/
public function update_questions_usage_by_activity(question_usage_by_activity $quba) {
$record = new stdClass();
$record->id = $quba->get_id();
$record->contextid = $quba->get_owning_context()->id;
$record->component = $quba->get_owning_component();
$record->preferredbehaviour = $quba->get_preferred_behaviour();
$this->db->update_record('question_usages', $record);
}
/**
* Update a question_attempts row to refect any changes in a question_attempt
* (but not any of its steps).
*
* You should not call this method directly. You should use
* @link question_engine::save_questions_usage_by_activity()}.
*
* @param question_attempt $qa the question attempt that has changed.
*/
public function update_question_attempt(question_attempt $qa) {
$record = new stdClass();
$record->id = $qa->get_database_id();
$record->slot = $qa->get_slot();
$record->questionid = $qa->get_question(false)->id;
$record->variant = $qa->get_variant();
$record->maxmark = $qa->get_max_mark();
$record->minfraction = $qa->get_min_fraction();
$record->maxfraction = $qa->get_max_fraction();
$record->flagged = $qa->is_flagged();
$record->questionsummary = $qa->get_question_summary();
$record->rightanswer = $qa->get_right_answer_summary();
$record->responsesummary = $qa->get_response_summary();
$record->timemodified = time();
$this->db->update_record('question_attempts', $record);
}
/**
* Delete a question_usage_by_activity and all its associated
*
* You should not call this method directly. You should use
* @link question_engine::delete_questions_usage_by_activities()}.
*
* {@link question_attempts} and {@link question_attempt_steps} from the
* database.
* @param qubaid_condition $qubaids identifies which question useages to delete.
*/
public function delete_questions_usage_by_activities(qubaid_condition $qubaids) {
$where = "qa.questionusageid {$qubaids->usage_id_in()}";
$params = $qubaids->usage_id_in_params();
$contextids = $this->db->get_records_sql_menu("
SELECT DISTINCT contextid, 1
FROM {question_usages}
WHERE id {$qubaids->usage_id_in()}", $qubaids->usage_id_in_params());
foreach ($contextids as $contextid => $notused) {
$this->delete_response_files($contextid, "IN (
SELECT qas.id
FROM {question_attempts} qa
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
WHERE $where)", $params);
}
if ($this->db->get_dbfamily() == 'mysql') {
$this->delete_usage_records_for_mysql($qubaids);
return;
}
$this->db->delete_records_select('question_attempt_step_data', "attemptstepid IN (
SELECT qas.id
FROM {question_attempts} qa
JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
WHERE $where)", $params);
$this->db->delete_records_select('question_attempt_steps', "questionattemptid IN (
SELECT qa.id
FROM {question_attempts} qa
WHERE $where)", $params);
$this->db->delete_records_select('question_attempts',