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

Legend:
Removed from v.718  
changed lines
  Added in v.2421

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9