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

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

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

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

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9