[system] / branches / rel-2-2-dev / webwork2 / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

Diff of /branches/rel-2-2-dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

Revision 555 Revision 1663
1################################################################################ 1################################################################################
2# WeBWorK mod_perl (c) 2000-2002 WeBWorK Project 2# WeBWorK Online Homework Delivery System
3# $Id$ 3# Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
4# $CVSHeader$
5#
6# This program is free software; you can redistribute it and/or modify it under
7# the terms of either: (a) the GNU General Public License as published by the
8# Free Software Foundation; either version 2, or (at your option) any later
9# version, or (b) the "Artistic License" which comes with this package.
10#
11# This program is distributed in the hope that it will be useful, but WITHOUT
12# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13# FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the
14# Artistic License for more details.
4################################################################################ 15################################################################################
5 16
6package WeBWorK::ContentGenerator::Problem; 17package WeBWorK::ContentGenerator::Problem;
18use base qw(WeBWorK::ContentGenerator);
7 19
8=head1 NAME 20=head1 NAME
9 21
10WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem. 22WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
11 23
12=cut 24=cut
13 25
14use strict; 26use strict;
15use warnings; 27use warnings;
16use base qw(WeBWorK::ContentGenerator);
17use CGI qw(); 28use CGI qw();
29use File::Path qw(rmtree);
18use WeBWorK::Form; 30use WeBWorK::Form;
19use WeBWorK::PG; 31use WeBWorK::PG;
20use WeBWorK::Utils qw(ref2string encodeAnswers decodeAnswers); 32use WeBWorK::PG::ImageGenerator;
33use WeBWorK::PG::IO;
34use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory);
35use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
36use WeBWorK::Timing;
37
38my $timer0_ON=0; # times pg translation phase
21 39
22############################################################ 40############################################################
23# 41#
24# user 42# user
43# effectiveUser
25# key 44# key
26# 45#
27# displayMode 46# displayMode
28# showOldAnswers 47# showOldAnswers
29# showCorrectAnswers 48# showCorrectAnswers
32# 51#
33# AnSwEr# - answer blanks in problem 52# AnSwEr# - answer blanks in problem
34# 53#
35# redisplay - name of the "Redisplay Problem" button 54# redisplay - name of the "Redisplay Problem" button
36# submitAnswers - name of "Submit Answers" button 55# submitAnswers - name of "Submit Answers" button
56# checkAnswers - name of the "Check Answers" button
57# previewAnswers - name of the "Preview Answers" button
58#
59# FIXME: this table is heinously out of date
37# 60#
38############################################################ 61############################################################
39 62
63# FIXME: what is this?
64sub templateName {
65 "problem";
66}
67
40sub pre_header_initialize { 68sub pre_header_initialize {
41 my ($self, $setName, $problemNumber) = @_; 69 my ($self, $setName, $problemNumber) = @_;
42 my $courseEnv = $self->{courseEnvironment}; 70 my $r = $self->{r};
43 my $r = $self->{r}; 71 my $courseEnv = $self->{ce};
72 my $db = $self->{db};
44 my $userName = $r->param('user'); 73 my $userName = $r->param('user');
74 my $effectiveUserName = $r->param('effectiveUser');
75 my $key = $r->param('key');
45 76
46 ##### database setup #####
47
48 my $cldb = WeBWorK::DB::Classlist->new($courseEnv);
49 my $wwdb = WeBWorK::DB::WW->new($courseEnv);
50 my $authdb = WeBWorK::DB::Auth->new($courseEnv);
51
52 my $user = $cldb->getUser($userName); 77 my $user = $db->getUser($userName); # checked
53 my $set = $wwdb->getSet($userName, $setName); 78 die "record for user $userName (real user) does not exist."
54 my $problem = $wwdb->getProblem($userName, $setName, $problemNumber); 79 unless defined $user;
55 my $psvn = $wwdb->getPSVN($userName, $setName); 80
81 my $effectiveUser = $db->getUser($effectiveUserName); # checked
82 die "record for user $effectiveUserName (effective user) does not exist."
83 unless defined $effectiveUser;
84
56 my $permissionLevel = $authdb->getPermissions($userName); 85 my $PermissionLevel = $db->getPermissionLevel($userName); # checked
86 die "permission level record for user $userName does not exist (but the user does? odd...)"
87 unless defined $PermissionLevel;
88 my $permissionLevel = $PermissionLevel->permission;
89
90 # obtain the merged set for $effectiveUser
91 my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
92
93 # obtain the merged problem for $effectiveUser
94 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
95
96 my $editMode = $r->param("editMode");
97
98 if ($permissionLevel > 0 and defined $editMode) {
99 # professors are allowed to fabricate sets and problems not
100 # assigned to them (or anyone). this allows them to use the
101 # editor to
102
103 # if that is not yet defined obtain the global set, convert
104 # it to a user set, and add fake user data
105 unless (defined $set) {
106 my $userSetClass = $db->{set_user}->{record};
107 my $globalSet = $db->getGlobalSet($setName); # checked
108 # if the global set doesn't exist either, bail!
109 die "Set $setName does not exist"
110 unless defined $set;
111 $set = global2user($userSetClass, $globalSet);
112 $set->psvn(0);
113 }
114
115 # if that is not yet defined obtain the global problem,
116 # convert it to a user problem, and add fake user data
117 unless (defined $problem) {
118 my $userProblemClass = $db->{problem_user}->{record};
119 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
120 # if the global problem doesn't exist either, bail!
121 die "Problem $problemNumber in set $setName does not exist"
122 unless defined $problem;
123 $problem = global2user($userProblemClass, $globalProblem);
124 $problem->user_id($effectiveUserName);
125 $problem->problem_seed(0);
126 $problem->status(0);
127 $problem->attempted(0);
128 $problem->last_answer("");
129 $problem->num_correct(0);
130 $problem->num_incorrect(0);
131 }
132
133 # now we're sure we have valid UserSet and UserProblem objects
134 # yay!
135
136 # now deal with possible editor overrides:
137
138 # if the caller is asking to override the source file, and
139 # editMode calls for a temporary file, do so
140 my $sourceFilePath = $r->param("sourceFilePath");
141 if (defined $sourceFilePath and $editMode eq "temporaryFile") {
142 $problem->source_file($sourceFilePath);
143 }
144
145 # if the caller is asking to override the problem seed, do so
146 my $problemSeed = $r->param("problemSeed");
147 if (defined $problemSeed) {
148 $problem->problem_seed($problemSeed);
149 }
150 } else {
151 # students can't view problems not assigned to them
152 die "Set $setName is not assigned to $effectiveUserName"
153 unless defined $set;
154 die "Problem $problemNumber in set $setName is not assigned to $effectiveUserName"
155 unless defined $problem;
156 }
157
158 $self->{userName} = $userName;
159 $self->{effectiveUserName} = $effectiveUserName;
160 $self->{user} = $user;
161 $self->{effectiveUser} = $effectiveUser;
162 $self->{permissionLevel} = $permissionLevel;
163 $self->{set} = $set;
164 $self->{problem} = $problem;
165 $self->{editMode} = $editMode;
57 166
58 ##### form processing ##### 167 ##### form processing #####
59 168
60 # set options from form fields (see comment at top of file for names) 169 # set options from form fields (see comment at top of file for names)
61 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode}; 170 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode};
62 my $redisplay = $r->param("redisplay"); 171 my $redisplay = $r->param("redisplay");
63 my $submitAnswers = $r->param("submitAnswers"); 172 my $submitAnswers = $r->param("submitAnswers");
173 my $checkAnswers = $r->param("checkAnswers");
174 my $previewAnswers = $r->param("previewAnswers");
175
176 # fields which may be defined when using Problem Editor
177 #my $override_seed = ($permissionLevel>=10) ? $r->param('problemSeed') : undef;
178 #my $override_problem_source = ($permissionLevel>=10) ? $r->param('sourceFilePath') : undef;
179 #my $editMode = undef;
180 #my $submit_button = $r->param('submit_button');
181 #if ( defined($submit_button ) ) {
182 # $editMode = "temporaryFile" if $submit_button eq 'Refresh';
183 # $editMode = 'savedFile' if $submit_button eq 'Save';
184 #}
185 #
186 ##override using the source file data from the form field
187 #$problem->source_file($override_problem_source) if defined($override_problem_source);
188 #$problem->problem_seed($override_seed) if defined($override_seed);
189 #
190 ## store path to source file for title.
191 #$self->{problem_source_name} = $problem->source_file;
192 #$self->{edit_mode} = $editMode;
193 #$self->{current_problem_source} = (defined($override_problem_source) ) ?
64 194
65 # coerce form fields into CGI::Vars format 195 # coerce form fields into CGI::Vars format
66 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; 196 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
197
198
199 $self->{displayMode} = $displayMode;
200 $self->{redisplay} = $redisplay;
201 $self->{submitAnswers} = $submitAnswers;
202 $self->{checkAnswers} = $checkAnswers;
203 $self->{previewAnswers} = $previewAnswers;
204 $self->{formFields} = $formFields;
67 205
68 ##### permissions ##### 206 ##### permissions #####
207
208 # are we allowed to view this problem?
209 $self->{isOpen} = time >= $set->open_date || $permissionLevel > 0;
210 return unless $self->{isOpen};
69 211
70 # what does the user want to do? 212 # what does the user want to do?
71 my %want = ( 213 my %want = (
72 showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers}, 214 showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers},
73 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers}, 215 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers},
74 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints}, 216 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints},
75 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions}, 217 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions},
76 recordAnswers => $r->param("recordAnswers") || 1, 218 recordAnswers => $submitAnswers,
219 checkAnswers => $checkAnswers,
77 ); 220 );
78 221
79 # are certain options enforced? 222 # are certain options enforced?
80 my %must = ( 223 my %must = (
81 showOldAnswers => 0, 224 showOldAnswers => 0,
82 showCorrectAnswers => 0, 225 showCorrectAnswers => 0,
83 showHints => 0, 226 showHints => 0,
84 showSolutions => 0, 227 showSolutions => 0,
85 recordAnswers => mustRecordAnswers($permissionLevel), 228 recordAnswers => mustRecordAnswers($permissionLevel),
229 checkAnswers => 0,
86 ); 230 );
87 231
88 # does the user have permission to use certain options? 232 # does the user have permission to use certain options?
89 my %can = ( 233 my %can = (
90 showOldAnswers => 1, 234 showOldAnswers => 1,
91 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), 235 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
92 showHints => 1, 236 showHints => 1,
93 showSolutions => canShowSolutions($permissionLevel, $set->answer_date), 237 showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
94 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, 238 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
95 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), 239 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
96 # num_correct+num_incorrect+1 -- as this happens before updating $problem 240 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
241 checkAnswers => canCheckAnswers($permissionLevel, $set->answer_date),
97 ); 242 );
243 #########################################################
244 # more complicated logic for showing check answer button:
245 #########################################################
246 # checkAnswers button shows up after due date -- once a student can't record anymore
247 # checkAnswers button always shows up when an instructor or TA is acting
248 # as someone else (the $user and $effectiveUserName aren't the same).
249 $can{checkAnswers} = ($can{checkAnswers} && not $can{recordAnswers} ) ||
250 ( defined($userName) and defined($effectiveUserName) and
251 ($userName ne $effectiveUserName)
252 );
253 #########################################################
254 # more complicated logif for showing "submit answer" button
255 #########################################################
256 # We hide the submit answer button if someone is acting as a student
257 # This prevents errors where you accidently submit the answer for a student
258 # Not sure whether this a feature or a bug
98 259
260 $can{recordAnswers} = ($can{recordAnswers} and not
261 ( defined($userName) and defined($effectiveUserName) and
262 ($userName ne $effectiveUserName)
263 )
264 );
99 # final values for options 265 # final values for options
100 my %will; 266 my %will;
101 foreach(keys %must) { 267 foreach (keys %must) {
102 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 268 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
103 } 269 }
104 270
105 ##### sticky answers ##### 271 ##### sticky answers #####
106 272
107 if (not $submitAnswers and $will{showOldAnswers}) { 273 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
108 # do this only if new answers are NOT being submitted 274 # do this only if new answers are NOT being submitted
109 my %oldAnswers = decodeAnswers($problem->last_answer); 275 my %oldAnswers = decodeAnswers($problem->last_answer);
110 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 276 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
111 } 277 }
112 278
113 ##### translation ##### 279 ##### translation #####
114 280
281 $WeBWorK::timer0->continue("begin pg processing") if $timer0_ON;
115 my $pg = WeBWorK::PG->new( 282 my $pg = WeBWorK::PG->new(
116 $courseEnv, 283 $courseEnv,
117 $user, 284 $effectiveUser,
118 $r->param('key'), 285 $key,
119 $set, 286 $set,
120 $problem, 287 $problem,
121 $psvn, 288 $set->psvn, # FIXME: this field should be removed
122 $formFields, 289 $formFields,
123 { # translation options 290 { # translation options
124 displayMode => $displayMode, 291 displayMode => $displayMode,
125 showHints => $will{showHints}, 292 showHints => $will{showHints},
126 showSolutions => $will{showSolutions}, 293 showSolutions => $will{showSolutions},
127 refreshMath2img => $will{showHints} || $will{showSolutions}, 294 refreshMath2img => $will{showHints} || $will{showSolutions},
128 # try leaving processAnswers on all the time? 295 processAnswers => 1,
129 processAnswers => 1, #$submitAnswers ? 1 : 0,
130 }, 296 },
131 ); 297 );
132 298
299 $WeBWorK::timer0->continue("end pg processing") if $timer0_ON;
300 ##### fix hint/solution options #####
301
302 $can{showHints} &&= $pg->{flags}->{hintExists}
303 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
304 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
305
133 ##### store fields ##### 306 ##### store fields #####
134
135 $self->{cldb} = $cldb;
136 $self->{wwdb} = $wwdb;
137 $self->{authdb} = $authdb;
138
139 $self->{user} = $user;
140 $self->{set} = $set;
141 $self->{problem} = $problem;
142 $self->{permissionLevel} = $permissionLevel;
143
144 $self->{displayMode} = $displayMode;
145 $self->{redisplay} = $redisplay;
146 $self->{submitAnswers} = $submitAnswers;
147 $self->{formFields} = $formFields;
148 307
149 $self->{want} = \%want; 308 $self->{want} = \%want;
150 $self->{must} = \%must; 309 $self->{must} = \%must;
151 $self->{can} = \%can; 310 $self->{can} = \%can;
152 $self->{will} = \%will; 311 $self->{will} = \%will;
153
154 $self->{pg} = $pg; 312 $self->{pg} = $pg;
155} 313}
156 314
315#sub if_warnings($$) {
316# my ($self, $arg) = @_;
317# return 0 unless $self->{isOpen};
318# return $self->{pg}->{warnings} ne "";
319#}
320
321sub if_errors($$) {
322 my ($self, $arg) = @_;
323 return 0 unless $self->{isOpen};
324 return $self->{pg}->{flags}->{error_flag};
325}
326
157sub header { 327sub head {
158 my $self = shift; 328 my $self = shift;
159 329 return "" unless $self->{isOpen};
160 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 330 return $self->{pg}->{head_text} if $self->{pg}->{head_text};
331}
332
333sub options {
334 my $self = shift;
335 return join("",
336 CGI::start_form("POST", $self->{r}->uri),
337 $self->hidden_authen_fields,
338 CGI::hr(),
339 CGI::start_div({class=>"viewOptions"}),
340 $self->viewOptions(),
341 CGI::end_div(),
342 CGI::end_form()
343 );
161} 344}
162 345
163sub path { 346sub path {
164 my $self = shift; 347 my $self = shift;
165 my $args = $_[-1]; 348 my $args = $_[-1];
166 my $setName = $self->{set}->id; 349 my $setName = $self->{set}->set_id;
167 my $problemNumber = $self->{problem}->id; 350 my $problemNumber = $self->{problem}->problem_id;
168 351
169 my $ce = $self->{courseEnvironment}; 352 my $ce = $self->{ce};
170 my $root = $ce->{webworkURLs}->{root}; 353 my $root = $ce->{webworkURLs}->{root};
171 my $courseName = $ce->{courseName}; 354 my $courseName = $ce->{courseName};
172 return $self->pathMacro($args, 355 return $self->pathMacro($args,
173 "Home" => "$root", 356 "Home" => "$root",
174 $courseName => "$root/$courseName", 357 $courseName => "$root/$courseName",
177 ); 360 );
178} 361}
179 362
180sub siblings { 363sub siblings {
181 my $self = shift; 364 my $self = shift;
182 my $setName = $self->{set}->id; 365 my $setName = $self->{set}->set_id;
183 my $problemNumber = $self->{problem}->id; 366 my $problemNumber = $self->{problem}->problem_id;
184 367
185 my $ce = $self->{courseEnvironment}; 368 my $ce = $self->{ce};
369 my $db = $self->{db};
186 my $root = $ce->{webworkURLs}->{root}; 370 my $root = $ce->{webworkURLs}->{root};
187 my $courseName = $ce->{courseName}; 371 my $courseName = $ce->{courseName};
188
189 print CGI::strong("Problems"), CGI::br(); 372 print CGI::strong("Problems"), CGI::br();
190 373
191 my $wwdb = $self->{wwdb};
192 my $user = $self->{r}->param("user"); 374 my $effectiveUser = $self->{r}->param("effectiveUser");
193 my @problems; 375 my @problemIDs = $db->listUserProblems($effectiveUser, $setName);
194 push @problems, $wwdb->getProblem($user, $setName, $_)
195 foreach ($wwdb->getProblems($user, $setName));
196 foreach my $problem (sort { $a->id <=> $b->id } @problems) { 376 foreach my $problem (sort { $a <=> $b } @problemIDs) {
197 print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?" 377 print '&nbsp;&nbsp;'.CGI::a({-href=>"$root/$courseName/$setName/".$problem."/?"
198 . $self->url_authen_args}, "Problem ".$problem->id), CGI::br(); 378 . $self->url_authen_args . "&displayMode=" . $self->{displayMode}},
379 "Problem ".$problem), CGI::br();
199 } 380 }
381
382 return "";
200} 383}
201 384
202sub nav { 385sub nav {
386 $WeBWorK::timer0->continue("begin nav subroutine") if $timer0_ON;
203 my $self = shift; 387 my $self = shift;
204 my $args = $_[-1]; 388 my $args = $_[-1];
205 my $setName = $self->{set}->id; 389 my $setName = $self->{set}->set_id;
206 my $problemNumber = $self->{problem}->id; 390 my $problemNumber = $self->{problem}->problem_id;
207 391
208 my $ce = $self->{courseEnvironment}; 392 my $ce = $self->{ce};
393 my $db = $self->{db};
209 my $root = $ce->{webworkURLs}->{root}; 394 my $root = $ce->{webworkURLs}->{root};
210 my $courseName = $ce->{courseName}; 395 my $courseName = $ce->{courseName};
211 396
212 my $wwdb = $self->{wwdb}; 397 my $wwdb = $self->{wwdb};
213 my $user = $self->{r}->param("user"); 398 my $effectiveUser = $self->{r}->param("effectiveUser");
399 my $tail = "&displayMode=".$self->{displayMode};
214 400
215 my @links = ("Problem List" => "$root/$courseName/$setName"); 401 my @links = ("Problem List" , "$root/$courseName/$setName", "navProbList");
216 402
217 my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1); 403 my @problemIDs = $db->listUserProblems($effectiveUser, $setName);
218 my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1); 404 my ($prevID, $nextID);
405 foreach my $id (@problemIDs) {
406 $prevID = $id if $id < $problemNumber
407 and (not defined $prevID or $id > $prevID);
408 $nextID = $id if $id > $problemNumber
409 and (not defined $nextID or $id < $nextID);
410 }
219 unshift @links, "Previous Problem" => $prevProblem 411 unshift @links, "Previous Problem" , ($prevID
220 ? "$root/$courseName/$setName/".$prevProblem->id 412 ? "$root/$courseName/$setName/".$prevID
221 : ""; 413 : "") , "navPrev";
222 push @links, "Next Problem" => $nextProblem 414 push @links, "Next Problem" , ($nextID
223 ? "$root/$courseName/$setName/".$nextProblem->id 415 ? "$root/$courseName/$setName/".$nextID
224 : ""; 416 : "") , "navNext";
225 417
226 return $self->navMacro($args, @links); 418 my $result = $self->navMacro($args, $tail, @links);
419 $WeBWorK::timer0->continue("end nav subroutine") if $timer0_ON;
420 return $result;
227} 421}
228 422
229sub title { 423sub title {
230 my $self = shift; 424 my $self = shift;
231 my $setName = $self->{set}->id; 425 my $setName = $self->{set}->set_id;
232 my $problemNumber = $self->{problem}->id; 426 my $problemNumber = $self->{problem}->problem_id;
233 427
234 return "$setName : Problem $problemNumber"; 428 return "$setName : Problem $problemNumber";
235} 429}
236 430
237sub body { 431sub body {
238 my $self = shift; 432 my $self = shift;
239 433
240 #$self->prepare(@_); 434 return CGI::p(CGI::font({-color=>"red"}, "This problem is not available because the problem set that contains it is not yet open."))
435 unless $self->{isOpen};
241 436
242 # unpack some useful variables 437 # unpack some useful variables
243 my $r = $self->{r}; 438 my $r = $self->{r};
244 my $wwdb = $self->{wwdb}; 439 my $db = $self->{db};
440 my $ce = $self->{ce};
441 my $root = $ce->{webworkURLs}->{root};
442 my $courseName = $ce->{courseName};
245 my $set = $self->{set}; 443 my $set = $self->{set};
246 my $problem = $self->{problem}; 444 my $problem = $self->{problem};
445 my $editMode = $self->{editMode};
247 my $permissionLevel = $self->{permissionLevel}; 446 my $permissionLevel = $self->{permissionLevel};
248 my $submitAnswers = $self->{submitAnswers}; 447 my $submitAnswers = $self->{submitAnswers};
448 my $checkAnswers = $self->{checkAnswers};
449 my $previewAnswers = $self->{previewAnswers};
450 my %want = %{ $self->{want} };
451 my %can = %{ $self->{can} };
452 my %must = %{ $self->{must} };
249 my %will = %{ $self->{will} }; 453 my %will = %{ $self->{will} };
250 my $pg = $self->{pg}; 454 my $pg = $self->{pg};
251 455
456
457
458 #####create Editor link #####
459 # print editor link if the user is an instructor AND the file is not in temporary editing mode
460 my $editorLinkMessage = '';
461 # and ( (not defined($self->{editMode})) or $self->{editMode} eq 'savedFile') # FIXME is this needed?
462 if ($self->{permissionLevel}>=10 ) {
463 $editorLinkMessage = CGI::a({-href=>$ce->{webworkURLs}->{root}."/$courseName/instructor/pgProblemEditor/".
464 $set->set_id.'/'.$problem->problem_id.'?'.$self->url_authen_args},'Edit this problem');
465 }
252 ##### translation errors? ##### 466 ##### translation errors? #####
253 467
254 if ($pg->{flags}->{error_flag}) { 468 if ($pg->{flags}->{error_flag}) {
255 return translationError($pg->{errors}, $pg->{body_text}); 469 return $self->errorOutput($pg->{errors}, $pg->{body_text}.CGI::p($editorLinkMessage));
256 } 470 }
257 471
258 ##### answer processing ##### 472 ##### answer processing #####
259 473 $WeBWorK::timer0->continue("begin answer processing") if $timer0_ON;
260 # if answers were submitted: 474 # if answers were submitted:
475 my $scoreRecordedMessage;
261 if ($submitAnswers) { 476 if ($submitAnswers) {
477 # get a "pure" (unmerged) UserProblem to modify
478 # this will be undefined if the problem has not been assigned to this user
479 my $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
480 if (defined $pureProblem) {
262 # store answers in DB for sticky answers 481 # store answers in DB for sticky answers
263 my %answersToStore; 482 my %answersToStore;
264 my %answerHash = %{ $pg->{answers} }; 483 my %answerHash = %{ $pg->{answers} };
265 $answersToStore{$_} = $answerHash{$_}->{original_student_ans} 484 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!!
266 foreach (keys %answerHash); 485 foreach (keys %answerHash);
486 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating
487 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
488 # however we need to store them. Fortunately they are still in the input form.
489 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
490
491 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names);
492
493 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
494 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
267 my $answerString = encodeAnswers(%answersToStore, 495 my $answerString = encodeAnswers(%answersToStore,
268 @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }); 496 @answer_order);
497
498 # store last answer to database
269 $problem->last_answer($answerString); 499 $problem->last_answer($answerString);
500 $pureProblem->last_answer($answerString);
270 $wwdb->setProblem($problem); 501 $db->putUserProblem($pureProblem);
271 502
272 # store state in DB if it makes sense 503 # store state in DB if it makes sense
273 if ($will{recordAnswers}) { 504 if ($will{recordAnswers}) {
274 $problem->attempted(1);
275 $problem->status($pg->{state}->{recorded_score}); 505 $problem->status($pg->{state}->{recorded_score});
506 $problem->attempted(1);
276 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 507 $problem->num_correct($pg->{state}->{num_of_correct_ans});
277 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 508 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
278 $wwdb->setProblem($problem); 509 $pureProblem->status($pg->{state}->{recorded_score});
510 $pureProblem->attempted(1);
511 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
512 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
513 if ($db->putUserProblem($pureProblem)) {
514 $scoreRecordedMessage = "Your score was recorded.";
515 } else {
516 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
517 }
518 # write to the transaction log, just to make sure
519 writeLog($self->{ce}, "transaction",
520 $problem->problem_id."\t".
521 $problem->set_id."\t".
522 $problem->user_id."\t".
523 $problem->source_file."\t".
524 $problem->value."\t".
525 $problem->max_attempts."\t".
526 $problem->problem_seed."\t".
527 $pureProblem->status."\t".
528 $pureProblem->attempted."\t".
529 $pureProblem->last_answer."\t".
530 $pureProblem->num_correct."\t".
531 $pureProblem->num_incorrect
532 );
533 } else {
534 if (time < $set->open_date or time > $set->due_date) {
535 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed.";
536 } else {
537 $scoreRecordedMessage = "Your score was not recorded.";
538 }
539 }
540 } else {
541 $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you.";
279 } 542 }
280 } 543 }
281 544
545 # logging student answers
546
547 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
548 if ( defined($answer_log )) {
549 if ($submitAnswers ) {
550 my $answerString = "";
551 my %answerHash = %{ $pg->{answers} };
552 $answerString = $answerString . $answerHash{$_}->{original_student_ans}."\t"
553 foreach (sort keys %answerHash);
554 $answerString = '' unless defined($answerString); # insure string is defined.
555 writeCourseLog($self->{ce}, "answer_log",
556 join("",
557 '|', $problem->user_id,
558 '|', $problem->set_id,
559 '|', $problem->problem_id,
560 '|',"\t",
561 time(),"\t",
562 $answerString,
563 ),
564 );
565
566 }
567 }
568
569 $WeBWorK::timer0->continue("end answer processing") if $timer0_ON;
570
282 ##### output ##### 571 ##### output #####
283 572
573 print CGI::start_div({class=>"problemHeader"});
574
575 # custom message for editor
576 if ($permissionLevel >= 10 and defined $editMode) {
577 if ($editMode eq "temporaryFile") {
578 print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file));
579 } elsif ($editMode eq "savedFile") {
580 print CGI::p(CGI::i("Problem saved to: ", $problem->source_file));
581 }
582 }
583
284 # attempt summary 584 # attempt summary
285 if ($submitAnswers or $will{showCorrectAnswers}) { 585 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything.
586 # until after the due date
587 # do I need to check $wills{howCorrectAnswers} to make preflight work??
588 if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) {
286 # print this if user submitted answers OR requested correct answers 589 # print this if user submitted answers OR requested correct answers
287 print attemptResults($pg, $submitAnswers, $will{showCorrectAnswers}, 590
591 print $self->attemptResults($pg, 1,
592 $will{showCorrectAnswers},
288 $pg->{flags}->{showPartialCorrectAnswers}); 593 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
594 } elsif ($checkAnswers) {
595 # print this if user previewed answers
596 print "ANSWERS ONLY CHECKED -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br();
597 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
598 # show attempt answers
599 # show correct answers if asked
600 # show attempt results (correctness)
601 # show attempt previews
602 } elsif ($previewAnswers) {
603 # print this if user previewed answers
604 print "PREVIEW ONLY -- NOT RECORDED",CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
605 # show attempt answers
606 # don't show correct answers
607 # don't show attempt results (correctness)
608 # show attempt previews
289 } 609 }
610
611 print CGI::end_div();
612
613 print CGI::start_div({class=>"problem"});
614
615 # main form
616 print
617 CGI::startform("POST", $r->uri),
618 $self->hidden_authen_fields,
619 CGI::p($pg->{body_text}),
620 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})),
621 CGI::p(
622 ($can{showCorrectAnswers}
623 ? CGI::checkbox(
624 -name => "showCorrectAnswers",
625 -checked => $will{showCorrectAnswers},
626 -label => "Show correct answers",
627 ) ." "
628 : "" ),
629 ($can{showHints}
630 ? '<div style="color:red">'. CGI::checkbox(
631 -name => "showHints",
632 -checked => $will{showHints},
633 -label => "Show Hints",
634 ) . "</div> "
635 : " " ),
636 ($can{showSolutions}
637 ? CGI::checkbox(
638 -name => "showSolutions",
639 -checked => $will{showSolutions},
640 -label => "Show Solutions",
641 ) . " "
642 : " " ),CGI::br(),
643 CGI::submit(-name=>"previewAnswers",
644 -label=>"Preview Answers"),
645 ($can{recordAnswers}
646 ? CGI::submit(-name=>"submitAnswers",
647 -label=>"Submit Answers")
648 : ""),
649 ( $can{checkAnswers}
650 ? CGI::submit(-name=>"checkAnswers",
651 -label=>"Check Answers")
652 : ""),
653 );
654 print CGI::end_div();
655
656 print CGI::start_div({class=>"scoreSummary"});
290 657
291 # score summary 658 # score summary
292 my $attempts = $problem->num_correct + $problem->num_incorrect; 659 my $attempts = $problem->num_correct + $problem->num_incorrect;
293 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 660 my $attemptsNoun = $attempts != 1 ? "times" : "time";
294 my $lastScore = int ($problem->status * 100) . "%"; 661 my $lastScore = sprintf("%.0f%%", $problem->status * 100); # Round to whole number
295 my ($attemptsLeft, $attemptsLeftNoun); 662 my ($attemptsLeft, $attemptsLeftNoun);
296 if ($problem->max_attempts == -1) { 663 if ($problem->max_attempts == -1) {
297 # unlimited attempts 664 # unlimited attempts
298 $attemptsLeft = "unlimited"; 665 $attemptsLeft = "unlimited";
299 $attemptsLeftNoun = "attempts"; 666 $attemptsLeftNoun = "attempts";
300 } else { 667 } else {
301 $attemptsLeft = $problem->max_attempts - $attempts; 668 $attemptsLeft = $problem->max_attempts - $attempts;
302 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 669 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
303 } 670 }
671
672 my $setClosed = 0;
304 my $setClosedMessage; 673 my $setClosedMessage;
305 if (time < $set->open_date or time > $set->due_date) { 674 if (time < $set->open_date or time > $set->due_date) {
675 $setClosed = 1;
306 $setClosedMessage = "This problem set is closed."; 676 $setClosedMessage = "This problem set is closed.";
307 if ($permissionLevel > 0) { 677 if ($permissionLevel > 0) {
308 $setClosedMessage .= " Since you are a privileged user, additional attempts will be recorded."; 678 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
309 } else { 679 } else {
310 $setClosedMessage .= " Additional attempts will not be recorded."; 680 $setClosedMessage .= " Additional attempts will not be recorded.";
311 } 681 }
312 } 682 }
313 print CGI::p( 683 print CGI::p(
684 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
314 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), 685 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
315 $problem->attempted 686 $problem->attempted
316 ? "Your recorded score is $lastScore." . CGI::br() 687 ? "Your recorded score is $lastScore." . CGI::br()
317 : "", 688 : "",
318 "You have $attemptsLeft $attemptsLeftNoun remaining.", CGI::br(), 689 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
319 $setClosedMessage,
320 ); 690 );
321 691 print CGI::end_div();
322 # BY THE WAY.......... 692
323 # we have to figure out some way to tell the student if their NEW answer, 693 # save state for viewOptions
324 # on THIS attempt, has been recorded. however, this is decided in part by 694 print CGI::hidden(
325 # the grader, so is there any way for us to know? we can rule out several 695 -name => "showOldAnswers",
326 # cases where the answer is NOT being recorded, because of things decided 696 -value => $will{showOldAnswers}
327 # in &canRecordAnswers... 697 ),
328 698
699 CGI::hidden(
700 -name => "displayMode",
701 -value => $self->{displayMode}
702 );
703 print( CGI::hidden(
704 -name => 'editMode',
705 -value => $self->{editMode},
706 )
707 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
708 print( CGI::hidden(
709 -name => 'sourceFilePath',
710 -value => $self->{problem}->{source_file}
711 )) if defined($self->{problem}->{source_file});
712
713 # end of main form
329 print CGI::hr(); 714 print CGI::endform();
330 715
331 # main form 716
717 print CGI::start_div({class=>"problemFooter"});
718
719 # arguments for answer inspection button
720 my $prof_url = $ce->{webworkURLs}->{oldProf};
721 my $webworkURL = $ce->{webworkURLs}->{root};
722 my $cgi_url = $prof_url;
723 $cgi_url=~ s|/[^/]*$||; # clip profLogin.pl
724 my $authen_args = $self->url_authen_args();
725 my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
726
727 # print answer inspection button
728 if ($self->{permissionLevel} > 0) {
729 print "\n",
730 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
731 $self->hidden_authen_fields,"\n",
732 CGI::hidden(-name => 'course', -value=>$courseName), "\n",
733 CGI::hidden(-name => 'problemNumber', -value=>$problem->problem_id), "\n",
734 CGI::hidden(-name => 'setName', -value=>$problem->set_id), "\n",
735 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n",
736 CGI::p( {-align=>"left"},
737 CGI::submit(-name => 'action', -value=>'Show Past Answers')
738 ), "\n",
739 CGI::endform();
740 }
741
742 #print CGI::end_div();
743 #
744 #print CGI::start_div();
745
746 # arguments for feedback form
747 my $feedbackURL = "$root/$courseName/feedback/";
748
749 #print feedback form
332 print 750 print
333 CGI::startform("POST", $r->uri), 751 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
334 $self->hidden_authen_fields, 752 $self->hidden_authen_fields,"\n",
335 $self->viewOptions, 753 CGI::hidden("module", __PACKAGE__),"\n",
336 CGI::p(CGI::i($pg->{result}->{msg})), 754 CGI::hidden("set", $set->set_id),"\n",
337 CGI::p($pg->{body_text}), 755 CGI::hidden("problem", $problem->problem_id),"\n",
338 CGI::p(CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers")), 756 CGI::hidden("displayMode", $self->{displayMode}),"\n",
757 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n",
758 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
759 CGI::hidden("showHints", $will{showHints}),"\n",
760 CGI::hidden("showSolutions", $will{showSolutions}),"\n",
761 CGI::p({-align=>"left"},
762 CGI::submit(-name=>"feedbackForm", -label=>"Email instructor")
763 ),
339 CGI::endform(); 764 CGI::endform(),"\n";
765
766 # FIXME print editor link
767 print $editorLinkMessage; #empty unless it is appropriate to have an editor link.
768
769 print CGI::end_div();
770
771 # warning output
772 #if ($pg->{warnings} ne "") {
773 # print CGI::hr(), $self->warningOutput($pg->{warnings});
774 #}
340 775
341 # debugging stuff 776 # debugging stuff
777 if (0) {
342 #print 778 print
343 # hr(), 779 CGI::hr(),
344 # h2("debugging information"), 780 CGI::h2("debugging information"),
345 # h3("form fields"), 781 CGI::h3("form fields"),
346 # ref2string($formFields), 782 ref2string($self->{formFields}),
347 # h3("user object"), 783 CGI::h3("user object"),
348 # ref2string($user), 784 ref2string($self->{user}),
349 # h3("set object"), 785 CGI::h3("set object"),
350 # ref2string($set), 786 ref2string($set),
351 # h3("problem object"), 787 CGI::h3("problem object"),
352 # ref2string($problem), 788 ref2string($problem),
353 # h3("PG object"), 789 CGI::h3("PG object"),
354 # ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 790 ref2string($pg, {'WeBWorK::PG::Translator' => 1});
791 }
355 792
356 return ""; 793 return "";
357} 794}
358 795
359##### output utilities ##### 796##### output utilities #####
360 797
361# this is used by ProblemSet.pm too, so don't fuck it up
362sub translationError($$) {
363 my ($error, $details) = @_;
364 return
365 CGI::h2("Software Error"),
366 CGI::p(<<EOF),
367WeBWorK has encountered a software error while attempting to process this problem.
368It is likely that there is an error in the problem itself.
369If you are a student, contact your professor to have the error corrected.
370If you are a professor, please consut the error output below for more informaiton.
371EOF
372 CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
373 CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
374}
375
376sub attemptResults($$$) { 798sub attemptResults($$$$$$) {
799 my $self = shift;
377 my $pg = shift; 800 my $pg = shift;
378 my $showAttemptAnswers = shift; 801 my $showAttemptAnswers = shift;
379 my $showCorrectAnswers = shift; 802 my $showCorrectAnswers = shift;
380 my $showAttemptResults = $showAttemptAnswers && shift; 803 my $showAttemptResults = $showAttemptAnswers && shift;
804 my $showSummary = shift;
805 my $showAttemptPreview = shift || 0;
806 my $ce = $self->{ce};
381 my $problemResult = $pg->{result}; # the overall result of the problem 807 my $problemResult = $pg->{result}; # the overall result of the problem
382 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }; 808 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
383 809
810 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
811
812 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
813 my $imgGen = WeBWorK::PG::ImageGenerator->new(
814 tempDir => $ce->{webworkDirs}->{tmp},
815 latex => $ce->{externalPrograms}->{latex},
816 dvipng => $ce->{externalPrograms}->{dvipng},
817 useCache => 1,
818 cacheDir => $ce->{webworkDirs}->{equationCache},
819 cacheURL => $ce->{webworkURLs}->{equationCache},
820 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
821 );
822
823 my $header;
384 my $header = CGI::th("answer"); 824 #$header .= CGI::th("Part");
385 $header .= $showAttemptAnswers ? CGI::th("attempt") : ""; 825 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
826 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
386 $header .= $showCorrectAnswers ? CGI::th("correct") : ""; 827 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
387 $header .= $showAttemptResults ? CGI::th("result") : ""; 828 $header .= $showAttemptResults ? CGI::th("Result") : "";
388 $header .= $showAttemptAnswers ? CGI::th("messages") : ""; 829 $header .= $showMessages ? CGI::th("messages") : "";
389 my @tableRows = ( $header ); 830 my @tableRows = ( $header );
390 my $numCorrect; 831 my $numCorrect;
391 foreach my $name (@answerNames) { 832 foreach my $name (@answerNames) {
392 my $answerResult = $pg->{answers}->{$name}; 833 my $answerResult = $pg->{answers}->{$name};
393 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans 834 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
835 my $preview = ($showAttemptPreview
836 ? $self->previewAnswer($answerResult, $imgGen)
837 : "");
394 my $correctAnswer = $answerResult->{correct_ans}; 838 my $correctAnswer = $answerResult->{correct_ans};
395 my $answerScore = $answerResult->{score}; 839 my $answerScore = $answerResult->{score};
396 my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : ""; 840 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
397 841 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
398 $numCorrect += $answerScore > 0; 842 $numCorrect += $answerScore > 0;
399 my $resultString = $answerScore ? "correct" : "incorrect"; 843 my $resultString = $answerScore ? "correct" : "incorrect";
400 844
401 # get rid of the goofy prefix on the answer names (supposedly, the format 845 # get rid of the goofy prefix on the answer names (supposedly, the format
402 # of the answer names is changeable. this only fixes 846 # of the answer names is changeable. this only fixes it for "AnSwEr"
403 $name =~ s/^AnSwEr//; 847 #$name =~ s/^AnSwEr//;
404 848
849 my $row;
405 my $row = CGI::td($name); 850 #$row .= CGI::td($name);
406 $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : ""; 851 $row .= $showAttemptAnswers ? CGI::td(nbsp($studentAnswer)) : "";
852 $row .= $showAttemptPreview ? CGI::td(nbsp($preview)) : "";
407 $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : ""; 853 $row .= $showCorrectAnswers ? CGI::td(nbsp($correctAnswer)) : "";
408 $row .= $showAttemptResults ? CGI::td($resultString) : ""; 854 $row .= $showAttemptResults ? CGI::td(nbsp($resultString)) : "";
409 $row .= $answerMessage ? CGI::td($answerMessage) : ""; 855 $row .= $answerMessage ? CGI::td(nbsp($answerMessage)) : "";
410 push @tableRows, $row; 856 push @tableRows, $row;
411 } 857 }
412 858
859 # render equation images
860 $imgGen->render(refresh => 1);
861
413 my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions"; 862# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
414 my $scorePercent = int ($problemResult->{score} * 100) . "\%"; 863 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
864# FIXME -- I left the old code in in case we have to back out.
415 my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of " 865# my $summary = "On this attempt, you answered $numCorrect out of "
416 . scalar @answerNames . " correct, for a score of $scorePercent."; 866# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
417 return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary); 867 my $summary = "";
868 if (scalar @answerNames == 1) {
869 if ($numCorrect == scalar @answerNames) {
870 $summary .= "The above answer is correct.";
871 } else {
872 $summary .= "The above answer is NOT correct.";
873 }
874 } else {
875 if ($numCorrect == scalar @answerNames) {
876 $summary .= "All of the above answers are correct.";
877 } else {
878 $summary .= "At least one of the above answers is NOT correct.";
879 }
880 }
881 #FIXME there must be a better way to force refresh.
882 #my $refresh_warning = 'Hold down shift and click "refresh" or "reload" to update answer preview images.';
883 #return CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) .
884 #CGI::div({style=>'color:red; font-size:10pt'},$refresh_warning) .
885 #($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
886 # ... this has been fixed by equation caching.
887 return
888 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
889 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
418} 890}
419 891sub nbsp {
892 my $str = shift;
893 ($str =~/\S/) ? $str : '&nbsp;' ; # returns non-breaking space for empty strings
894 # tricky cases: $str =0;
895 # $str is a complex number
896}
420sub viewOptions($) { 897sub viewOptions($) {
421 my $self = shift; 898 my $self = shift;
422 my $displayMode = $self->{displayMode}; 899 my $displayMode = $self->{displayMode};
423 my %must = %{ $self->{must} }; 900 my %must = %{ $self->{must} };
424 my %can = %{ $self->{can} }; 901 my %can = %{ $self->{can} };
425 my %will = %{ $self->{will} }; 902 my %will = %{ $self->{will} };
426 903
427 my $optionLine; 904 my $optionLine;
428 $can{showOldAnswers} and $optionLine .= join "", 905 $can{showOldAnswers} and $optionLine .= join "",
429 "Show: &nbsp;", 906 "Show: &nbsp;".CGI::br(),
430 CGI::checkbox( 907 CGI::checkbox(
431 -name => "showOldAnswers", 908 -name => "showOldAnswers",
432 -checked => $will{showOldAnswers}, 909 -checked => $will{showOldAnswers},
433 -label => "Saved answers", 910 -label => "Saved answers",
434 ), "&nbsp;&nbsp;"; 911 ), "&nbsp;&nbsp;".CGI::br();
435 $can{showCorrectAnswers} and $optionLine .= join "", 912
436 CGI::checkbox(
437 -name => "showCorrectAnswers",
438 -checked => $will{showCorrectAnswers},
439 -label => "Correct answers",
440 ), "&nbsp;&nbsp;";
441 $can{showHints} and $optionLine .= join "",
442 CGI::checkbox(
443 -name => "showHints",
444 -checked => $will{showHints},
445 -label => "Hints",
446 ), "&nbsp;&nbsp;";
447 $can{showSolutions} and $optionLine .= join "",
448 CGI::checkbox(
449 -name => "showSolutions",
450 -checked => $will{showSolutions},
451 -label => "Solutions",
452 ), "&nbsp;&nbsp;";
453 $optionLine and $optionLine .= join "", CGI::br(); 913 $optionLine and $optionLine .= join "", CGI::br();
454 914
455 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"}, 915 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
456 "View equations as: &nbsp;", 916 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br(),
457 CGI::radio_group( 917 CGI::radio_group(
458 -name => "displayMode", 918 -name => "displayMode",
459 -values => ['plainText', 'formattedText', 'images'], 919 -values => ['plainText', 'formattedText', 'images'],
460 -default => $displayMode, 920 -default => $displayMode,
921 -linebreak=>'true',
461 -labels => { 922 -labels => {
462 plainText => "plain text", 923 plainText => "plain",
463 formattedText => "formatted text", 924 formattedText => "formatted",
464 images => "images", 925 images => "images",
465 } 926 }
466 ), CGI::br(), 927 ), CGI::br(),CGI::hr(),
467 $optionLine, 928 $optionLine,
468 CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"), 929 CGI::submit(-name=>"redisplay", -label=>"Save Options"),
469 ); 930 );
470} 931}
932
933sub previewAnswer($$) {
934 my ($self, $answerResult, $imgGen) = @_;
935 my $ce = $self->{ce};
936 my $effectiveUser = $self->{effectiveUser};
937 my $set = $self->{set};
938 my $problem = $self->{problem};
939 my $displayMode = $self->{displayMode};
940
941 # note: right now, we have to do things completely differently when we are
942 # rendering math from INSIDE the translator and from OUTSIDE the translator.
943 # so we'll just deal with each case explicitly here. there's some code
944 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
945
946 my $tex = $answerResult->{preview_latex_string};
947
948 return "" unless defined $tex and $tex ne "";
949
950 if ($displayMode eq "plainText") {
951 return $tex;
952 } elsif ($displayMode eq "formattedText") {
953 my $tthCommand = $ce->{externalPrograms}->{tth}
954 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
955 . "\\(".$tex."\\)\n"
956 . "END_OF_INPUT\n";
957
958 # call tth
959 my $result = `$tthCommand`;
960 if ($?) {
961 return "<b>[tth failed: $? $@]</b>";
962 }
963 return $result;
964 } elsif ($displayMode eq "images") {
965 ## how are we going to name this?
966 #my $targetPathCommon = "/m2i/"
967 # . $effectiveUser->user_id . "."
968 # . $set->set_id . "."
969 # . $problem->problem_id . "."
970 # . $answerResult->{ans_name} . ".png";
971 #
972 ## figure out where to put things
973 #my $wd = makeTempDirectory($ce->{courseDirs}->{html_temp}, "webwork-dvipng");
974 #my $latex = $ce->{externalPrograms}->{latex};
975 #my $dvipng = $ce->{externalPrograms}->{dvipng};
976 #my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon;
977 # # should use surePathToTmpFile, but we have to
978 # # isolate it from the problem enivronment first
979 #my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon;
980 #
981 ## call dvipng to generate a preview
982 #dvipng($wd, $latex, $dvipng, $tex, $targetPath);
983 #rmtree($wd, 0, 0);
984 #if (-e $targetPath) {
985 # return "<img src=\"$targetURL\" alt=\"$tex\" />";
986 #} else {
987 # return "<b>[math2img failed]</b>";
988 #}
989 $imgGen->add($answerResult->{preview_latex_string});
990
991 }
992}
993
994##### logging subroutine ####
995
996
471 997
472##### permission queries ##### 998##### permission queries #####
473 999
474# this stuff should be abstracted out into the permissions system 1000# this stuff should be abstracted out into the permissions system
475# however, the permission system only knows about things in the 1001# however, the permission system only knows about things in the
491 1017
492sub canRecordAnswers($$$$$) { 1018sub canRecordAnswers($$$$$) {
493 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_; 1019 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
494 my $permHigh = $permissionLevel > 0; 1020 my $permHigh = $permissionLevel > 0;
495 my $timeOK = time >= $openDate && time <= $dueDate; 1021 my $timeOK = time >= $openDate && time <= $dueDate;
496 my $attemptsOK = $attempts <= $maxAttempts; 1022 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
497 return $permHigh || ($timeOK && $attemptsOK); 1023 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
1024 return $recordAnswers;
1025}
1026
1027sub canCheckAnswers($$) {
1028 my ($permissionLevel, $answerDate) = @_;
1029 my $permHigh = $permissionLevel > 0;
1030 my $timeOK = time >= $answerDate;
1031 my $recordAnswers = $permHigh || $timeOK;
1032 return $recordAnswers;
498} 1033}
499 1034
500sub mustRecordAnswers($) { 1035sub mustRecordAnswers($) {
501 my ($permissionLevel) = @_; 1036 my ($permissionLevel) = @_;
502 return $permissionLevel == 0; 1037 return $permissionLevel == 0;

Legend:
Removed from v.555  
changed lines
  Added in v.1663

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9