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

Legend:
Removed from v.906  
changed lines
  Added in v.2020

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9