-
Notifications
You must be signed in to change notification settings - Fork 58
/
locallib.php
2584 lines (2255 loc) · 99.7 KB
/
locallib.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 mod_offlinequiz for 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/>.
/**
* Internal library of functions for module offlinequiz
*
* All the offlinequiz specific functions, needed to implement the module
* logic, should go here. Never include this file from your lib.php!
*
* @package mod
* @subpackage offlinequiz
* @author Juergen Zimmer <[email protected]>
* @copyright 2015 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org}
* @since Moodle 2.2+
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/filelib.php');
require_once($CFG->dirroot . '/question/editlib.php');
require_once($CFG->dirroot . '/question/format.php');
require_once($CFG->dirroot . '/question/engine/questionusage.php');
// These are the old error codes from the Moodle 1.9 module. We still need them for migration.
define("OFFLINEQUIZ_IMPORT_LMS", "1");
define("OFFLINEQUIZ_IMPORT_OK", "0");
define("OFFLINEQUIZ_IMPORT_CORRECTED", "1");
define("OFFLINEQUIZ_IMPORT_DOUBLE", "2");
define("OFFLINEQUIZ_IMPORT_ITEM_ERROR", "3");
define("OFFLINEQUIZ_IMPORT_DOUBLE_ERROR", "11");
define("OFFLINEQUIZ_IMPORT_USER_ERROR", "12");
define("OFFLINEQUIZ_IMPORT_GROUP_ERROR", "13");
define("OFFLINEQUIZ_IMPORT_FATAL_ERROR", "14");
define("OFFLINEQUIZ_IMPORT_INSECURE_ERROR", "15");
define("OFFLINEQUIZ_IMPORT_PAGE_ERROR", "16");
define("OFFLINEQUIZ_IMPORT_SINGLE_ERROR", "17"); // This is not really an error.
// It occures, when multipage answer sheets are scanned.
define("OFFLINEQUIZ_IMPORT_DOUBLE_PAGE_ERROR", "18"); // New error for double pages (e.g. page 2 occurs twice for as student).
define("OFFLINEQUIZ_IMPORT_DIFFERING_PAGE_ERROR", "19"); // New error for double pages that have different results (rawdata).
// Codes for lists of participants.
define("OFFLINEQUIZ_PART_FATAL_ERROR", "21"); // Over 20 indicates, it is a participants error.
define("OFFLINEQUIZ_PART_INSECURE_ERROR", "22");
define("OFFLINEQUIZ_PART_USER_ERROR", "23");
define("OFFLINEQUIZ_PART_LIST_ERROR", "24");
define("OFFLINEQUIZ_IMPORT_NUMUSERS", "50");
define('OFFLINEQUIZ_USER_FORMULA_REGEXP', "/^([^\[]*)\[([\-]?[0-9]+)\]([^\=]*)=([a-z]+[0-9]?)$/");
define('OFFLINEQUIZ_GROUP_LETTERS', "ABCDEFGHIJKL"); // Letters for naming offlinequiz groups.
define('OFFLINEQUIZ_PDF_FORMAT', 0); // PDF file format for question sheets.
define('OFFLINEQUIZ_DOCX_FORMAT', 1); // DOCX file format for question sheets.
define('OFFLINEQUIZ_LATEX_FORMAT', 2); // LATEX file format for question sheets.
define('OFFLINEQUIZ_QUESTIONINFO_NONE', 0); // No info is printed.
define('OFFLINEQUIZ_QUESTIONINFO_QTYPE', 1); // The question type is printed.
define('OFFLINEQUIZ_QUESTIONINFO_ANSWERS', 2); // The number of correct answers is printed.
define('NUMBERS_PER_PAGE', 30); // Number of students on participants list.
define('OQ_IMAGE_WIDTH', 860); // Width of correction form.
class offlinequiz_question_usage_by_activity extends question_usage_by_activity {
public function get_clone($qinstances) {
// The new quba doesn't have to be cloned, so we can use the parent class.
$newquba = question_engine::make_questions_usage_by_activity($this->owningcomponent, $this->context);
$newquba->set_preferred_behaviour('immediatefeedback');
foreach ($this->get_slots() as $slot) {
$slotquestion = $this->get_question($slot);
$attempt = $this->get_question_attempt($slot);
// We have to check for the type because we might have old migrated templates
// that could contain description questions.
if ($slotquestion->get_type_name() == 'multichoice' || $slotquestion->get_type_name() == 'multichoiceset') {
$order = $slotquestion->get_order($attempt); // Order of the answers.
$order = implode(',', $order);
$newslot = $newquba->add_question($slotquestion, $qinstances[$slotquestion->id]->maxmark);
$qa = $newquba->get_question_attempt($newslot);
$qa->start('immediatefeedback', 1, array('_order' => $order));
}
}
question_engine::save_questions_usage_by_activity($newquba);
return $newquba;
}
/**
* Create a question_usage_by_activity from records loaded from the database.
*
* For internal use only.
*
* @param Iterator $records Raw records loaded from the database.
* @param int $questionattemptid The id of the question_attempt to extract.
* @return question_usage_by_activity The newly constructed usage.
*/
public static function load_from_records($records, $qubaid) {
$record = $records->current();
while ($record->qubaid != $qubaid) {
$records->next();
if (!$records->valid()) {
throw new coding_exception("Question usage $qubaid not found in the database.");
}
$record = $records->current();
}
$quba = new offlinequiz_question_usage_by_activity($record->component,
context::instance_by_id($record->contextid));
$quba->set_id_from_database($record->qubaid);
$quba->set_preferred_behaviour($record->preferredbehaviour);
$quba->observer = new question_engine_unit_of_work($quba);
while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
$quba->questionattempts[$record->slot] = question_attempt::load_from_records($records,
$record->questionattemptid, $quba->observer,
$quba->get_preferred_behaviour());
if ($records->valid()) {
$record = $records->current();
} else {
$record = false;
}
}
return $quba;
}
}
function offlinequiz_print_tabs($offlinequiz, $currenttab, $cm) {
global $CFG, $OUTPUT;
if (empty($offlinequiz) || empty($currenttab) || empty($cm) ) {
return;
}
$tabs = offlinequiz_get_tabs_object($offlinequiz, $cm);
$ct = $tabs[$currenttab];
$options = [];
foreach ($tabs as $tabname => $tabobject) {
if ($tabobject['tab'] == $ct['tab']) {
$options[$tabobject['url']->out()] = isset($tabobject['title'])?$tabobject['title'] : get_string($tabname, 'offlinequiz');
}
}
$selectobject = new \url_select($options);
echo $OUTPUT->render($selectobject);
}
function offlinequiz_get_tabs_object($offlinequiz, $cm) {
global $CFG;
if (empty($offlinequiz) || empty($cm) ) {
return [];
}
$tabs = ['tabeditgroupquestions' =>
['tab' => 'tabofflinequizcontent',
'url' => new moodle_url('/mod/offlinequiz/edit.php', ['cmid' => $cm->id, 'gradetool' => 0])],
'tabpreview' =>
['tab' => 'tabofflinequizcontent',
'url' => new moodle_url('/mod/offlinequiz/navigate.php', ['tab' => 'tabforms', 'id' => $cm->id])],
'tabofflinequizupload' =>
['tab' => 'tabresults',
'url' => new moodle_url('/mod/offlinequiz/report.php', ['q' => $offlinequiz->id, 'mode' => 'rimport'])],
'tabofflinequizcorrect' =>
['tab' => 'tabresults',
'url' => new moodle_url('/mod/offlinequiz/report.php', ['q' => $offlinequiz->id, 'mode' => 'correct'])],
'tabresultsoverview' =>
['tab' => 'tabresults',
'url' => new moodle_url('/mod/offlinequiz/report.php', ['q' => $offlinequiz->id, 'mode' => 'overview'])],
'tabstatsoverview' =>
['tab' => 'tabstatistics',
'url' => new moodle_url('/mod/offlinequiz/report.php',
['q' => $offlinequiz->id, 'mode' => 'statistics'])],
'tabquestionstats' =>
['tab' => 'tabstatistics',
'url' => new moodle_url('/mod/offlinequiz/report.php',
['q' => $offlinequiz->id, 'mode' => 'statistics', 'statmode' => 'questionstats'])],
'tabquestionandanswerstats' =>
['tab' => 'tabstatistics',
'url' => new moodle_url('/mod/offlinequiz/report.php',
['q' => $offlinequiz->id, 'mode' => 'statistics', 'statmode' => 'questionandanswerstats'])],
'tabparticipantlists' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'editlists'])],
'tabeditparticipants' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'editparticipants'])],
'tabdownloadparticipantsforms' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'createpdfs'])],
'tabparticipantsupload' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'upload'])],
'tabparticipantscorrect' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'correct'])],
'tabattendancesoverview' =>
['tab' => 'tabattendances',
'url' => new moodle_url('/mod/offlinequiz/participants.php',
['q' => $offlinequiz->id, 'mode' => 'attendances'])],
];
// Add tabs from subplugins.
$pluginmanager = core_plugin_manager::instance();
$subplugins = $pluginmanager->get_subplugins_of_plugin('mod_offlinequiz');
foreach ($subplugins as $subplugin) {
// Instantiate the subplugin.
$file = $subplugin->rootdir . '/report.php';
if (is_readable($file)) {
require_once($CFG->dirroot . '/mod/offlinequiz/report/default.php');
require_once($file);
$class = "offlinequiz_{$subplugin->name}_report";
$plugin = new $class();
if (method_exists($plugin, 'add_to_tabs')) {
$tabs = $plugin->add_to_tabs($tabs, $cm, $offlinequiz);
}
}
}
return $tabs;
}
function offlinequiz_make_questions_usage_by_activity($component, $context) {
return new offlinequiz_question_usage_by_activity($component, $context);
}
function offlinequiz_get_pdffont($offlinequiz = null) {
$offlinequizconfig = get_config('offlinequiz');
if(!$offlinequiz) {
$id = optional_param('id', 0, PARAM_INT); // Course Module ID.
$q = optional_param('q', 0, PARAM_INT); // Or offlinequiz ID.
if($id || $q) {
list($offlinequiz, $course, $cm) = get_course_objects($id, $q);
}
}
if($offlinequiz && property_exists($offlinequiz,'pdffont')) {
return $offlinequiz->pdffont;
} else if($offlinequizconfig && $offlinequizconfig->defaultpdffont) {
return $offlinequizconfig->defaultpdffont;
} else {
//Default fallback if anything goes horribly wrong
return 'freeserif';
}
}
function get_course_objects($id, $q) {
global $DB;
if ($id) {
if (!$cm = get_coursemodule_from_id('offlinequiz', $id)) {
throw new \moodle_exception("There is no coursemodule with id $id");
}
if (!$course = $DB->get_record("course", array('id' => $cm->course))) {
throw new \moodle_exception("Course is misconfigured");
}
if (!$offlinequiz = $DB->get_record("offlinequiz", array('id' => $cm->instance))) {
throw new \moodle_exception("The offlinequiz with id $cm->instance corresponding to this coursemodule $id is missing");
}
} else {
if (!$offlinequiz = $DB->get_record("offlinequiz", array('id' => $q))) {
throw new \moodle_exception("There is no offlinequiz with id $q");
}
if (!$course = $DB->get_record("course", array('id' => $offlinequiz->course))) {
throw new \moodle_exception("The course with id $offlinequiz->course that the offlinequiz with id $q belongs to is missing");
}
if (!$cm = get_coursemodule_from_instance('offlinequiz', $offlinequiz->id, $course->id)) {
throw new \moodle_exception("The course module for the offlinequiz with id $q is missing");
}
}
return [$offlinequiz, $course, $cm];
}
/**
* Load a {@link question_usage_by_activity} from the database, including
* all its {@link question_attempt}s and all their steps.
* @param int $qubaid the id of the usage to load.
* @param question_usage_by_activity the usage that was loaded.
*/
function offlinequiz_load_questions_usage_by_activity($qubaid) {
global $DB;
$records = $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 = offlinequiz_question_usage_by_activity::load_from_records($records, $qubaid);
$records->close();
return $quba;
}
/**
*
* @param int $offlinequiz
* @param int $groupid
* @return string
*/
function offlinequiz_get_group_question_ids($offlinequiz, $groupid = 0) {
global $DB;
if (!$groupid) {
$groupid = $offlinequiz->groupid;
}
// This query only makes sense if it is restricted to a offline group.
if (!$groupid) {
return '';
}
$sql = "SELECT questionid
FROM {offlinequiz_group_questions}
WHERE offlinequizid = :offlinequizid
AND offlinegroupid = :offlinegroupid
ORDER BY slot ASC ";
$params = array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $groupid);
$questionids = $DB->get_fieldset_sql($sql, $params);
return $questionids;
}
function offlinequiz_get_group_questionbankentry_ids($offlinequiz, $groupid) {
global $DB;
if (!$groupid) {
$groupid = $offlinequiz->groupid;
}
// This query only makes sense if it is restricted to a offline group.
if (!$groupid) {
return '';
}
$sql = "SELECT qv.questionbankentryid
FROM {offlinequiz_group_questions} ogq
JOIN {question_versions} qv ON qv.questionid = ogq.questionid
WHERE offlinequizid = :offlinequizid
AND offlinegroupid = :offlinegroupid
ORDER BY slot ASC ";
$params = array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $groupid);
$questionbankentryids = $DB->get_fieldset_sql($sql, $params);
return $questionbankentryids;
}
/**
*
* @param mixed $offlinequiz The offlinequiz
* @return array returns an array of offline group numbers
*/
function offlinequiz_get_empty_groups($offlinequiz) {
global $DB;
$emptygroups = array();
if ($groups = $DB->get_records('offlinequiz_groups',
array('offlinequizid' => $offlinequiz->id), 'groupnumber', '*', 0, $offlinequiz->numgroups)) {
foreach ($groups as $group) {
$questions = offlinequiz_get_group_question_ids($offlinequiz, $group->id);
if (count($questions) < 1) {
$emptygroups[] = $group->groupnumber;
}
}
}
return $emptygroups;
}
/**
* Get the slot for a question with a particular id.
* @param object $offlinequiz the offlinequiz settings.
* @param int $questionid the of a question in the offlinequiz.
* @return int the corresponding slot. Null if the question is not in the offlinequiz.
*/
function offlinequiz_get_slot_for_question($offlinequiz, $group, $questionid) {
$questionids = offlinequiz_get_group_question_ids($offlinequiz, $group->id);
foreach ($questionids as $key => $id) {
if ($id == $questionid) {
return $key + 1;
}
}
return null;
}
/**
* Verify that the question exists, and the user has permission to use it.
* Does not return. Throws an exception if the question cannot be used.
* @param int $questionid The id of the question.
*/
function offlinequiz_require_question_use($questionid) {
global $DB;
$question = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
question_require_capability_on($question, 'use');
}
/**
* Add a question to a offlinequiz
*
* Adds a question to a offlinequiz by updating $offlinequiz as well as the
* offlinequiz and offlinequiz_slots tables. It also adds a page break if required.
* @param int $questionid The id of the question to be added
* @param object $offlinequiz The extended offlinequiz object as used by edit.php
* This is updated by this function
* @param int $page Which page in offlinequiz to add the question on. If 0 (default),
* add at the end
* @param float $maxmark The maximum mark to set for this question. (Optional,
* defaults to question.defaultmark.
* @return bool false if the question was already in the offlinequiz
*/
function offlinequiz_add_offlinequiz_question($questionid, $offlinequiz, $page = 0, $maxmark = null) {
global $DB;
if (offlinequiz_has_scanned_pages($offlinequiz->id)) {
return false;
}
$slots = $DB->get_records('offlinequiz_group_questions',
array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $offlinequiz->groupid),
'slot', 'questionid, slot, page, id');
if (array_key_exists($questionid, $slots)) {
return false;
}
$trans = $DB->start_delegated_transaction();
$maxpage = 1;
$numonlastpage = 0;
foreach ($slots as $slot) {
if ($slot->page > $maxpage) {
$maxpage = $slot->page;
$numonlastpage = 1;
} else {
$numonlastpage += 1;
}
}
// Add the new question instance.
$slot = new stdClass();
$slot->offlinequizid = $offlinequiz->id;
$slot->offlinegroupid = $offlinequiz->groupid;
$slot->questionid = $questionid;
if ($maxmark !== null) {
$slot->maxmark = $maxmark;
} else {
$slot->maxmark = $DB->get_field('question', 'defaultmark', array('id' => $questionid));
}
if (is_int($page) && $page >= 1) {
// Adding on a given page.
$lastslotbefore = 0;
foreach (array_reverse($slots) as $otherslot) {
if ($otherslot->page > $page) {
// Increase the slot number of the other slot.
$DB->set_field('offlinequiz_group_questions', 'slot', $otherslot->slot + 1, array('id' => $otherslot->id));
} else {
$lastslotbefore = $otherslot->slot;
break;
}
}
$slot->slot = $lastslotbefore + 1;
$slot->page = min($page, $maxpage + 1);
} else {
$lastslot = end($slots);
if ($lastslot) {
$slot->slot = $lastslot->slot + 1;
} else {
$slot->slot = 1;
}
if ($offlinequiz->questionsperpage && $numonlastpage >= $offlinequiz->questionsperpage) {
$slot->page = $maxpage + 1;
} else {
$slot->page = $maxpage;
}
}
$slotid = $DB->insert_record('offlinequiz_group_questions', $slot);
// Update or insert record in question_reference table.
$sql = "SELECT DISTINCT qr.id, qr.itemid
FROM {question} q
JOIN {question_versions} qv ON q.id = qv.questionid
JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
JOIN {question_references} qr ON qbe.id = qr.questionbankentryid AND qr.version = qv.version
JOIN {offlinequiz_group_questions} os ON os.id = qr.itemid
WHERE q.id = ?
AND os.id = ?
AND qr.component = ?
AND qr.questionarea = ?";
$qreferenceitem = $DB->get_record_sql($sql, [$questionid, $slotid, 'mod_offlinequiz', 'slot']);
$version = $DB->get_field('question_versions', 'version', ['questionid' => $questionid]);
if (!$qreferenceitem) {
// Create a new reference record for questions created already.
$questionreferences = new \StdClass();
$questionreferences->usingcontextid = context_module::instance($offlinequiz->cmid)->id;
$questionreferences->component = 'mod_offlinequiz';
$questionreferences->questionarea = 'slot';
$questionreferences->itemid = $slotid;
$questionreferences->questionbankentryid = get_question_bank_entry($questionid)->id;
$questionreferences->version = $version;
$DB->insert_record('question_references', $questionreferences);
} else if ($qreferenceitem->itemid === 0 || $qreferenceitem->itemid === null) {
$questionreferences = new \StdClass();
$questionreferences->id = $qreferenceitem->id;
$questionreferences->itemid = $slotid;
$questionreferences->version = $version;
$DB->update_record('question_references', $questionreferences);
} else {
// If the reference record exits for another quiz.
$questionreferences = new \StdClass();
$questionreferences->usingcontextid = context_module::instance($offlinequiz->cmid)->id;
$questionreferences->component = 'mod_offlinequiz';
$questionreferences->questionarea = 'slot';
$questionreferences->itemid = $slotid;
$questionreferences->questionbankentryid = get_question_bank_entry($questionid)->id;
$questionreferences->version = $version;
$DB->insert_record('question_references', $questionreferences);
}
$trans->allow_commit();
}
/**
* returns the maximum number of questions in a set of offline groups
*
* @param unknown_type $offlinequiz
* @param unknown_type $groups
* @return Ambigous <number, unknown>
*/
function offlinequiz_get_maxquestions($offlinequiz, $groups) {
global $DB;
$maxquestions = 0;
foreach ($groups as $group) {
$questionids = offlinequiz_get_group_question_ids($offlinequiz, $group->id);
list($qsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
$numquestions = $DB->count_records_sql("SELECT COUNT(id) FROM {question} WHERE qtype <> 'description' AND id $qsql",
$params);
if ($numquestions > $maxquestions) {
$maxquestions = $numquestions;
}
}
return $maxquestions;
}
/**
*
* @param unknown_type $scannedpage
* @param unknown_type $corners
*/
function offlinequiz_save_page_corners($scannedpage, $corners) {
global $DB;
$position = 0;
if ($existingcorners = $DB->get_records('offlinequiz_page_corners', array('scannedpageid' => $scannedpage->id), 'position')) {
foreach ($existingcorners as $corner) {
$corner->x = $corners[$position]->x;
$corner->y = $corners[$position++]->y;
$DB->update_record('offlinequiz_page_corners', $corner);
}
} else {
foreach ($corners as $corner) {
unset($corner->blank);
$corner->position = $position++;
$corner->scannedpageid = $scannedpage->id;
$DB->insert_record('offlinequiz_page_corners', $corner);
}
}
}
/**
* returns the maximum number of answers in the group questions of an offlinequiz
* @param unknown_type $offlinequiz
* @return number
*/
function offlinequiz_get_maxanswers($offlinequiz, $groups = array()) {
global $CFG, $DB;
$groupids = array();
foreach ($groups as $group) {
$groupids[] = $group->id;
}
$sql = "SELECT DISTINCT(questionid)
FROM {offlinequiz_group_questions}
WHERE offlinequizid = :offlinequizid
AND questionid > 0";
if (!empty($groupids)) {
list($gsql, $params) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED);
$sql .= " AND offlinegroupid " . $gsql;
} else {
$params = array();
}
$params['offlinequizid'] = $offlinequiz->id;
$questionids = $DB->get_records_sql($sql, $params);
$questionlist = array_keys($questionids);
$counts = array();
if (!empty($questionlist)) {
foreach ($questionlist as $questionid) {
$sql = "SELECT COUNT(id)
FROM {question_answers} qa
WHERE qa.question = :questionid
";
$params = array('questionid' => $questionid);
$counts[] = $DB->count_records_sql($sql, $params);
}
return max($counts);
} else {
return 0;
}
}
/**
* Repaginate the questions in a offlinequiz
* @param int $offlinequizid the id of the offlinequiz to repaginate.
* @param int $slotsperpage number of items to put on each page. 0 means unlimited.
*/
function offlinequiz_repaginate_questions($offlinequizid, $offlinegroupid, $slotsperpage) {
global $DB;
$trans = $DB->start_delegated_transaction();
$slots = $DB->get_records('offlinequiz_group_questions',
array('offlinequizid' => $offlinequizid, 'offlinegroupid' => $offlinegroupid),
'slot');
$currentpage = 1;
$slotsonthispage = 0;
foreach ($slots as $slot) {
if ($slotsonthispage && $slotsonthispage == $slotsperpage) {
$currentpage += 1;
$slotsonthispage = 0;
}
if ($slot->page != $currentpage) {
$DB->set_field('offlinequiz_group_questions', 'page', $currentpage,
array('id' => $slot->id));
}
$slotsonthispage += 1;
}
$trans->allow_commit();
}
/**
* Re-paginates the offlinequiz layout
*
* @return string The new layout string
* @param string $layout The string representing the offlinequiz layout.
* @param integer $perpage The number of questions per page
* @param boolean $shuffle Should the questions be reordered randomly?
*/
function offlinequiz_shuffle_questions($questionids) {
shuffle($questionids);
return $questionids;
}
/**
* returns true if there are scanned pages for an offline quiz.
* @param int $offlinequizid
*/
function offlinequiz_has_scanned_pages($offlinequizid) {
global $CFG, $DB;
$sql = "SELECT COUNT(id)
FROM {offlinequiz_scanned_pages}
WHERE offlinequizid = :offlinequizid";
$params = array('offlinequizid' => $offlinequizid);
return $DB->count_records_sql($sql, $params) > 0;
}
/**
*
* @param unknown_type $page
*/
function offlinequiz_delete_scanned_page($page, $context) {
global $DB;
$resultid = $page->resultid;
$fs = get_file_storage();
// Delete the scanned page.
$DB->delete_records('offlinequiz_scanned_pages', array('id' => $page->id));
// Delete the choices made on the page.
$DB->delete_records('offlinequiz_choices', array('scannedpageid' => $page->id));
// Delete the corner coordinates.
$DB->delete_records('offlinequiz_page_corners', array('scannedpageid' => $page->id));
// If there is no scannedpage for the result anymore, we also delete the result.
if ($resultid && !$DB->get_records('offlinequiz_scanned_pages', array('resultid' => $resultid))) {
// Delete the result.
$DB->delete_records('offlinequiz_results', array('id' => $resultid));
}
// JZ: also delete the image files associated with the deleted page.
if ($page->filename && $file = $fs->get_file($context->id, 'mod_offlinequiz', 'imagefiles', 0, '/', $page->filename)) {
$file->delete();
}
if ($page->warningfilename &&
$file = $fs->get_file($context->id, 'mod_offlinequiz', 'imagefiles', 0, '/', $page->warningfilename)) {
$file->delete();
}
}
/**
*
* @param unknown_type $page
*/
function offlinequiz_delete_scanned_p_page($page, $context) {
global $DB;
$fs = get_file_storage();
// Delete the scanned participants page.
$DB->delete_records('offlinequiz_scanned_p_pages', array('id' => $page->id));
// Delete the choices made on the page.
$DB->delete_records('offlinequiz_p_choices', array('scannedppageid' => $page->id));
// JZ: also delete the image files associated with the deleted page.
if ($page->filename && $file = $fs->get_file($context->id, 'mod_offlinequiz', 'imagefiles', 0, '/', $page->filename)) {
$file->delete();
}
}
/**
* returns the number of completed results for an offline quiz.
* @param int $offlinequizid
* @param int $courseid
* @param boolean $onlystudents
*/
function offlinequiz_completed_results($offlinequizid, $courseid, $onlystudents = false) {
global $CFG, $DB;
if ($onlystudents) {
$coursecontext = context_course::instance($courseid);
$contextids = $coursecontext->get_parent_context_ids(true);
list($csql, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
$params['offlinequizid'] = $offlinequizid;
$select = "SELECT COUNT(DISTINCT(u.id)) as counter
FROM {user} u
JOIN {role_assignments} ra ON ra.userid = u.id
LEFT JOIN {offlinequiz_results} qa
ON u.id = qa.userid
AND qa.offlinequizid = :offlinequizid
AND qa.status = 'complete'
WHERE ra.contextid $csql
AND qa.userid IS NOT NULL
";
return $DB->count_records_sql($select, $params);
} else {
$params = array('offlinequizid' => $offlinequizid);
return $DB->count_records_select('offlinequiz_results', "offlinequizid = :offlinequizid AND status = 'complete'",
$params, 'COUNT(id)');
}
}
/**
* Delete an offlinequiz result, including the questions_usage_by_activity corresponding to it.
*
* @param mixed $attempt an integer attempt id or an attempt object
* (row of the offlinequiz_results table).
* @param object $offlinequiz the offlinequiz object.
*/
function offlinequiz_delete_result($resultid, $context) {
global $DB;
if ($result = $DB->get_record('offlinequiz_results', array('id' => $resultid))) {
// First delete the result itself.
$DB->delete_records('offlinequiz_results', array('id' => $result->id));
// Now we delete all scanned pages that refer to the result.
$scannedpages = $DB->get_records_sql("
SELECT *
FROM {offlinequiz_scanned_pages}
WHERE resultid = :resultid", array('resultid' => $result->id));
foreach ($scannedpages as $page) {
offlinequiz_delete_scanned_page($page, $context);
}
// Finally, delete the question usage that belongs to the result.
if ($result->usageid) {
question_engine::delete_questions_usage_by_activity($result->usageid);
}
}
}
/**
* Save new maxgrade to a question instance
*
* Saves changes to the question grades in the offlinequiz_group_questions table.
* The grades of the questions in the group template qubas are also updated.
* This function does not update 'sumgrades' in the offlinequiz table.
*
* @param stdClass $offlinequiz The offlinequiz to update / add the instances for.
* @param int $questionid The id of the question
* @param int grade The maximal grade for the question
*/
function offlinequiz_update_question_instance($offlinequiz, $contextid, $questionid, $grade, $newquestionid = null) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$DB->set_field('offlinequiz_group_questions', 'maxmark', $grade,
['offlinequizid' => $offlinequiz->id, 'questionid' => $questionid]);
if ($newquestionid) {
$newquestionversion = $DB->get_field('question_versions', 'version', ['questionid' => $newquestionid]);
$groupquestions = $DB->get_records('offlinequiz_group_questions', ['questionid' => $questionid, 'offlinequizid' => $offlinequiz->id], 'id');
$DB->set_field('offlinequiz_group_questions', 'questionid', $newquestionid,
['offlinequizid' => $offlinequiz->id, 'questionid' => $questionid]);
if ($groupquestions && $newquestionversion) {
foreach ($groupquestions as $groupquestion) {
$DB->set_field('question_references', 'version', $newquestionversion, ['itemid' => $groupquestion->id, 'component' => 'mod_offlinequiz', 'usingcontextid' => $contextid]);
if (!$groupquestion->documentquestionid && $offlinequiz->docscreated) {
$DB->set_field('offlinequiz_group_questions', 'documentquestionid', $questionid,
['questionid' => $groupquestion->questionid, 'offlinequizid' => $offlinequiz->id]);
}
}
}
}
if($offlinequiz->docscreated) {
$groups = $DB->get_records('offlinequiz_groups',
['offlinequizid' => $offlinequiz->id], 'groupnumber');
// Now change the maxmark of the question instance in the template question usages of the offlinequiz groups.
foreach ($groups as $group) {
if ($group->templateusageid) {
$templateusage = question_engine::load_questions_usage_by_activity($group->templateusageid);
offlinequiz_update_quba($templateusage, $questionid, $newquestionid, $grade);
}
}
// Now do the same for the qubas of the results of the offline quiz.
if ($results = $DB->get_records('offlinequiz_results', array('offlinequizid' => $offlinequiz->id))) {
foreach ($results as $result) {
if ($result->usageid > 0) {
$templateusage = question_engine::load_questions_usage_by_activity($result->usageid);
$templateusage = offlinequiz_update_quba($templateusage, $questionid, $newquestionid, $grade);
}
}
}
$DB->delete_records('offlinequiz_statistics', ['offlinequizid' => $offlinequiz->id]);
offlinequiz_update_grades($offlinequiz);
} else {
offlinequiz_delete_template_usages($offlinequiz);
}
$DB->commit_delegated_transaction($transaction);
}
function offlinequiz_update_quba(question_usage_by_activity $templateusage, $oldquestionid, $newquestionid, $grade) {
global $DB;
$slots = $templateusage->get_slots();
$slot = 0;
foreach ($slots as $thisslot) {
if ($templateusage->get_question($thisslot)->id == $oldquestionid) {
$slot = $thisslot;
break;
}
}
if ($slot) {
if ($newquestionid) {
$oldquestionanswers = $DB->get_records('question_answers', ['question' => $oldquestionid]);
$newquestionanswers = array_values($DB->get_records('question_answers', ['question' => $newquestionid]));
$sql = "SELECT qasd.id AS id, qasd.value AS value
FROM {question_attempt_step_data} qasd
JOIN {question_attempt_steps} qas ON qas.id = qasd.attemptstepid
JOIN {question_attempts} qa ON qa.id = qas.questionattemptid
WHERE qa.questionusageid = :qubaid
AND qa.questionid = :questionid
AND qasd.name = '_order'";
$value = $DB->get_record_sql($sql, ['qubaid' => $templateusage->get_id(), 'questionid' => $oldquestionid]);
$values = explode(',', $value->value);
$replace = [];
$i = 0;
foreach ($oldquestionanswers as $oldquestionanswer) {
$replace[$oldquestionanswer->id] = $newquestionanswers[$i]->id;
$i++;
}
for ($i = 0; $i < count($values); $i++) {
$values[$i] = $replace[$values[$i]];
}
$values = implode(',', $values);
$DB->set_field('question_attempt_step_data', 'value', $values, ['id' => $value->id]);
$DB->set_field('question_attempts', 'questionid', $newquestionid, ['questionid' => $oldquestionid, 'questionusageid' => $templateusage->get_id()]);
// Update the grade in the template usage.
$templateusage = question_engine::load_questions_usage_by_activity($templateusage->get_id());
}
question_engine::set_max_mark_in_attempts(new qubaid_list([$templateusage->get_id()]), $slot, $grade);
$templateusage->regrade_question($slot, true, $grade);
question_engine::save_questions_usage_by_activity($templateusage);
$templateusage = question_engine::load_questions_usage_by_activity($templateusage->get_id());
$totalmark = $templateusage->get_total_mark();
$DB->set_field('offlinequiz_results', 'sumgrades', $totalmark, ['usageid' => $templateusage->get_id()]);
}
$templateusage = question_engine::load_questions_usage_by_activity($templateusage->get_id());
return $templateusage;
}
/**
* Update the sumgrades field of the results in an offline quiz.
*
* @param object $offlinequiz The offlinequiz.
*/
function offlinequiz_update_all_attempt_sumgrades($offlinequiz) {
global $DB;
$dm = new question_engine_data_mapper();
$timenow = time();
$sql = "UPDATE {offlinequiz_results}
SET timemodified = :timenow,
sumgrades = (
{$dm->sum_usage_marks_subquery('usageid')}
)
WHERE offlinequizid = :offlinequizid
AND timefinish <> 0";
$DB->execute($sql, array('timenow' => $timenow, 'offlinequizid' => $offlinequiz->id));
}
/**
* A {@link qubaid_condition} for finding all the question usages belonging to
* a particular offlinequiz. Used in editlib.php.
*
* @copyright 2010 The University of Vienna
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class result_qubaids_for_offlinequiz extends qubaid_join {
public function __construct($offlinequizid, $offlinegroupid, $includepreviews = true, $onlyfinished = false) {
$where = 'quiza.offlinequizid = :offlinequizid AND quiza.offlinegroupid = :offlinegroupid';
if (!$includepreviews) {
$where .= ' AND preview = 0';
}
if ($onlyfinished) {
$where .= ' AND timefinish <> 0';
}