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

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

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

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

Legend:
Removed from v.1591  
changed lines
  Added in v.3653

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9