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

Legend:
Removed from v.1016  
changed lines
  Added in v.2998

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9