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

Legend:
Removed from v.1326  
changed lines
  Added in v.2213

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9