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

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

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

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

Legend:
Removed from v.704  
changed lines
  Added in v.6416

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9