forked from xcompass/webwork2
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGatewayQuiz.pm
2586 lines (2249 loc) · 99.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-2018 The WeBWorK Project, http://openwebwork.sf.net/
# $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/GatewayQuiz.pm,v 1.54 2008/07/01 13:12:56 glarose Exp $
#
# 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 base qw(WeBWorK::ContentGenerator);
=head1 NAME
WeBWorK::ContentGenerator::GatewayQuiz - display a quiz of problems on one page,
deal with versioning sets
=cut
use strict;
use warnings;
use WeBWorK::CGI;
use File::Path qw(rmtree);
use WeBWorK::Form;
use WeBWorK::PG;
use WeBWorK::PG::ImageGenerator;
use WeBWorK::PG::IO;
use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers
ref2string makeTempDirectory path_is_subdir sortByName before after
between wwRound is_restricted); # use the ContentGenerator formatDateTime, not the version in Utils
use WeBWorK::DB::Utils qw(global2user user2global);
use WeBWorK::Utils::Tasks qw(fake_set fake_set_version fake_problem);
use WeBWorK::Debug;
use WeBWorK::ContentGenerator::Instructor qw(assignSetVersionToUser);
use WeBWorK::Authen::LTIAdvanced::SubmitGrade;
use LTIAdvantage::Service::AssignmentAndGradeService;
use DelayedJob::Service;
use WeBWorK::Utils::AttemptsTable;
use WeBWorK::ContentGenerator::Instructor::SingleProblemGrader;
use PGrandom;
use Caliper::Sensor;
use Caliper::Entity;
# template method
sub templateName {
return "gateway";
}
################################################################################
# "can" methods
################################################################################
# Subroutines to determine if a user "can" perform an action. Each subroutine is
# called with the following arguments:
#
# ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem)
# *** The "can" routines are taken from Problem.pm, with small modifications
# *** to look at number of attempts per version, not per set, and to allow
# *** showing of correct answers after all attempts at a version are used
sub can_showOldAnswers {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem, $tmplSet) = @_;
my $authz = $self->r->authz;
# we'd like to use "! $Set->hide_work()", but that hides students' work
# as they're working on the set, which isn't quite right. so use instead:
return 0 unless $authz->hasPermissions($User->user_id,"can_show_old_answers");
return (before($Set->due_date()) ||
$authz->hasPermissions($User->user_id,"view_hidden_work") ||
($Set->hide_work() eq 'N' ||
($Set->hide_work() eq 'BeforeAnswerDate' && time > $tmplSet->answer_date)));
}
# gateway change here: add $submitAnswers as an optional additional argument
# to be included if it's defined
sub can_showCorrectAnswers {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem,
$tmplSet, $submitAnswers) = @_;
my $authz = $self->r->authz;
# gateway change here to allow correct answers to be viewed after all attempts
# at a version are exhausted as well as if it's after the answer date
# $addOne allows us to count the current submission
my $addOne = defined($submitAnswers) ? $submitAnswers : 0;
my $maxAttempts = $Set->attempts_per_version() || 0;
my $attemptsUsed = $Problem->num_correct + $Problem->num_incorrect + $addOne || 0;
# this is complicated by trying to address hiding scores by problem---that
# is, if $set->hide_score_by_problem and $set->hide_score are both set,
# then we should allow scores to be shown, but not show the score on
# any individual problem. to deal with this, we make
# can_showCorrectAnswers give the least restrictive view of hiding, and
# then filter scores for the problems themselves later
# showing correcrt answers but not showing scores doesn't make sense
# so we should hide the correct answers if we aren not showing
# scores GG.
my $canShowScores = $Set->hide_score_by_problem eq 'N' &&
($Set->hide_score eq 'N' ||
($Set->hide_score eq 'BeforeAnswerDate' && after($tmplSet->answer_date)));
return (((after($Set->answer_date) ||
($attemptsUsed >= $maxAttempts && $maxAttempts != 0 &&
$Set->due_date() == $Set->answer_date())) ||
$authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")) &&
($authz->hasPermissions($User->user_id, "view_hidden_work") || $canShowScores));
}
sub can_showProblemGrader {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
my $authz = $self->r->authz;
return ($authz->hasPermissions($User->user_id, "access_instructor_tools") &&
$authz->hasPermissions($User->user_id, "score_sets") &&
$Set->set_id ne "Undefined_Set" && !$self->{invalidSet});
}
sub can_showHints {
#my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
return 1;
}
# gateway change here: add $submitAnswers as an optional additional argument
# to be included if it's defined
sub can_showSolutions {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem,
$tmplSet, $submitAnswers) = @_;
my $authz = $self->r->authz;
# this is the same as can_showCorrectAnswers
# gateway change here to allow correct answers to be viewed after all attempts
# at a version are exhausted as well as if it's after the answer date
# $addOne allows us to count the current submission
my $addOne = defined($submitAnswers) ? $submitAnswers : 0;
my $attempts_per_version = $Set->attempts_per_version() || 0;
my $attemptsUsed = $Problem->num_correct+$Problem->num_incorrect+$addOne || 0;
# this is complicated by trying to address hiding scores by problem---that
# is, if $set->hide_score_by_problem and $set->hide_score are both set,
# then we should allow scores to be shown, but not show the score on
# any individual problem. to deal with this, we make can_showSolutions
# give the least restrictive view of hiding, and then filter scores for
# the problems themselves later
# showing correcrt answers but not showing scores doesn't make sense
# so we should hide the correct answers if we aren not showing
# scores GG.
my $canShowScores = $Set->hide_score_by_problem eq 'N' &&
($Set->hide_score eq 'N' ||
($Set->hide_score eq 'BeforeAnswerDate' && after($tmplSet->answer_date)));
return (((after($Set->answer_date) ||
($attemptsUsed >= $attempts_per_version &&
$attempts_per_version != 0 &&
$Set->due_date() == $Set->answer_date())) ||
$authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")) &&
($authz->hasPermissions($User->user_id, "view_hidden_work") || $canShowScores));
}
# gateway change here: add $submitAnswers as an optional additional argument
# to be included if it's defined
# we also allow for a version_last_attempt_time which is the time the set was
# submitted; if that's present we use that instead of the current time to
# decide if we can record the answers. this deals with the time between the
# submission time and the proctor authorization.
sub can_recordAnswers {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem,
$tmplSet, $submitAnswers) = @_;
my $authz = $self->r->authz;
# easy first case: never record answers for undefined sets
return 0 if $Set->set_id eq "Undefined_Set";
my $timeNow = defined($self->{timeNow}) ? $self->{timeNow} : time();
# get the sag time after the due date in which we'll still grade the test
my $grace = $self->{ce}->{gatewayGracePeriod};
my $submitTime = ($Set->assignment_type eq 'proctored_gateway' &&
defined($Set->version_last_attempt_time()) && $Set->version_last_attempt_time())
? $Set->version_last_attempt_time() : $timeNow;
if ($User->user_id ne $EffectiveUser->user_id) {
my $recordAsOther = $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
my $recordVersionsAsOther = $authz->hasPermissions($User->user_id, "record_set_version_answers_when_acting_as_student");
if ($recordAsOther) {
return $recordAsOther;
} elsif (!$recordVersionsAsOther) {
return $recordVersionsAsOther;
}
## if we're not allowed to record answers as another user,
## return that permission. if we're allowed to record
## only set version answers, then we allow that between
## the open and close dates, and so drop out of this
## conditional to the usual one.
## it isn't clear if this is the correct behavior, but I
## think it's probably reasonable.
}
if (before($Set->open_date, $submitTime)) {
return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
} elsif (between($Set->open_date, $Set->due_date + $grace, $submitTime)) {
# gateway change here; we look at maximum attempts per version, not for the set,
# to determine the number of attempts allowed
# $addOne allows us to count the current submission
my $addOne = (defined($submitAnswers) && $submitAnswers) ? 1 : 0;
my $attempts_per_version = $Set->attempts_per_version() || 0;
my $attempts_used = $Problem->num_correct+$Problem->num_incorrect+$addOne;
if ($attempts_per_version == 0 or $attempts_used < $attempts_per_version) {
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");
}
} elsif (between(($Set->due_date + $grace), $Set->answer_date, $submitTime)) {
return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
} elsif (after($Set->answer_date, $submitTime)) {
return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
}
}
# gateway change here: add $submitAnswers as an optional additional argument
# to be included if it's defined
# we also allow for a version_last_attempt_time which is the time the set was
# submitted; if that's present we use that instead of the current time to
# decide if we can check the answers. this deals with the time between the
# submission time and the proctor authorization.
sub can_checkAnswers {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem,
$tmplSet, $submitAnswers) = @_;
my $authz = $self->r->authz;
# if we can record answers then we dont need to be able to check them
# unless we have that specific permission.
if ($self->can_recordAnswers($User, $PermissionLevel, $EffectiveUser,
$Set, $Problem, $tmplSet, $submitAnswers)
&& !$authz->hasPermissions($User->user_id, "can_check_and_submit_answers")) {
return 0;
}
my $timeNow = defined($self->{timeNow}) ? $self->{timeNow} : time();
# get the sag time after the due date in which we'll still grade the test
my $grace = $self->{ce}->{gatewayGracePeriod};
my $submitTime = ($Set->assignment_type eq 'proctored_gateway' &&
defined($Set->version_last_attempt_time()) && $Set->version_last_attempt_time())
? $Set->version_last_attempt_time() : $timeNow;
# this is further complicated by trying to address hiding scores by
# problem---that is, if $set->hide_score_by_problem and
# $set->hide_score are both set, then we should allow scores to
# be shown, but not show the score on any individual problem.
# to deal with this, we use the least restrictive view of hiding
# here, and then filter for the problems themselves later
# showing correcrt answers but not showing scores doesn't make sense
# so we should hide the correct answers if we aren not showing
# scores GG.
my $canShowScores = $Set->hide_score_by_problem eq 'N' && ($Set->hide_score eq 'N' ||
($Set->hide_score eq 'BeforeAnswerDate' && after($tmplSet->answer_date)));
if (before($Set->open_date, $submitTime)) {
return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
} elsif (between($Set->open_date, $Set->due_date + $grace, $submitTime)) {
# gateway change here; we look at maximum attempts per version, not for the set,
# to determine the number of attempts allowed
# $addOne allows us to count the current submission
my $addOne = (defined($submitAnswers) && $submitAnswers) ? 1 : 0;
my $attempts_per_version = $Set->attempts_per_version() || 0;
my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $addOne;
if ($attempts_per_version == -1 or $attempts_used < $attempts_per_version) {
return ($authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts") &&
($authz->hasPermissions($User->user_id, "view_hidden_work") ||
$canShowScores));
} else {
return ($authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts") &&
($authz->hasPermissions($User->user_id, "view_hidden_work") ||
$canShowScores));
}
} elsif (between(($Set->due_date + $grace), $Set->answer_date, $submitTime)) {
return ($authz->hasPermissions($User->user_id, "check_answers_after_due_date") &&
($authz->hasPermissions($User->user_id, "view_hidden_work") ||
$canShowScores));
} elsif (after($Set->answer_date, $submitTime)) {
return ($authz->hasPermissions($User->user_id, "check_answers_after_answer_date") &&
($authz->hasPermissions($User->user_id, "view_hidden_work") ||
$canShowScores));
}
}
sub can_showScore {
my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem,
$tmplSet, $submitAnswers) = @_;
my $authz = $self->r->authz;
my $timeNow = defined($self->{timeNow}) ? $self->{timeNow} : time();
# address hiding scores by problem
my $canShowScores = ($Set->hide_score eq 'N' ||
($Set->hide_score eq 'BeforeAnswerDate' &&
after($tmplSet->answer_date)));
return ($authz->hasPermissions($User->user_id,"view_hidden_work") || $canShowScores);
}
sub can_useMathView {
my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
my $ce= $self->r->ce;
return $ce->{pg}->{specialPGEnvironmentVars}->{entryAssist} eq 'MathView';
}
sub can_useWirisEditor {
my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
my $ce= $self->r->ce;
return $ce->{pg}->{specialPGEnvironmentVars}->{entryAssist} eq 'WIRIS';
}
sub can_useMathQuill {
my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
my $ce= $self->r->ce;
return $ce->{pg}->{specialPGEnvironmentVars}->{entryAssist} eq 'MathQuill';
}
################################################################################
# output utilities
################################################################################
sub attemptResults {
my $self = shift;
my $pg = shift;
my $showAttemptAnswers = shift;
my $showCorrectAnswers = shift;
my $showAttemptResults = $showAttemptAnswers && shift;
my $showSummary = shift;
my $showAttemptPreview = shift || 0;
my $colorAnswers = $showAttemptResults;
my $ce = $self->{ce};
# for color coding the responses.
$self->{correct_ids} = [] unless $self->{correct_ids};
$self->{incorrect_ids} = [] unless $self->{incorrect_ids};
# to make grabbing these options easier, we'll pull them out now...
my %imagesModeOptions = %{$ce->{pg}{displayModeOptions}{images}};
my $imgGen = WeBWorK::PG::ImageGenerator->new(
tempDir => $ce->{webworkDirs}{tmp},
latex => $ce->{externalPrograms}{latex},
dvipng => $ce->{externalPrograms}{dvipng},
useCache => 1,
cacheDir => $ce->{webworkDirs}{equationCache},
cacheURL => $ce->{webworkURLs}{equationCache},
cacheDB => $ce->{webworkFiles}{equationCacheDB},
dvipng_align => $imagesModeOptions{dvipng_align},
dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
);
my $showEvaluatedAnswers = $ce->{pg}{options}{showEvaluatedAnswers} // '';
# Create AttemptsTable object
my $tbl = WeBWorK::Utils::AttemptsTable->new(
$pg->{answers},
answersSubmitted => 1,
answerOrder => $pg->{flags}{ANSWER_ENTRY_ORDER},
displayMode => $self->{displayMode},
showHeadline => 0,
showAnswerNumbers => 0,
showAttemptAnswers => $showAttemptAnswers && $showEvaluatedAnswers,
showAttemptPreviews => $showAttemptPreview,
showAttemptResults => $showAttemptResults,
showCorrectAnswers => $showCorrectAnswers,
showMessages => $showAttemptAnswers, # internally checks for messages
showSummary => $showSummary,
imgGen => $imgGen, # not needed if ce is present ,
ce => '', # not needed if $imgGen is present
maketext => WeBWorK::Localize::getLoc($ce->{language}),
);
my $answerTemplate = $tbl->answerTemplate;
$tbl->imgGen->render(refresh => 1) if $tbl->displayMode eq 'images';
push(@{$self->{correct_ids}}, @{$tbl->correct_ids}) if $colorAnswers;
push(@{$self->{incorrect_ids}}, @{$tbl->incorrect_ids}) if $colorAnswers;
return $answerTemplate;
}
sub handle_input_colors {
my $self = shift;
my $r = $self->r;
my $ce = $r->ce;
my $site_url = $ce->{webworkURLs}{htdocs};
return if $self->{previewAnswers}; # don't color previewed answers
# The color.js file, which uses javascript to color the input fields based on whether they are correct or incorrect.
print CGI::start_script({type=>"text/javascript", src=>"$site_url/js/apps/InputColor/color.js"}), CGI::end_script();
print CGI::start_script({type=>"text/javascript"}),
"color_inputs([",
join(", ", map {"'$_'"} @{$self->{correct_ids} || []}), "],\n[",
join(", ", map {"'$_'"} @{$self->{incorrect_ids} || []}), "]);",
CGI::end_script();
}
sub get_instructor_comment {
my ($self, $problem) = @_;
return unless ref($problem) =~ /ProblemVersion/;
my $db = $self->r->db;
my $userPastAnswerID = $db->latestProblemPastAnswer($self->{ce}{courseName}, $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 escape implementations
################################################################################
# FIXME need to make $Set and $set be used consistently
sub pre_header_initialize {
my ($self) = @_;
my $r = $self->r;
my $ce = $r->ce;
my $db = $r->db;
my $authz = $r->authz;
my $urlpath = $r->urlpath;
my $setName = $urlpath->arg("setID");
my $userName = $r->param('user');
my $effectiveUserName = $r->param('effectiveUser');
my $key = $r->param('key');
# should we allow a new version to be created when acting as a user?
my $verCreateOK = defined($r->param('createnew_ok')) ? $r->param('createnew_ok') : 0;
# user checks
my $User = $db->getUser($userName);
die "record for user $userName (real user) does not exist." unless defined $User;
my $EffectiveUser = $db->getUser($effectiveUserName);
die "record for user $effectiveUserName (effective user) does not exist." unless defined $EffectiveUser;
my $PermissionLevel = $db->getPermissionLevel($userName);
die "permission level record for $userName does not exist (but the user does? odd...)"
unless defined($PermissionLevel);
my $permissionLevel = $PermissionLevel->permission;
# we could be coming in with $setName = the versioned or nonversioned set
# deal with that first
my $requestedVersion = ($setName =~ /,v(\d+)$/) ? $1 : 0;
$setName =~ s/,v\d+$//;
# note that if we're already working with a version we want to be sure to stick
# with that version. we do this after we've validated that the user is
# assigned the set, below
###################################
# 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. assemble these
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 ($setName eq "Undefined_Set") {
# make sure these are defined
$requestedVersion = 1;
$self->{assignment_type} = 'gateway';
if (!$authz->hasPermissions($userName, "modify_problem_sets")) {
$self->{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 (!$r->param("sourceFilePath")) {
$self->{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 = $r->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);
$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(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(time());
$set->time_limit_cap('0');
$Problem->problem_id(1);
$Problem->source_file($sourceFPath);
$Problem->user_id($effectiveUserName);
$Problem->value(1);
$Problem->problem_seed($r->param("problemSeed")) if ($r->param("problemSeed"));
}
}
} else {
# get template set: the non-versioned set that's assigned to the user
# if this fails/failed in authz->checkSet, then $self->{invalidSet} is set
$tmplSet = $db->getMergedSet($effectiveUserName, $setName);
$self->{isOpen} = $authz->hasPermissions($userName, "view_unopened_sets") || (time >= $tmplSet->open_date && !(
$ce->{options}{enableConditionalRelease} &&
is_restricted($db, $tmplSet, $effectiveUserName)));
die("You do not have permission to view unopened sets") unless $self->{isOpen};
# now we know that we're in a gateway test, save the assignment test
# for the processing of proctor keys for graded proctored tests;
# if we failed to get the set from the database, we store a fake
# value here to be able to continue
$self->{'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($effectiveUserName, $setName);
my $latestVersion = (@allVersionIds ? $allVersionIds[-1] : 0);
# double check that any requested version makes sense
$requestedVersion = $latestVersion
if ($requestedVersion !~ /^\d+$/ ||
$requestedVersion > $latestVersion ||
$requestedVersion < 0);
die("No requested version when returning to problem?!")
if (($r->param("previewAnswers") ||
$r->param("checkAnswers") ||
$r->param("submitAnswers") ||
$r->param("newPage")) && ! $requestedVersion);
# to test for a proctored test, we need the set version, not the
# template, to allow a finished proctored test to be checked as an
# unproctored test. so we get the versioned set here
if ($requestedVersion) {
# if a specific set version was requested, it was stored in the $authz
# object when we did the set check
$set = $db->getMergedSetVersion($effectiveUserName,
$setName,
$requestedVersion);
} elsif ($latestVersion) {
# otherwise, if there's a current version, which we take to be the
# latest version taken, we use that
$set = $db->getMergedSetVersion($effectiveUserName,
$setName,
$latestVersion);
} else {
# and if neither of those work, get a dummy set so that we have
# something to work with
my $userSetClass = $ce->{dbLayout}->{set_version}->{record};
# FIXME RETURN TO: should this be global2version?
$set = global2user($userSetClass, $db->getGlobalSet($setName));
die "set $setName not found." unless $set;
$set->user_id($effectiveUserName);
$set->psvn('000');
$set->set_id("$setName"); # redundant?
$set->version_id(0);
}
}
my $setVersionNumber = ($set) ? $set->version_id() : 0;
#################################
# assemble gateway parameters
#################################
# we get the open/close dates for the gateway from the template set.
# note $isOpen/Closed give the open/close dates for the gateway
# as a whole (that is, the merged user|global set). because the
# set could be bad (if $self->{invalidSet}), we check ->open_date
# before actually testing the date
my $isOpen = $tmplSet && $tmplSet->open_date && (after($tmplSet->open_date()) ||
$authz->hasPermissions($userName, "view_unopened_sets"));
# FIXME for $isClosed, "record_answers_after_due_date" isn't quite
# the right description, but it seems reasonable
my $isClosed = $tmplSet && $tmplSet->due_date && (after($tmplSet->due_date()) &&
! $authz->hasPermissions($userName, "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 it's the case
my @setPNum = $setName eq "Undefined_Set" ? (1) : $db->listUserProblems($EffectiveUser->user_id, $setName);
die("Set $setName contains no problems.") if (!@setPNum);
# if we assigned a fake problem above, $Problem is already defined.
# otherwise, we get the Problem, or define it to be undefined if
# the set hasn't been versioned to the user yet--this gets fixed
# when we assign the setVersion
if (!$Problem) {
$Problem = $setVersionNumber
? $db->getMergedProblemVersion($EffectiveUser->user_id, $setName, $setVersionNumber, $setPNum[0])
: undef;
}
# note that having $maxAttemptsPerVersion set to an infinite/0 value is
# nonsensical; if we did that, why have versions? (might want to do it for one individual?)
# Its actually a good thing for "repeatable" practice sets
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? I think 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 must have the same submission characteristics
my $currentNumAttempts = (defined($Problem) && $Problem->num_correct() ne '')
? $Problem->num_correct() + $Problem->num_incorrect() : 0;
# $maxAttempts turns into the maximum number of versions we can create;
# if $Problem isn't defined, we can't have made any attempts, so it
# doesn't matter
my $maxAttempts = (defined($Problem) && defined($Problem->max_attempts()) && $Problem->max_attempts())
? $Problem->max_attempts() : -1;
# finding the number of versions per time interval is a little harder.
# we interpret the time interval as a rolling interval: that is,
# if we allow two sets per day, that's two sets in any 24 hour
# period. this is probably not what we really want, but it's
# more extensible to a limitation like "one version per hour",
# and we can set it to two sets per 12 hours for most "2ce daily"
# type applications
my $timeNow = time();
my $grace = $ce->{gatewayGracePeriod};
my $currentNumVersions = 0; # this is the number of versions in the
# time interval
my $totalNumVersions = 0;
# we don't need to check this if $self->{invalidSet} is already set,
# or if we're working with an Undefined_Set
if ($setVersionNumber && ! $self->{invalidSet} && $setName ne "Undefined_Set") {
my @setVersionIDs = $db->listSetVersions($effectiveUserName, $setName);
my @setVersions = $db->getSetVersions(map {[$effectiveUserName, $setName,, $_]} @setVersionIDs);
foreach (@setVersions) {
$totalNumVersions++;
$currentNumVersions++
if (!$timeInterval ||
$_->version_creation_time() > ($timeNow - $timeInterval));
}
}
####################################
# new version creation conditional
####################################
my $versionIsOpen = 0; # can we do anything to this version?
# recall $isOpen = timeNow > openDate [for the merged userset] and
# $isClosed = timeNow > dueDate [for the merged userset]
# again, if $self->{invalidSet} is already set, we don't need to
# to check this
if ($isOpen && ! $isClosed && ! $self->{invalidSet}) {
# if no specific version is requested, we can create a new one if
# need be
if (!$requestedVersion) {
if (($maxAttempts == -1 ||
$totalNumVersions < $maxAttempts)
&&
($setVersionNumber == 0 ||
(
($currentNumAttempts>=$maxAttemptsPerVersion
||
$timeNow >= $set->due_date + $grace)
&&
(! $versionsPerInterval
||
$currentNumVersions < $versionsPerInterval)
)
)
&&
($effectiveUserName eq $userName ||
($authz->hasPermissions($userName, "record_answers_when_acting_as_student") ||
($authz->hasPermissions($userName, "create_new_set_version_when_acting_as_student") && $verCreateOK)))
) {
# assign set, get the right name, version
# number, etc., and redefine the $set
# and $Problem we're working with
my $setTmpl = $db->getUserSet($effectiveUserName,$setName);
WeBWorK::ContentGenerator::Instructor::assignSetVersionToUser($self, $effectiveUserName, $setTmpl);
$setVersionNumber++;
# get a clean version of the set to save,
# and the merged version to use in the
# rest of the routine
my $cleanSet = $db->getSetVersion($effectiveUserName, $setName, $setVersionNumber);
$set = $db->getMergedSetVersion($effectiveUserName, $setName, $setVersionNumber);
$Problem = $db->getMergedProblemVersion($effectiveUserName, $setName, $setVersionNumber, 1);
# because we're creating this on the fly,
# it should be visible
$set->visible(1);
# set up creation time, open and due dates
my $ansOffset = $set->answer_date() - $set->due_date();
$set->version_creation_time($timeNow);
$set->open_date($timeNow);
# figure out the due date, taking into account
# any time limit cap
my $dueTime = ($timeLimit == 0 || ($set->time_limit_cap && $timeNow+$timeLimit > $set->due_date))
? $set->due_date : $timeNow+$timeLimit;
$set->due_date($dueTime);
$set->answer_date($set->due_date + $ansOffset);
$set->version_last_attempt_time(0);
my $proctorOnlyNeededWhenStarting = $ce->{options}{proctorOnlyNeededWhenStarting} // 0;
if ( $set->assignment_type eq 'proctored_gateway' && $proctorOnlyNeededWhenStarting ) {
# override the assignment type if proctor login is only required to start the quiz
$set->assignment_type( 'gateway' );
}
# put this new info into the database. we
# put back that data which we need for the
# version, and leave blank any information
# that we'd like to inherit from the user
# set or global set. we set the data which
# determines if a set is open, because we
# don't want the set version to 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);
# we have a new set version, so it's open
$versionIsOpen = 1;
# also reset the number of attempts for this
# set to zero
$currentNumAttempts = 0;
} elsif ($maxAttempts != -1 && $totalNumVersions > $maxAttempts) {
$self->{invalidSet} = "No new versions of this assignment are available, " .
"because you have already taken the maximum number allowed.";
} elsif ($effectiveUserName ne $userName &&
$authz->hasPermissions($userName, "create_new_set_version_when_acting_as_student")) {
$self->{invalidSet} = "User $effectiveUserName 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.";
$self->{invalidVersionCreation} = 1;
} elsif ($effectiveUserName ne $userName) {
$self->{invalidSet} = "User $effectiveUserName is being acted as. " .
"When acting as another user, new versions of the set cannot be created.";
$self->{invalidVersionCreation} = 2;
} elsif (($maxAttemptsPerVersion == 0 || $currentNumAttempts < $maxAttemptsPerVersion) &&
$timeNow < $set->due_date() + $grace) {
if (between($set->open_date(), $set->due_date() + $grace, $timeNow)) {
$versionIsOpen = 1;
} else {
$versionIsOpen = 0; # redundant
$self->{invalidSet} = "No new versions of this assignment" .
" are available,\nbecause the set is not open or its time" .
" limit has expired.\n";
}
} elsif ($versionsPerInterval &&
($currentNumVersions >= $versionsPerInterval)){
$self->{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 {
# (we're still in the $isOpen && ! $isClosed conditional here)
# if a specific version is requested, then we only check to
# see if it's open
if (($currentNumAttempts < $maxAttemptsPerVersion)
&&
($effectiveUserName eq $userName ||
$authz->hasPermissions($userName, "record_set_version_answers_when_acting_as_student"))
) {
if (between($set->open_date(), $set->due_date() + $grace, $timeNow)) {
$versionIsOpen = 1;
} else {
$versionIsOpen = 0; # redundant
}
}
}
# closed set, with attempt at a new one
} elsif (!$self->{invalidSet} && !$requestedVersion) {
$self->{invalidSet} = "This set is closed. No new set versions may be taken.";
}
####################################
# save problem and user data
####################################
my $psvn = $set->psvn();
$self->{tmplSet} = $tmplSet;
$self->{set} = $set;
$self->{problem} = $Problem;
$self->{requestedVersion} = $requestedVersion;
$self->{userName} = $userName;
$self->{effectiveUserName} = $effectiveUserName;
$self->{user} = $User;
$self->{effectiveUser} = $EffectiveUser;
$self->{permissionLevel} = $permissionLevel;
$self->{isOpen} = $isOpen;
$self->{isClosed} = $isClosed;
$self->{versionIsOpen} = $versionIsOpen;
$self->{timeNow} = $timeNow;
####################################
# form processing
####################################
# this is the same as the following, but doesn't appear in Problem.pm
my $newPage = $r->param("newPage");
$self->{newPage} = $newPage;
# also get the current page, if it's given
my $currentPage = $r->param("currentPage") || 1;
# This is a hack to manage changing pages. We set previewAnswers to
# false if the "pageChangeHack" input is set (a page change link was used).
$r->param('previewAnswers', 0) if ($r->param('pageChangeHack'));
# [This section lifted from Problem.pm] ##############################
# set options from form fields (see comment at top of file for names)
my $displayMode = $User->displayMode || $ce->{pg}->{options}->{displayMode};
my $redisplay = $r->param("redisplay");
my $submitAnswers = $r->param("submitAnswers") // 0;
my $checkAnswers = $r->param("checkAnswers") // 0;
my $previewAnswers = $r->param("previewAnswers") // 0;
my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
$self->{displayMode} = $displayMode;
$self->{redisplay} = $redisplay;
$self->{submitAnswers} = $submitAnswers;
$self->{checkAnswers} = $checkAnswers;
$self->{previewAnswers} = $previewAnswers;
$self->{formFields} = $formFields;
# now that we've set all the necessary variables quit out if the set or
# problem is invalid
return if $self->{invalidSet} || $self->{invalidProblem};
# [End lifted section] ###############################################
####################################
# permissions
####################################
# bail without doing anything if the set isn't yet open for this user
if (!($self->{isOpen} || $authz->hasPermissions($userName,"view_unopened_sets"))) {
$self->{invalidSet} = "This set is not yet open.";
return;
}
# what does the user want to do?
my %want = (
showOldAnswers => $User->showOldAnswers ne '' ?
$User->showOldAnswers : $ce->{pg}->{options}->{showOldAnswers},
# showProblemGrader implies showCorrectAnswers. This is a convenience for grading.
showCorrectAnswers => $r->param('showProblemGrader') ||
(($r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers})
&& ($submitAnswers || $checkAnswers)),
showProblemGrader => $r->param('showProblemGrader') || 0,
showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints},
# showProblemGrader implies showSolutions. Another convenience for grading.
showSolutions => $r->param('showProblemGrader') ||
(($r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions})
&& ($submitAnswers || $checkAnswers)),
recordAnswers => $submitAnswers && !$authz->hasPermissions($userName, "avoid_recording_answers"),
# we also want to check answers if we were checking answers and are
# switching between pages
checkAnswers => $checkAnswers,
useMathView => $User->useMathView ne '' ? $User->useMathView : $ce->{pg}->{options}->{useMathView},
useWirisEditor => $User->useWirisEditor ne '' ? $User->useWirisEditor : $ce->{pg}->{options}->{useWirisEditor},
useMathQuill => $User->useMathQuill ne '' ? $User->useMathQuill : $ce->{pg}->{options}->{useMathQuill},
);
# are certain options enforced?
my %must = (
showOldAnswers => 0,
showCorrectAnswers => 0,
showProblemGrader => 0,
showHints => 0,
showSolutions => 0,
recordAnswers => 0,
checkAnswers => 0,
useMathView => 0,
useWirisEditor => 0,
useMathQuill => 0,
);
# does the user have permission to use certain options?
my @args = ($User, $PermissionLevel, $EffectiveUser, $set, $Problem, $tmplSet);
my $sAns = $submitAnswers ? 1 : 0;
my %can = (
showOldAnswers => $self->can_showOldAnswers(@args),
showCorrectAnswers => $self->can_showCorrectAnswers(@args, $sAns),
showProblemGrader => $self->can_showProblemGrader(@args),
showHints => $self->can_showHints(@args),
showSolutions => $self->can_showSolutions(@args, $sAns),
recordAnswers => $self->can_recordAnswers(@args),
checkAnswers => $self->can_checkAnswers(@args),
recordAnswersNextTime => $self->can_recordAnswers(@args, $sAns),
checkAnswersNextTime => $self->can_checkAnswers(@args, $sAns),
showScore => $self->can_showScore(@args),
useMathView => $self->can_useMathView(@args),
useWirisEditor => $self->can_useWirisEditor(@args),
useMathQuill => $self->can_useMathQuill(@args)
);
# final values for options
my %will;
foreach (keys %must) {