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

Diff of /trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

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

Legend:
Removed from v.756  
changed lines
  Added in v.2244

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9