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

Legend:
Removed from v.2244  
changed lines
  Added in v.6274

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9