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

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9