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

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9