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

Legend:
Removed from v.997  
changed lines
  Added in v.3963

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9