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

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

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

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

Legend:
Removed from v.903  
changed lines
  Added in v.5644

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9