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

Legend:
Removed from v.1128  
changed lines
  Added in v.1955

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9