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

Legend:
Removed from v.1040  
changed lines
  Added in v.2099

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9