-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
GatewayQuiz.pm
1508 lines (1286 loc) · 60.2 KB
/
GatewayQuiz.pm
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
################################################################################
# WeBWorK Online Homework Delivery System
# Copyright © 2000-2024 The WeBWorK Project, https://github.com/openwebwork
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of either: (a) the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version, or (b) the "Artistic License" which comes with this package.
#
# This program 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 either the GNU General Public License or the
# Artistic License for more details.
################################################################################
package WeBWorK::ContentGenerator::GatewayQuiz;
use Mojo::Base 'WeBWorK::ContentGenerator', -signatures, -async_await;
=head1 NAME
WeBWorK::ContentGenerator::GatewayQuiz - display a quiz of problems on one page,
deal with versioning sets
=cut
use Mojo::Promise;
use Mojo::JSON qw(encode_json decode_json);
use WeBWorK::Utils qw(encodeAnswers decodeAnswers wwRound);
use WeBWorK::Utils::DateTime qw(before between after);
use WeBWorK::Utils::Files qw(path_is_subdir);
use WeBWorK::Utils::Instructor qw(assignSetVersionToUser);
use WeBWorK::Utils::Logs qw(writeLog writeCourseLog);
use WeBWorK::Utils::ProblemProcessing qw/create_ans_str_from_responses compute_reduced_score/;
use WeBWorK::Utils::Rendering qw(getTranslatorDebuggingOptions renderPG);
use WeBWorK::Utils::Sets qw(is_restricted);
use WeBWorK::DB::Utils qw(global2user fake_set fake_set_version fake_problem);
use WeBWorK::Debug;
use WeBWorK::Authen::LTIAdvanced::SubmitGrade;
use WeBWorK::Authen::LTIAdvantage::SubmitGrade;
use PGrandom;
use Caliper::Sensor;
use Caliper::Entity;
# Disable links for gateway tests.
sub can ($c, $arg) {
return $arg eq 'links' ? 0 : $c->SUPER::can($arg);
}
# "can" methods
# Subroutines to determine if a user "can" perform an action. Each subroutine is
# called with the following arguments:
# ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet)
# In addition can_recordAnswers and can_checkAnswers have the argument $submitAnswers
# that is used to distinguish between this submission and the next.
sub can_showOldAnswers ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
my $authz = $c->authz;
return 0 unless $authz->hasPermissions($user->user_id, 'can_show_old_answers');
return (
before($set->due_date, $c->submitTime)
|| $authz->hasPermissions($user->user_id, 'view_hidden_work')
|| ($set->hide_work eq 'N'
|| ($set->hide_work eq 'BeforeAnswerDate' && after($tmplSet->answer_date, $c->submitTime)))
);
}
sub can_showCorrectAnswers ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
my $authz = $c->authz;
# Allow correct answers to be viewed after all attempts at a version
# are exhausted or if it is after the answer date.
my $attemptsPerVersion = $set->attempts_per_version || 0;
my $attemptsUsed = $problem->num_correct + $problem->num_incorrect + ($c->{submitAnswers} ? 1 : 0);
return (
(
$authz->hasPermissions($user->user_id, 'show_correct_answers_before_answer_date')
|| (
after($set->answer_date, $c->submitTime)
|| ($attemptsUsed >= $attemptsPerVersion
&& $attemptsPerVersion != 0
&& $set->due_date == $set->answer_date)
)
)
&& $c->can_showProblemScores($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet)
);
}
# This version is the same as the above version except that it ignores elevated permisions. So it will be true if this
# set is in the state that anyone can show correct answers regardless of if they have the
# show_correct_answers_before_answer_date or view_hidden_work permissions. In this case, feedback is shown even without
# a form submission, and correct answers are shown in the feedback, if the $pg{options}{automaticAnswerFeedback} option
# is set in the course configuration.
sub can_showCorrectAnswersForAll ($c, $set, $problem, $tmplSet) {
my $attemptsPerVersion = $set->attempts_per_version || 0;
my $attemptsUsed = $problem->num_correct + $problem->num_incorrect + ($c->{submitAnswers} ? 1 : 0);
return (
(
after($set->answer_date, $c->submitTime) || ($attemptsUsed >= $attemptsPerVersion
&& $attemptsPerVersion != 0
&& $set->due_date == $set->answer_date)
)
&& (
(
$set->hide_score eq 'N'
|| ($set->hide_score eq 'BeforeAnswerDate' && after($tmplSet->answer_date, $c->submitTime))
)
&& $set->hide_score_by_problem eq 'N'
)
);
}
sub can_showProblemGrader ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
my $authz = $c->authz;
return ($authz->hasPermissions($user->user_id, 'access_instructor_tools')
&& $authz->hasPermissions($user->user_id, 'problem_grader')
&& $set->set_id ne 'Undefined_Set'
&& !$c->{invalidSet});
}
sub can_showHints ($c) { return 1; }
sub can_showSolutions ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
my $authz = $c->authz;
return 1 if $authz->hasPermissions($user->user_id, 'always_show_solution');
return $c->can_showCorrectAnswers($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet);
}
# Allow for a version_last_attempt_time which is the time the set was submitted. If that is present we use that instead
# of the current time to decide if answers can be recorded. This deals with the time between the submission time and
# the proctor authorization.
sub can_recordAnswers ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet = 0, $submitAnswers = 0) {
my $authz = $c->authz;
# Never record answers for undefined sets
return 0 if $set->set_id eq 'Undefined_Set';
if ($user->user_id ne $effectiveUser->user_id) {
# If the user is not allowed to record answers as another user, return that permission. If the user is allowed
# to record only set version answers, then allow that between the open and close dates, and so drop out of this
# conditional to the usual one.
return 1 if $authz->hasPermissions($user->user_id, 'record_answers_when_acting_as_student');
return 0 if !$authz->hasPermissions($user->user_id, 'record_set_version_answers_when_acting_as_student');
}
my $submitTime =
($set->assignment_type eq 'proctored_gateway' && $set->version_last_attempt_time)
? $set->version_last_attempt_time
: $c->submitTime;
return $authz->hasPermissions($user->user_id, 'record_answers_before_open_date')
if before($set->open_date, $submitTime);
if (between($set->open_date, $set->due_date + $c->ce->{gatewayGracePeriod}, $submitTime)) {
# Look at maximum attempts per version, not for the set, to determine the number of attempts allowed.
my $attemptsPerVersion = $set->attempts_per_version || 0;
my $attemptsUsed = $problem->num_correct + $problem->num_incorrect + ($submitAnswers ? 1 : 0);
if ($attemptsPerVersion == 0 || $attemptsUsed < $attemptsPerVersion) {
return $authz->hasPermissions($user->user_id, 'record_answers_after_open_date_with_attempts');
} else {
return $authz->hasPermissions($user->user_id, 'record_answers_after_open_date_without_attempts');
}
}
return $authz->hasPermissions($user->user_id, 'record_answers_after_due_date')
if between(($set->due_date + $c->ce->{gatewayGracePeriod}), $set->answer_date, $submitTime);
return $authz->hasPermissions($user->user_id, 'record_answers_after_answer_date')
if after($set->answer_date, $submitTime);
return 0;
}
# Allow for a version_last_attempt_time which is the time the set was submitted. If that is present, then use that
# instead of the current time to decide if answers can be checked. This deals with the time between the submission time
# and the proctor authorization.
sub can_checkAnswers ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet, $submitAnswers = 0) {
my $authz = $c->authz;
return 0
if $c->can_recordAnswers($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet, $submitAnswers)
&& !$authz->hasPermissions($user->user_id, 'can_check_and_submit_answers');
my $submitTime =
($set->assignment_type eq 'proctored_gateway' && $set->version_last_attempt_time)
? $set->version_last_attempt_time
: $c->submitTime;
return $authz->hasPermissions($user->user_id, 'check_answers_before_open_date')
if before($set->open_date, $submitTime);
# This is complicated by trying to address hiding scores by problem. If $set->hide_score_by_problem and
# $set->hide_score are both set, then allow scores to be shown, but don't show the score on any individual problem.
# To deal with this, use the least restrictive view of hiding, and then filter for the problems themselves later.
my $canShowProblemScores =
$c->can_showProblemScores($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet);
if (between($set->open_date, $set->due_date + $c->ce->{gatewayGracePeriod}, $submitTime)) {
# Look at maximum attempts per version, not for the set, to determine the number of attempts allowed.
my $attempts_per_version = $set->attempts_per_version || 0;
my $attempts_used = $problem->num_correct + $problem->num_incorrect + ($submitAnswers ? 1 : 0);
if ($attempts_per_version == -1 || $attempts_used < $attempts_per_version) {
return $authz->hasPermissions($user->user_id, 'check_answers_after_open_date_with_attempts')
&& $canShowProblemScores;
} else {
return $authz->hasPermissions($user->user_id, 'check_answers_after_open_date_without_attempts')
&& $canShowProblemScores;
}
}
return $authz->hasPermissions($user->user_id, 'check_answers_after_due_date') && $canShowProblemScores
if between(($set->due_date + $c->ce->{gatewayGracePeriod}), $set->answer_date, $submitTime);
return $authz->hasPermissions($user->user_id, 'check_answers_after_answer_date') && $canShowProblemScores
if after($set->answer_date, $submitTime);
return 0;
}
sub can_showScore ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
return
$c->authz->hasPermissions($user->user_id, 'view_hidden_work')
|| $set->hide_score eq 'N'
|| ($set->hide_score eq 'BeforeAnswerDate' && after($tmplSet->answer_date, $c->submitTime));
}
sub can_showProblemScores ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
return $c->can_showScore($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet)
&& ($set->hide_score_by_problem eq 'N' || $c->authz->hasPermissions($user->user_id, 'view_hidden_work'));
}
sub can_showWork ($c, $user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet) {
return $c->authz->hasPermissions($user->user_id, 'view_hidden_work')
|| ($set->hide_work eq 'N'
|| ($set->hide_work eq 'BeforeAnswerDate' && $c->submitTime > $tmplSet->answer_date));
}
sub can_useMathView ($c) {
return $c->ce->{pg}{specialPGEnvironmentVars}{entryAssist} eq 'MathView';
}
sub can_useMathQuill ($c) {
return $c->ce->{pg}{specialPGEnvironmentVars}{entryAssist} eq 'MathQuill';
}
# Output utility
sub attemptResults ($c, $pg) {
return ($c->{can}{showProblemScores} && $pg->{result}{summary})
? $c->tag('div', role => 'alert', $c->b($pg->{result}{summary}))
: '';
}
sub get_instructor_comment ($c, $problem) {
return unless ref($problem) =~ /ProblemVersion/;
my $db = $c->db;
my $userPastAnswerID =
$db->latestProblemPastAnswer($problem->user_id, $problem->set_id . ',v' . $problem->version_id,
$problem->problem_id);
if ($userPastAnswerID) {
my $userPastAnswer = $db->getPastAnswer($userPastAnswerID);
return $userPastAnswer->comment_string;
}
return '';
}
# Template methods
async sub pre_header_initialize ($c) {
# Make sure these are defined for the templates.
$c->stash->{problems} = [];
$c->stash->{pg_results} = [];
$c->stash->{startProb} = 0;
$c->stash->{endProb} = 0;
$c->stash->{numPages} = 0;
$c->stash->{pageNumber} = 0;
$c->stash->{problem_numbers} = [];
$c->stash->{probOrder} = [];
# If authz->checkSet has failed, then this set is invalid. No need to proceeded.
return if $c->{invalidSet};
my $ce = $c->ce;
my $db = $c->db;
my $authz = $c->authz;
my $setID = $c->stash('setID');
my $userID = $c->param('user');
my $effectiveUserID = $c->param('effectiveUser');
my $isFakeSet = 0;
# User checks
my $user = $db->getUser($userID);
die "record for user $userID (real user) does not exist." unless defined $user;
my $effectiveUser = $db->getUser($effectiveUserID);
die "record for user $effectiveUserID (effective user) does not exist." unless defined $effectiveUser;
my $permissionLevel = $db->getPermissionLevel($userID);
die "permission level record for $userID does not exist (but the user does? odd...)"
unless defined $permissionLevel;
# The $setID could be the versioned or nonversioned set. Extract the version if it is provided.
my $requestedVersion = ($setID =~ /,v(\d+)$/) ? $1 : 0;
$setID =~ s/,v\d+$//;
# Note that if a version was provided the version needs to be checked. That is done after it has
# been validated that the user is assigned the set.
# Gateway set and problem collection
# We need the template (user) set, the merged set version, and a problem from the set to be able to test whether
# we're creating a new set version.
my ($tmplSet, $set, $problem) = (0, 0, 0);
# If the set comes in as "Undefined_Set", then we're trying/editing a single problem in a set, and so create a fake
# set with which to work if the user has the authorization to do that.
if ($setID eq 'Undefined_Set') {
$isFakeSet = 1;
# Make sure these are defined
$requestedVersion = 1;
$c->{assignment_type} = 'gateway';
if (!$authz->hasPermissions($userID, 'modify_problem_sets')) {
$c->{invalidSet} = 'You do not have the authorization level required to view/edit undefined sets.';
# Define these so that we can drop through to report the error in body.
$tmplSet = fake_set($db);
$set = fake_set_version($db);
$problem = fake_problem($db);
} else {
# In this case we're creating a fake set from the input, so the input must include a source file.
if (!$c->param('sourceFilePath')) {
$c->{invalidSet} =
'An Undefined_Set was requested, but no source file for the contained problem was provided.';
# Define these so that we can drop through to report the error in body.
$tmplSet = fake_set($db);
$set = fake_set_version($db);
$problem = fake_problem($db);
} else {
my $sourceFPath = $c->param('sourceFilePath');
die('sourceFilePath is unsafe!')
unless path_is_subdir($sourceFPath, $ce->{courseDirs}{templates}, 1);
$tmplSet = fake_set($db);
$set = fake_set_version($db);
$problem = fake_problem($db);
my $creation_time = time;
$tmplSet->assignment_type('gateway');
$tmplSet->attempts_per_version(0);
$tmplSet->time_interval(0);
$tmplSet->versions_per_interval(1);
$tmplSet->version_time_limit(0);
$tmplSet->version_creation_time($creation_time);
$tmplSet->problem_randorder(0);
$tmplSet->problems_per_page(1);
$tmplSet->hide_score('N');
$tmplSet->hide_score_by_problem('N');
$tmplSet->hide_work('N');
$tmplSet->time_limit_cap('0');
$tmplSet->restrict_ip('No');
$set->assignment_type('gateway');
$set->time_interval(0);
$set->versions_per_interval(1);
$set->version_time_limit(0);
$set->version_creation_time($creation_time);
$set->time_limit_cap('0');
$problem->problem_id(1);
$problem->source_file($sourceFPath);
$problem->user_id($effectiveUserID);
$problem->value(1);
$problem->problem_seed($c->param('problemSeed')) if ($c->param('problemSeed'));
}
}
} else {
# Get the template set, i.e., the non-versioned set that's assigned to the user.
# If this failed in authz->checkSet, then $c->{invalidSet} is set.
$tmplSet = $db->getMergedSet($effectiveUserID, $setID);
# Now that is has been validated that this is a gateway test, save the assignment test for the processing of
# graded proctored tests. If a set was not obtained from the database, store a fake value here
# to be able to continue.
$c->{assignment_type} = $tmplSet->assignment_type || 'gateway';
# next, get the latest (current) version of the set if we don't have a
# requested version number
my @allVersionIds = $db->listSetVersions($effectiveUserID, $setID);
my $latestVersion = (@allVersionIds ? $allVersionIds[-1] : 0);
# Double check that the requested version makes sense.
$requestedVersion = $latestVersion
if ($requestedVersion !~ /^\d+$/
|| $requestedVersion > $latestVersion
|| $requestedVersion < 0);
die('No requested version when returning to problem?!')
if (
(
$c->param('previewAnswers')
|| $c->param('checkAnswers')
|| $c->param('submitAnswers')
|| $c->param('newPage')
)
&& !$requestedVersion
);
# To check for a proctored test, the set version is needed, not the template. So get that.
if ($requestedVersion) {
$set = $db->getMergedSetVersion($effectiveUserID, $setID, $requestedVersion);
} elsif ($latestVersion) {
$set = $db->getMergedSetVersion($effectiveUserID, $setID, $latestVersion);
} else {
# If there is not a requested version or a latest version, then create dummy set to proceed.
# FIXME RETURN TO: should this be global2version?
$set = global2user($ce->{dbLayout}{set_version}{record}, $db->getGlobalSet($setID));
$set->user_id($effectiveUserID);
$set->psvn('000');
$set->set_id($setID); # redundant?
$set->version_id(0);
}
}
my $setVersionNumber = $set ? $set->version_id : 0;
# Assemble gateway parameters
# We get the open and close dates for the gateway from the template set, or from the merged set version if a set has
# been requested. Note $isOpen and $isClosed give the open and close dates for the gateway as a whole (that is, the
# merged user|global set). The set could be an invalid set, so check for an open_date before actually testing the
# date. If a specific version has not been requested and conditional release is enabled, then this also checks to
# see if the conditions have been met for a conditional release.
my $isOpen = (
$requestedVersion ? ($set && $set->open_date && after($set->open_date, $c->submitTime)) : ($tmplSet
&& $tmplSet->open_date
&& after($tmplSet->open_date, $c->submitTime)
&& !($ce->{options}{enableConditionalRelease} && is_restricted($db, $tmplSet, $effectiveUserID)))
)
|| $authz->hasPermissions($userID, 'view_unopened_sets');
my $isClosed =
$tmplSet
&& $tmplSet->due_date
&& after($tmplSet->due_date, $c->submitTime)
&& !$authz->hasPermissions($userID, 'record_answers_after_due_date');
# To determine if we need a new version, we need to know whether this version exceeds the number of attempts per
# version. Among other things, the number of attempts is a property of the problem, so get a problem to check that.
# Note that for a gateway quiz all problems will have the same number of attempts. This means that if the set
# doesn't have any problems we're up a creek, so check for that here and bail if that is the case.
my @setPNum = $setID eq 'Undefined_Set' ? (1) : $db->listUserProblems($effectiveUser->user_id, $setID);
die("Set $setID contains no problems.") if (!@setPNum);
# If we assigned a fake problem above, $problem is already defined. Otherwise, get the problem, or define it to be
# undefined if the set hasn't been versioned to the user yet. This is fixed when we assign the setVersion.
if (!$problem) {
$problem =
$setVersionNumber
? $db->getMergedProblemVersion($effectiveUser->user_id, $setID, $setVersionNumber, $setPNum[0])
: undef;
}
my $maxAttemptsPerVersion = $tmplSet->attempts_per_version || 0;
my $timeInterval = $tmplSet->time_interval || 0;
my $versionsPerInterval = $tmplSet->versions_per_interval || 0;
my $timeLimit = $tmplSet->version_time_limit || 0;
# What happens if someone didn't set one of these? Perhaps this can happen if we're handed a malformed set, where
# the values in the database are null.
$timeInterval = 0 if !defined $timeInterval || $timeInterval eq '';
$versionsPerInterval = 0 if !defined $versionsPerInterval || $versionsPerInterval eq '';
# Every problem in the set is assumed have the same submission characteristics.
my $currentNumAttempts = defined $problem ? $problem->num_correct + $problem->num_incorrect : 0;
# $maxAttempts is the maximum number of versions that can be created.
# If the problem isn't defined it doesn't matter.
my $maxAttempts = defined $problem && $problem->max_attempts ? $problem->max_attempts : -1;
# Find the number of versions per time interval. Interpret the time interval as a rolling interval. That is, if two
# sets are allowed per day, that is two sets in any 24 hour period.
my $currentNumVersions = 0; # this is the number of versions in the time interval
my $totalNumVersions = 0;
if ($setVersionNumber && !$c->{invalidSet} && $setID ne 'Undefined_Set') {
my @setVersionIDs = $db->listSetVersions($effectiveUserID, $setID);
my @setVersions = $db->getSetVersions(map { [ $effectiveUserID, $setID,, $_ ] } @setVersionIDs);
for (@setVersions) {
$totalNumVersions++;
$currentNumVersions++
if (!$timeInterval || $_->version_creation_time() > ($c->submitTime - $timeInterval));
}
}
# New version creation conditional
my $versionIsOpen = 0;
if ($isOpen && !$isClosed && !$c->{invalidSet}) {
# If specific version was not requested, then create a new one if needed.
if (!$requestedVersion) {
if (
($maxAttempts == -1 || $totalNumVersions < $maxAttempts)
&& (
$setVersionNumber == 0
|| (
(
($maxAttemptsPerVersion == 0 && $currentNumAttempts > 0)
|| ($maxAttemptsPerVersion != 0 && $currentNumAttempts >= $maxAttemptsPerVersion)
|| $c->submitTime >= $set->due_date + $ce->{gatewayGracePeriod}
)
&& (!$versionsPerInterval || $currentNumVersions < $versionsPerInterval)
)
)
&& (
$effectiveUserID eq $userID
|| (
$authz->hasPermissions($userID, 'record_answers_when_acting_as_student')
|| ($authz->hasPermissions($userID, 'create_new_set_version_when_acting_as_student')
&& $c->param('createnew_ok'))
)
)
)
{
# Assign the set, get the right name, version number, etc., and redefine the $set and $problem for the
# remainder of this method.
my $setTmpl = $db->getUserSet($effectiveUserID, $setID);
assignSetVersionToUser($db, $effectiveUserID, $setTmpl);
$setVersionNumber++;
# Get a clean version of the set and merged version to use in the rest of the routine.
my $cleanSet = $db->getSetVersion($effectiveUserID, $setID, $setVersionNumber);
$set = $db->getMergedSetVersion($effectiveUserID, $setID, $setVersionNumber);
$set->visible(1);
$problem = $db->getMergedProblemVersion($effectiveUserID, $setID, $setVersionNumber, $setPNum[0]);
# Convert the floating point value from Time::HiRes to an integer for use below. Truncate towards 0.
my $timeNowInt = int($c->submitTime);
# Set up creation time, and open and due dates.
my $ansOffset = $set->answer_date - $set->due_date;
$set->version_creation_time($timeNowInt);
$set->open_date($timeNowInt);
# Figure out the due date, taking into account the time limit cap.
my $dueTime =
$timeLimit == 0 || ($set->time_limit_cap && $c->submitTime + $timeLimit > $set->due_date)
? $set->due_date
: $timeNowInt + $timeLimit;
$set->due_date($dueTime);
$set->answer_date($set->due_date + $ansOffset);
$set->version_last_attempt_time(0);
# Put this new info into the database. Put back the data needed for the version, and leave blank any
# information that should be inherited from the user set or global set. Set the data which determines
# if a set is open, because a set version should not reopen after it's complete.
$cleanSet->version_creation_time($set->version_creation_time);
$cleanSet->open_date($set->open_date);
$cleanSet->due_date($set->due_date);
$cleanSet->answer_date($set->answer_date);
$cleanSet->version_last_attempt_time($set->version_last_attempt_time);
$cleanSet->version_time_limit($set->version_time_limit);
$cleanSet->attempts_per_version($set->attempts_per_version);
$cleanSet->assignment_type($set->assignment_type);
$db->putSetVersion($cleanSet);
# This is a new set version, so it's open.
$versionIsOpen = 1;
# Set the number of attempts for this set to zero.
$currentNumAttempts = 0;
} elsif ($maxAttempts != -1 && $totalNumVersions > $maxAttempts) {
$c->{invalidSet} = 'No new versions of this assignment are available, '
. 'because you have already taken the maximum number allowed.';
} elsif ($effectiveUserID ne $userID
&& $authz->hasPermissions($userID, 'create_new_set_version_when_acting_as_student'))
{
$c->{invalidSet} =
"User $effectiveUserID is being acted "
. 'as. If you continue, you will create a new version of this set '
. 'for that user, which will count against their allowed maximum '
. 'number of versions for the current time interval. IN GENERAL, THIS '
. 'IS NOT WHAT YOU WANT TO DO. Please be sure that you want to '
. 'do this before clicking the "Create new set version" link '
. 'below. Alternately, PRESS THE "BACK" BUTTON and continue.';
$c->{invalidVersionCreation} = 1;
} elsif ($effectiveUserID ne $userID) {
$c->{invalidSet} = "User $effectiveUserID is being acted as. "
. 'When acting as another user, new versions of the set cannot be created.';
$c->{invalidVersionCreation} = 2;
} elsif (($maxAttemptsPerVersion == 0 || $currentNumAttempts < $maxAttemptsPerVersion)
&& $c->submitTime < $set->due_date() + $ce->{gatewayGracePeriod})
{
if (between($set->open_date(), $set->due_date() + $ce->{gatewayGracePeriod}, $c->submitTime)) {
$versionIsOpen = 1;
} else {
$c->{invalidSet} =
'No new versions of this assignment are available, because the set is not open or its time'
. ' limit has expired.';
}
} elsif ($versionsPerInterval
&& ($currentNumVersions >= $versionsPerInterval))
{
$c->{invalidSet} =
'You have already taken all available versions of this test in the current time interval. '
. 'You may take the test again after the time interval has expired.';
}
} else {
# If a specific version is requested, then check to see if it's open.
if (
($currentNumAttempts < $maxAttemptsPerVersion)
&& ($effectiveUserID eq $userID
|| $authz->hasPermissions($userID, 'record_set_version_answers_when_acting_as_student'))
)
{
if (between($set->open_date(), $set->due_date() + $ce->{gatewayGracePeriod}, $c->submitTime)) {
$versionIsOpen = 1;
}
}
}
} elsif (!$c->{invalidSet} && !$requestedVersion) {
$c->{invalidSet} = 'This set is closed. No new set versions may be taken.';
}
# If the proctor session key does not have a set version id, then add it. This occurs when a student
# initially enters a proctored test, since the version id is not determined until just above.
if ($c->authen->session('proctor_authorization_granted')
&& $c->authen->session('proctor_authorization_granted') !~ /,v\d+$/)
{
if ($setVersionNumber) { $c->authen->session(proctor_authorization_granted => "$setID,v$setVersionNumber"); }
else { delete $c->authen->session->{proctor_authorization_granted}; }
}
# If the set or problem is invalid, then delete any proctor session keys and return.
if ($c->{invalidSet} || $c->{invalidProblem}) {
if (defined $c->{assignment_type} && $c->{assignment_type} eq 'proctored_gateway') {
delete $c->authen->session->{proctor_authorization_granted};
}
return;
}
# Save problem and user data
my $psvn = $set->psvn();
$c->{tmplSet} = $tmplSet;
$c->{set} = $set;
$c->{problem} = $problem;
$c->{userID} = $userID;
$c->{user} = $user;
$c->{effectiveUser} = $effectiveUser;
$c->{isOpen} = $isOpen;
$c->{isClosed} = $isClosed;
$c->{versionIsOpen} = $versionIsOpen;
# Form processing
# Get the current page, if it's given.
my $currentPage = $c->param('currentPage') || 1;
# This is a hack to manage changing pages. Set previewAnswers to
# false if the "pageChangeHack" input is set (a page change link was used).
$c->param('previewAnswers', 0) if $c->param('pageChangeHack');
$c->{displayMode} = $user->displayMode || $ce->{pg}{options}{displayMode};
# Set options from request parameters.
$c->{redisplay} = $c->param('redisplay');
$c->{submitAnswers} = $c->param('submitAnswers') || 0;
$c->{checkAnswers} = $c->param('checkAnswers') // 0;
$c->{previewAnswers} = $c->param('previewAnswers') // 0;
$c->{formFields} = $c->req->params->to_hash;
# Permissions
# Bail without doing anything if the set isn't yet open for this user.
if (!($c->{isOpen} || $authz->hasPermissions($userID, 'view_unopened_sets'))) {
$c->{invalidSet} = 'This set is not yet open.';
return;
}
# Unset the showProblemGrader parameter if the "Hide Problem Grader" button was clicked.
$c->param(showProblemGrader => undef) if $c->param('hideProblemGrader');
# What does the user want to do?
my %want = (
showOldAnswers => $user->showOldAnswers ne '' ? $user->showOldAnswers : $ce->{pg}{options}{showOldAnswers},
showCorrectAnswers => 1,
showProblemGrader => $c->param('showProblemGrader') || 0,
showHints => 0, # Hints are not yet implemented in gateway quzzes.
showSolutions => 1,
recordAnswers => $c->{submitAnswers} && !$authz->hasPermissions($userID, 'avoid_recording_answers'),
checkAnswers => $c->{checkAnswers},
useMathView => $user->useMathView ne '' ? $user->useMathView : $ce->{pg}{options}{useMathView},
useMathQuill => $user->useMathQuill ne '' ? $user->useMathQuill : $ce->{pg}{options}{useMathQuill},
);
# Does the user have permission to use certain options?
my @args = ($user, $permissionLevel, $effectiveUser, $set, $problem, $tmplSet);
my %can = (
showOldAnswers => $c->can_showOldAnswers(@args),
showCorrectAnswers => $c->can_showCorrectAnswers(@args),
showProblemGrader => $c->can_showProblemGrader(@args),
showHints => $c->can_showHints,
showSolutions => $c->can_showSolutions(@args),
recordAnswers => $c->can_recordAnswers(@args),
checkAnswers => $c->can_checkAnswers(@args),
recordAnswersNextTime => $c->can_recordAnswers(@args, $c->{submitAnswers}),
checkAnswersNextTime => $c->can_checkAnswers(@args, $c->{submitAnswers}),
showScore => $c->can_showScore(@args),
showProblemScores => $c->can_showProblemScores(@args),
showWork => $c->can_showWork(@args),
useMathView => $c->can_useMathView,
useMathQuill => $c->can_useMathQuill
);
# Final values for options
my %will = map { $_ => $can{$_} && $want{$_} } keys %can;
$c->{want} = \%want;
$c->{can} = \%can;
$c->{will} = \%will;
# Set up problem numbering and multipage variables.
my @problemNumbers;
if ($setID eq 'Undefined_Set') {
@problemNumbers = (1);
} else {
@problemNumbers = $db->listProblemVersions($effectiveUserID, $setID, $setVersionNumber);
}
# To speed up processing of long (multi-page) tests, we want to only translate those problems that are being
# submitted or are currently being displayed. So determine which problems are on the current page.
my ($numPages, $pageNumber, $numProbPerPage) = (1, 0, 0);
my ($startProb, $endProb) = (0, $#problemNumbers);
# Update startProb and endProb for multipage tests
if ($set->problems_per_page) {
$numProbPerPage = $set->problems_per_page;
$pageNumber = $c->param('newPage') || $currentPage;
$numPages = scalar(@problemNumbers) / $numProbPerPage;
$numPages = int($numPages) + 1 if (int($numPages) != $numPages);
$startProb = ($pageNumber - 1) * $numProbPerPage;
$startProb = 0 if ($startProb < 0 || $startProb > $#problemNumbers);
$endProb =
($startProb + $numProbPerPage > $#problemNumbers) ? $#problemNumbers : $startProb + $numProbPerPage - 1;
}
# Set up problem list for randomly ordered tests.
my @probOrder = (0 .. $#problemNumbers);
if ($set->problem_randorder) {
my @newOrder;
# Make sure to keep the random order the same each time the set is loaded! This is done by ensuring that the
# random seed used is the same each time the same set is called by setting the seed to the psvn of the problem
# set. Use a local PGrandom object to avoid mucking with the system seed.
my $pgrand = PGrandom->new;
$pgrand->srand($set->psvn);
while (@probOrder) {
my $i = int($pgrand->rand(scalar(@probOrder)));
push(@newOrder, splice(@probOrder, $i, 1));
}
@probOrder = @newOrder;
}
# Now $probOrder[i] is the problem number, numbered from zero, that is displayed in the ith position on the test.
# Make a list of those problems displayed on this page.
my @probsToDisplay = ();
for (my $i = 0; $i < @probOrder; $i++) {
push(@probsToDisplay, $probOrder[$i])
if ($i >= $startProb && $i <= $endProb);
}
# Process problems
my @problems;
my @pg_results;
# pg errors are stored here.
$c->{errors} = [];
# Process the problems as needed.
my @mergedProblems;
if ($setID eq 'Undefined_Set') {
@mergedProblems = ($problem);
} else {
@mergedProblems = $db->getAllMergedProblemVersions($effectiveUserID, $setID, $setVersionNumber);
}
my @renderPromises;
for my $pIndex (0 .. $#problemNumbers) {
my $problemN = $mergedProblems[$pIndex];
if (!defined $problemN) {
$c->{invalidSet} = 'One or more of the problems in this set have not been assigned to you.';
return;
}
# sticky answers are set up here
if (!($c->{submitAnswers} || $c->{previewAnswers} || $c->{checkAnswers} || $c->param('newPage'))
&& $will{showOldAnswers})
{
my %oldAnswers = decodeAnswers($problemN->last_answer);
$c->{formFields}{$_} = $oldAnswers{$_} for (keys %oldAnswers);
}
push(@problems, $problemN);
# If this problem DOES NOT need to be translated, store a defined but false placeholder in the array.
my $pg = 0;
# This is the actual translation of each problem.
if ((grep {/^$pIndex$/} @probsToDisplay) || $c->{submitAnswers}) {
push @renderPromises, $c->getProblemHTML($c->{effectiveUser}, $set, $c->{formFields}, $problemN);
# If this problem DOES need to be translated, store an undefined placeholder in the array.
# This will be replaced with the rendered problem after all of the above promises are awaited.
$pg = undef;
}
push(@pg_results, $pg);
}
# Show the template problem ID if the problems are in random order
# or the template problem IDs are not in order starting at 1.
$c->{can}{showTemplateIds} = $c->{can}{showProblemGrader}
&& ($set->problem_randorder || $problems[-1]->problem_id != scalar(@problems));
# Wait for all problems to be rendered and replace the undefined entries
# in the pg_results array with the rendered result.
my @renderedPG = await Mojo::Promise->all(@renderPromises);
for (@pg_results) {
$_ = (shift @renderedPG)->[0] if !defined $_;
}
$c->stash->{problems} = \@problems;
$c->stash->{pg_results} = \@pg_results;
$c->stash->{startProb} = $startProb;
$c->stash->{endProb} = $endProb;
$c->stash->{numPages} = $numPages;
$c->stash->{pageNumber} = $pageNumber;
$c->stash->{problem_numbers} = \@problemNumbers;
$c->stash->{probOrder} = \@probOrder;
my $versionID = $set->version_id;
my $setVName = "$setID,v$versionID";
# Report everything with the request submit time. Convert the floating point
# value from Time::HiRes to an integer for use below. Truncate towards 0.
my $timeNowInt = int($c->submitTime);
# Answer processing
debug('begin answer processing');
my @scoreRecordedMessage = ('') x scalar(@problems);
my $LTIGradeResult = -1;
# Save results to database as appropriate
if ($c->{submitAnswers} || (($c->{previewAnswers} || $c->param('newPage')) && $can{recordAnswers})) {
# If answers are being submitted, then save the problems to the database. If this is a preview or page change
# and answers can be recorded, then save the last answer for future reference.
# Also save the persistent data to the database even when the last answer is not saved.
# Deal with answers being submitted for a proctored exam. If there are no attempts left, then delete the
# proctor session key so that it isn't possible to start another proctored test without being reauthorized.
delete $c->authen->session->{proctor_authorization_granted}
if ($c->{submitAnswers}
&& $c->{assignment_type} eq 'proctored_gateway'
&& $set->attempts_per_version > 0
&& $set->attempts_per_version - 1 - $problem->num_correct - $problem->num_incorrect <= 0);
my @pureProblems = $db->getAllProblemVersions($effectiveUserID, $setID, $versionID);
for my $i (0 .. $#problems) {
# Process each problem.
my $pureProblem = $pureProblems[ $probOrder[$i] ];
my $problem = $problems[ $probOrder[$i] ];
my $pg_result = $pg_results[ $probOrder[$i] ];
my %answerHash;
my @answer_order;
my ($encoded_last_answer_string, $answer_types_string);
if (ref $pg_result) {
my ($past_answers_string, $scores); # Not used here
($past_answers_string, $encoded_last_answer_string, $scores, $answer_types_string) =
create_ans_str_from_responses($c->{formFields}, $pg_result,
$pureProblem->flags =~ /:needs_grading/);
# Transfer persistent problem data from the PERSISTENCE_HASH:
# - Get keys to update first, to avoid extra work when no updated ar
# are needed. When none, we avoid the need to decode/encode JSON,
# to save the pureProblem when it would not otherwise be saved.
# - We are assuming that there is no need to DELETE old
# persistent data if the hash is empty, even if in
# potential there may be some data already in the database.
my @persistent_data_keys = keys %{ $pg_result->{PERSISTENCE_HASH_UPDATED} };
if (@persistent_data_keys) {
my $json_data = decode_json($pureProblem->{problem_data} || '{}');
for my $key (@persistent_data_keys) {
$json_data->{$key} = $pg_result->{PERSISTENCE_HASH}{$key};
}
$pureProblem->problem_data(encode_json($json_data));
# If the pureProblem will not be saved below, we should save the
# persistent data here before any other changes are made to it.
if (($c->{submitAnswers} && !$will{recordAnswers})) {
$c->db->putProblemVersion($pureProblem);
}
}
} else {
my $prefix = sprintf('Q%04d_', $problemNumbers[$i]);
my @fields = sort grep {/^(?!previous).*$prefix/} (keys %{ $c->{formFields} });
my %answersToStore = map { $_ => $c->{formFields}->{$_} } @fields;
my @answer_order = @fields;
$encoded_last_answer_string = encodeAnswers(\%answersToStore, \@answer_order);
}
# Set the last answer
$problem->last_answer($encoded_last_answer_string);
$pureProblem->last_answer($encoded_last_answer_string);
# Store the state in the database if answers are being recorded.
if ($c->{submitAnswers} && $will{recordAnswers}) {
my $score =
compute_reduced_score($ce, $problem, $set, $pg_result->{state}{recorded_score}, $c->submitTime);
$problem->status($score) if $score > $problem->status;
$problem->sub_status($problem->status)
if (!$ce->{pg}{ansEvalDefaults}{enableReducedScoring}
|| !$set->enable_reduced_scoring
|| before($set->reduced_scoring_date, $c->submitTime));
$problem->attempted(1);
$problem->num_correct($pg_result->{state}{num_of_correct_ans});
$problem->num_incorrect($pg_result->{state}{num_of_incorrect_ans});
$pureProblem->status($problem->status);
$pureProblem->sub_status($problem->sub_status);
$pureProblem->attempted(1);
$pureProblem->num_correct($pg_result->{state}{num_of_correct_ans});
$pureProblem->num_incorrect($pg_result->{state}{num_of_incorrect_ans});
# Add flags which are really a comma separated list of answer types.
$pureProblem->flags($answer_types_string);
if ($db->putProblemVersion($pureProblem)) {
# Use a simple untranslated value here. This message will never be shown, and will later be
# used in a string comparison. Don't compare translated strings!
$scoreRecordedMessage[ $probOrder[$i] ] = 'recorded';
} else {
$scoreRecordedMessage[ $probOrder[$i] ] = $c->maketext('Your score was not recorded because '
. 'there was a failure in storing the problem record to the database.');
}
# Write the transaction log
writeLog($c->ce, 'transaction',
$problem->problem_id . "\t"
. $problem->set_id . "\t"
. $problem->user_id . "\t"
. $problem->source_file . "\t"
. $problem->value . "\t"
. $problem->max_attempts . "\t"
. $problem->problem_seed . "\t"
. $problem->status . "\t"
. $problem->attempted . "\t"
. $problem->last_answer . "\t"
. $problem->num_correct . "\t"
. $problem->num_incorrect);
} elsif ($c->{submitAnswers}) {
# This is the case answers were submitted but can not be saved. Report an error message.
if ($c->{isClosed}) {
$scoreRecordedMessage[ $probOrder[$i] ] =
$c->maketext('Your score was not recorded because this problem set version is not open.');