[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

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

Legend:
Removed from v.737  
changed lines
  Added in v.6299

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9