[system] / branches / gage_dev / webwork2 / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

Diff of /branches/gage_dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.1223  
changed lines
  Added in v.2507

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9