[system] / branches / gage_dev / webwork2 / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

Diff of /branches/gage_dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

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

Legend:
Removed from v.719  
changed lines
  Added in v.2011

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9