[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 558 Revision 3973
1################################################################################ 1################################################################################
2# WeBWorK mod_perl (c) 2000-2002 WeBWorK Project 2# WeBWorK Online Homework Delivery System
3# $Id$ 3# Copyright © 2000-2006 The WeBWorK Project, http://openwebwork.sf.net/
4# $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.193 2006/01/24 23:27:02 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;
18use base qw(WeBWorK::ContentGenerator);
7 19
8=head1 NAME 20=head1 NAME
9 21
10WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem. 22WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
11 23
12=cut 24=cut
13 25
14use strict; 26use strict;
15use warnings; 27use warnings;
16use base qw(WeBWorK::ContentGenerator);
17use CGI qw(); 28use CGI qw();
29use File::Path qw(rmtree);
30use WeBWorK::Debug;
18use WeBWorK::Form; 31use WeBWorK::Form;
19use WeBWorK::PG; 32use WeBWorK::PG;
20use WeBWorK::Utils qw(ref2string encodeAnswers decodeAnswers); 33use WeBWorK::PG::ImageGenerator;
34use WeBWorK::PG::IO;
35use WeBWorK::Utils qw(readFile writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory);
36use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
37use URI::Escape;
21 38
39use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
40
22############################################################ 41################################################################################
42# CGI param interface to this module (up-to-date as of v1.153)
43################################################################################
44
45# Standard params:
23# 46#
24# user 47# user - user ID of real user
25# key 48# key - session key
49# effectiveUser - user ID of effective user
26# 50#
27# displayMode 51# Integration with PGProblemEditor:
28# showOldAnswers
29# showCorrectAnswers
30# showHints
31# showSolutions
32# 52#
33# AnSwEr# - answer blanks in problem 53# editMode - if set, indicates alternate problem source location.
54# can be "temporaryFile" or "savedFile".
34# 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#
35# redisplay - name of the "Redisplay Problem" button 74# redisplay - name of the "Redisplay Problem" button
36# submitAnswers - name of "Submit Answers" button 75# submitAnswers - name of "Submit Answers" button
37# 76# checkAnswers - name of the "Check Answers" button
77# previewAnswers - name of the "Preview Answers" button
78
38############################################################ 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################################################################################
39 379
40sub pre_header_initialize { 380sub pre_header_initialize {
41 my ($self, $setName, $problemNumber) = @_; 381 my ($self) = @_;
42 my $courseEnv = $self->{courseEnvironment};
43 my $r = $self->{r}; 382 my $r = $self->r;
383 my $ce = $r->ce;
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");
44 my $userName = $r->param('user'); 390 my $userName = $r->param('user');
391 my $effectiveUserName = $r->param('effectiveUser');
392 my $key = $r->param('key');
393 my $editMode = $r->param("editMode");
45 394
46 ##### database setup #####
47
48 my $cldb = WeBWorK::DB::Classlist->new($courseEnv);
49 my $wwdb = WeBWorK::DB::WW->new($courseEnv);
50 my $authdb = WeBWorK::DB::Auth->new($courseEnv);
51
52 my $user = $cldb->getUser($userName); 395 my $user = $db->getUser($userName); # checked
53 my $set = $wwdb->getSet($userName, $setName); 396 die "record for user $userName (real user) does not exist."
397 unless defined $user;
398
399 my $effectiveUser = $db->getUser($effectiveUserName); # checked
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);
424 $set = $db->getMergedSet($effectiveUserName, $setName);
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
54 my $problem = $wwdb->getProblem($userName, $setName, $problemNumber); 431 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
55 my $psvn = $wwdb->getPSVN($userName, $setName); 432
56 my $permissionLevel = $authdb->getPermissions($userName); 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
442 unless (defined $set) {
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 {
449 $set = global2user($userSetClass, $globalSet);
450 $set->psvn(0);
451 }
452 }
453
454 # if that is not yet defined obtain the global problem,
455 # convert it to a user problem, and add fake user data
456 unless (defined $problem) {
457 my $userProblemClass = $db->{problem_user}->{record};
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);
474 $problem->attempted(0);
475 $problem->last_answer("");
476 $problem->num_correct(0);
477 $problem->num_incorrect(0);
478 }
479 }
480
481 # now we're sure we have valid UserSet and UserProblem objects
482 # yay!
483
484 # now deal with possible editor overrides:
485
486 # if the caller is asking to override the source file, and
487 # editMode calls for a temporary file, do so
488 my $sourceFilePath = $r->param("sourceFilePath");
489 if (defined $sourceFilePath and
490 (not defined $editMode or $editMode eq "temporaryFile")) {
491 $problem->source_file($sourceFilePath);
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);
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
517 $self->{userName} = $userName;
518 $self->{effectiveUserName} = $effectiveUserName;
519 $self->{user} = $user;
520 $self->{effectiveUser} = $effectiveUser;
521 $self->{set} = $set;
522 $self->{problem} = $problem;
523 $self->{editMode} = $editMode;
57 524
58 ##### form processing ##### 525 ##### form processing #####
59 526
60 # 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)
61 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode}; 528 my $displayMode = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
62 my $redisplay = $r->param("redisplay"); 529 my $redisplay = $r->param("redisplay");
63 my $submitAnswers = $r->param("submitAnswers"); 530 my $submitAnswers = $r->param("submitAnswers");
531 my $checkAnswers = $r->param("checkAnswers");
532 my $previewAnswers = $r->param("previewAnswers");
64 533
65 # coerce form fields into CGI::Vars format
66 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; 534 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
67 535
536 $self->{displayMode} = $displayMode;
537 $self->{redisplay} = $redisplay;
538 $self->{submitAnswers} = $submitAnswers;
539 $self->{checkAnswers} = $checkAnswers;
540 $self->{previewAnswers} = $previewAnswers;
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};
549
68 ##### permissions ##### 550 ##### permissions #####
69 551
552 # are we allowed to view this problem?
553 $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets");
554 return unless $self->{isOpen};
555
70 # 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.
71 my %want = ( 563 my %want = (
72 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},
73 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers}, 565 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
74 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints}, 566 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints},
75 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions}, 567 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions},
76 recordAnswers => $r->param("recordAnswers") || 1, 568 recordAnswers => $submitAnswers,
569 checkAnswers => $checkAnswers,
570 getSubmitButton => 1,
77 ); 571 );
78 572
79 # are certain options enforced? 573 # are certain options enforced?
80 my %must = ( 574 my %must = (
81 showOldAnswers => 0, 575 showOldAnswers => 0,
82 showCorrectAnswers => 0, 576 showCorrectAnswers => 0,
83 showHints => 0, 577 showHints => 0,
84 showSolutions => 0, 578 showSolutions => 0,
85 recordAnswers => mustRecordAnswers($permissionLevel), 579 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
580 checkAnswers => 0,
581 getSubmitButton => 0,
86 ); 582 );
87 583
88 # 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);
89 my %can = ( 586 my %can = (
90 showOldAnswers => 1, 587 showOldAnswers => $self->can_showOldAnswers(@args),
91 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), 588 showCorrectAnswers => $self->can_showCorrectAnswers(@args),
92 showHints => 1, 589 showHints => $self->can_showHints(@args),
93 showSolutions => canShowSolutions($permissionLevel, $set->answer_date), 590 showSolutions => $self->can_showSolutions(@args),
94 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, 591 recordAnswers => $self->can_recordAnswers(@args, 0),
95 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), 592 checkAnswers => $self->can_checkAnswers(@args, $submitAnswers),
96 # num_correct+num_incorrect+1 -- as this happens before updating $problem 593 getSubmitButton => $self->can_recordAnswers(@args, $submitAnswers),
97 ); 594 );
98 595
99 # final values for options 596 # final values for options
100 my %will; 597 my %will;
101 foreach(keys %must) { 598 foreach (keys %must) {
102 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 599 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
103 } 600 }
104 601
105 ##### sticky answers ##### 602 ##### sticky answers #####
106 603
107 if (not $submitAnswers and $will{showOldAnswers}) { 604 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
108 # do this only if new answers are NOT being submitted 605 # do this only if new answers are NOT being submitted
109 my %oldAnswers = decodeAnswers($problem->last_answer); 606 my %oldAnswers = decodeAnswers($problem->last_answer);
110 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 607 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
111 } 608 }
112 609
113 ##### translation ##### 610 ##### translation #####
114 611
612 debug("begin pg processing");
115 my $pg = WeBWorK::PG->new( 613 my $pg = WeBWorK::PG->new(
116 $courseEnv, 614 $ce,
117 $user, 615 $effectiveUser,
118 $r->param('key'), 616 $key,
119 $set, 617 $set,
120 $problem, 618 $problem,
121 $psvn, 619 $set->psvn, # FIXME: this field should be removed
122 $formFields, 620 $formFields,
123 { # translation options 621 { # translation options
124 displayMode => $displayMode, 622 displayMode => $displayMode,
125 showHints => $will{showHints}, 623 showHints => $will{showHints},
126 showSolutions => $will{showSolutions}, 624 showSolutions => $will{showSolutions},
127 refreshMath2img => $will{showHints} || $will{showSolutions}, 625 refreshMath2img => $will{showHints} || $will{showSolutions},
128 # try leaving processAnswers on all the time? 626 processAnswers => 1,
129 processAnswers => 1, #$submitAnswers ? 1 : 0,
130 }, 627 },
131 ); 628 );
132 629
630 debug("end pg processing");
631
632 ##### fix hint/solution options #####
633
634 $can{showHints} &&= $pg->{flags}->{hintExists}
635 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
636 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
637
133 ##### store fields ##### 638 ##### store fields #####
134
135 $self->{cldb} = $cldb;
136 $self->{wwdb} = $wwdb;
137 $self->{authdb} = $authdb;
138
139 $self->{user} = $user;
140 $self->{set} = $set;
141 $self->{problem} = $problem;
142 $self->{permissionLevel} = $permissionLevel;
143
144 $self->{displayMode} = $displayMode;
145 $self->{redisplay} = $redisplay;
146 $self->{submitAnswers} = $submitAnswers;
147 $self->{formFields} = $formFields;
148 639
149 $self->{want} = \%want; 640 $self->{want} = \%want;
150 $self->{must} = \%must; 641 $self->{must} = \%must;
151 $self->{can} = \%can; 642 $self->{can} = \%can;
152 $self->{will} = \%will; 643 $self->{will} = \%will;
153
154 $self->{pg} = $pg; 644 $self->{pg} = $pg;
155}
156
157sub if_warnings($$) {
158 my ($self, $arg) = @_;
159 return $self->{pg}->{warnings} ne "";
160} 645}
161 646
162sub if_errors($$) { 647sub if_errors($$) {
163 my ($self, $arg) = @_; 648 my ($self, $arg) = @_;
649
650 if ($self->{isOpen}) {
164 return $self->{pg}->{flags}->{error_flag}; 651 return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
652 } else {
653 return !$arg;
654 }
165} 655}
166 656
167sub header { 657sub head {
168 my $self = shift; 658 my ($self) = @_;
169 659
660 return "" unless $self->{isOpen};
170 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 661 return $self->{pg}->{head_text} if $self->{pg}->{head_text};
171} 662}
172 663
173sub path { 664sub options {
174 my $self = shift; 665 my ($self) = @_;
175 my $args = $_[-1]; 666 #warn "doing options in Problem";
176 my $setName = $self->{set}->id;
177 my $problemNumber = $self->{problem}->id;
178 667
179 my $ce = $self->{courseEnvironment}; 668 # don't show options if we don't have anything to show
180 my $root = $ce->{webworkURLs}->{root}; 669 return "" if $self->{invalidSet} or $self->{invalidProblem};
181 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
182 return $self->pathMacro($args, 680 return $self->optionsMacro(
183 "Home" => "$root", 681 options_to_show => \@options_to_show,
184 $courseName => "$root/$courseName", 682 extra_params => ["editMode", "sourceFilePath"],
185 $setName => "$root/$courseName/$setName",
186 "Problem $problemNumber" => "",
187 ); 683 );
188} 684}
189 685
190sub siblings { 686sub siblings {
191 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");
192 my $setName = $self->{set}->id; 696 my $setID = $self->{set}->set_id;
193 my $problemNumber = $self->{problem}->id; 697 my $eUserID = $r->param("effectiveUser");
698 my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
194 699
195 my $ce = $self->{courseEnvironment}; 700 print CGI::start_div({class=>"info-box", id=>"fisheye"});
196 my $root = $ce->{webworkURLs}->{root}; 701 print CGI::h2("Problems");
197 my $courseName = $ce->{courseName}; 702 #print CGI::start_ul({class=>"LinksMenu"});
198 703 #print CGI::start_li();
199 print CGI::strong("Problems"), CGI::br(); 704 #print CGI::span({style=>"font-size:larger"}, "Problems");
200 705 print CGI::start_ul();
201 my $wwdb = $self->{wwdb}; 706
202 my $user = $self->{r}->param("user"); 707 foreach my $problemID (@problemIDs) {
203 my @problems; 708 my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
204 push @problems, $wwdb->getProblem($user, $setName, $_) 709 courseID => $courseID, setID => $setID, problemID => $problemID);
205 foreach ($wwdb->getProblems($user, $setName)); 710 print CGI::li(CGI::a( {href=>$self->systemLink($problemPage,
206 foreach my $problem (sort { $a->id <=> $b->id } @problems) { 711 params=>{ displayMode => $self->{displayMode},
207 print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?" 712 showOldAnswers => $self->{will}->{showOldAnswers}
208 . $self->url_authen_args}, "Problem ".$problem->id), CGI::br(); 713 })}, "Problem $problemID")
714 );
209 } 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 "";
210} 723}
211 724
212sub nav { 725sub nav {
213 my $self = shift; 726 my ($self, $args) = @_;
214 my $args = $_[-1]; 727 my $r = $self->r;
215 my $setName = $self->{set}->id; 728 my $db = $r->db;
216 my $problemNumber = $self->{problem}->id; 729 my $urlpath = $r->urlpath;
217 730
218 my $ce = $self->{courseEnvironment}; 731 my $courseID = $urlpath->arg("courseID");
219 my $root = $ce->{webworkURLs}->{root}; 732 my $setID = $self->{set}->set_id if !($self->{invalidSet});
220 my $courseName = $ce->{courseName}; 733 my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
734 my $eUserID = $r->param("effectiveUser");
221 735
222 my $wwdb = $self->{wwdb}; 736 my ($prevID, $nextID);
223 my $user = $self->{r}->param("user"); 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 }
224 747
225 my @links = ("Problem List" => "$root/$courseName/$setName"); 748 my @links;
226 749
227 my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1); 750 if ($prevID) {
228 my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1); 751 my $prevPage = $urlpath->newFromModule(__PACKAGE__,
229 unshift @links, "Previous Problem" => $prevProblem 752 courseID => $courseID, setID => $setID, problemID => $prevID);
230 ? "$root/$courseName/$setName/".$prevProblem->id 753 push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
231 : ""; 754 } else {
232 push @links, "Next Problem" => $nextProblem 755 push @links, "Previous Problem", "", "navPrev";
233 ? "$root/$courseName/$setName/".$nextProblem->id 756 }
234 : "";
235 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 {
765 push @links, "Next Problem", "", "navNext";
766 }
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};
236 return $self->navMacro($args, @links); 773 return $self->navMacro($args, $tail, @links);
237} 774}
238 775
239sub title { 776sub title {
240 my $self = shift; 777 my ($self) = @_;
241 my $setName = $self->{set}->id; 778
242 my $problemNumber = $self->{problem}->id; 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");
243 782
244 return "$setName : Problem $problemNumber"; 783 return "$setID: Problem $problemID";
245} 784}
246 785
247sub body { 786sub body {
248 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 }
249 800
250 #$self->prepare(@_); 801 if ($self->{invalidProblem}) {
251 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
806 unless ($self->{isOpen}) {
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 }
252 # unpack some useful variables 810 # unpack some useful variables
253 my $r = $self->{r};
254 my $wwdb = $self->{wwdb};
255 my $set = $self->{set}; 811 my $set = $self->{set};
256 my $problem = $self->{problem}; 812 my $problem = $self->{problem};
257 my $permissionLevel = $self->{permissionLevel}; 813 my $editMode = $self->{editMode};
258 my $submitAnswers = $self->{submitAnswers}; 814 my $submitAnswers = $self->{submitAnswers};
815 my $checkAnswers = $self->{checkAnswers};
816 my $previewAnswers = $self->{previewAnswers};
817 my %want = %{ $self->{want} };
818 my %can = %{ $self->{can} };
819 my %must = %{ $self->{must} };
259 my %will = %{ $self->{will} }; 820 my %will = %{ $self->{will} };
260 my $pg = $self->{pg}; 821 my $pg = $self->{pg};
261 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
262 ##### translation errors? ##### 840 ##### translation errors? #####
263 841
264 if ($pg->{flags}->{error_flag}) { 842 if ($pg->{flags}->{error_flag}) {
265 return translationError($pg->{errors}, $pg->{body_text}); 843 if ($authz->hasPermissions($user, "view_problem_debugging_info")) {
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 "";
266 } 850 }
267 851
268 ##### answer processing ##### 852 ##### answer processing #####
269 853 debug("begin answer processing");
270 # if answers were submitted: 854 # if answers were submitted:
855 my $scoreRecordedMessage;
856 my $pureProblem;
271 if ($submitAnswers) { 857 if ($submitAnswers) {
858 # get a "pure" (unmerged) UserProblem to modify
859 # this will be undefined if the problem has not been assigned to this user
860 $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
861 if (defined $pureProblem) {
272 # store answers in DB for sticky answers 862 # store answers in DB for sticky answers
273 my %answersToStore; 863 my %answersToStore;
274 my %answerHash = %{ $pg->{answers} }; 864 my %answerHash = %{ $pg->{answers} };
275 $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!!
276 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);
277 my $answerString = encodeAnswers(%answersToStore, 876 my $answerString = encodeAnswers(%answersToStore,
278 @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }); 877 @answer_order);
878
879 # store last answer to database
279 $problem->last_answer($answerString); 880 $problem->last_answer($answerString);
881 $pureProblem->last_answer($answerString);
280 $wwdb->setProblem($problem); 882 $db->putUserProblem($pureProblem);
281 883
282 # store state in DB if it makes sense 884 # store state in DB if it makes sense
283 if ($will{recordAnswers}) { 885 if ($will{recordAnswers}) {
284 $problem->attempted(1);
285 $problem->status($pg->{state}->{recorded_score}); 886 $problem->status($pg->{state}->{recorded_score});
887 $problem->attempted(1);
286 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 888 $problem->num_correct($pg->{state}->{num_of_correct_ans});
287 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 889 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
288 $wwdb->setProblem($problem); 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 }
899 # write to the transaction log, just to make sure
900 writeLog($self->{ce}, "transaction",
901 $problem->problem_id."\t".
902 $problem->set_id."\t".
903 $problem->user_id."\t".
904 $problem->source_file."\t".
905 $problem->value."\t".
906 $problem->max_attempts."\t".
907 $problem->problem_seed."\t".
908 $pureProblem->status."\t".
909 $pureProblem->attempted."\t".
910 $pureProblem->last_answer."\t".
911 $pureProblem->num_correct."\t".
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 }
289 } 920 }
921 } else {
922 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
290 } 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 ),
952 );
953
954 }
955 }
956
957 debug("end answer processing");
291 958
292 ##### 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 }
968 print CGI::start_div({class=>"problemHeader"});
293 969
970
971
294 # attempt summary 972 # attempt summary
295 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) ) {
296 # print this if user submitted answers OR requested correct answers 977 # print this if user submitted answers OR requested correct answers
297 print attemptResults($pg, $submitAnswers, $will{showCorrectAnswers}, 978
979 print $self->attemptResults($pg, 1,
980 $will{showCorrectAnswers},
298 $pg->{flags}->{showPartialCorrectAnswers}); 981 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
982 } elsif ($checkAnswers) {
983 # print this if user previewed answers
984 print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br();
985 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
986 # show attempt answers
987 # show correct answers if asked
988 # show attempt results (correctness)
989 # show attempt previews
990 } elsif ($previewAnswers) {
991 # print this if user previewed answers
992 print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
993 # show attempt answers
994 # don't show correct answers
995 # don't show attempt results (correctness)
996 # show attempt previews
997 }
998
999 print CGI::end_div();
1000
1001 # main form
1002 print CGI::startform("POST", $r->uri);
1003 print $self->hidden_authen_fields;
1004
1005 print CGI::start_div({class=>"problem"});
1006 print CGI::p($pg->{body_text});
1007 print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
1008 print $editorLink; # this is empty unless it is appropriate to have an editor link.
1009 print CGI::end_div();
1010
1011 print CGI::start_p();
1012
1013 if ($can{showCorrectAnswers}) {
1014 print CGI::checkbox(
1015 -name => "showCorrectAnswers",
1016 -checked => $will{showCorrectAnswers},
1017 -label => "Show correct answers",
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");
299 } 1052 }
1053 }
1054
1055 print CGI::end_p();
1056
1057 print CGI::start_div({class=>"scoreSummary"});
300 1058
301 # score summary 1059 # score summary
302 my $attempts = $problem->num_correct + $problem->num_incorrect; 1060 my $attempts = $problem->num_correct + $problem->num_incorrect;
303 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 1061 my $attemptsNoun = $attempts != 1 ? "times" : "time";
304 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
305 my ($attemptsLeft, $attemptsLeftNoun); 1064 my ($attemptsLeft, $attemptsLeftNoun);
306 if ($problem->max_attempts == -1) { 1065 if ($problem->max_attempts == -1) {
307 # unlimited attempts 1066 # unlimited attempts
308 $attemptsLeft = "unlimited"; 1067 $attemptsLeft = "unlimited";
309 $attemptsLeftNoun = "attempts"; 1068 $attemptsLeftNoun = "attempts";
310 } else { 1069 } else {
311 $attemptsLeft = $problem->max_attempts - $attempts; 1070 $attemptsLeft = $problem->max_attempts - $attempts;
312 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 1071 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
313 } 1072 }
1073
1074 my $setClosed = 0;
314 my $setClosedMessage; 1075 my $setClosedMessage;
315 if (time < $set->open_date or time > $set->due_date) { 1076 if (before($set->open_date) or after($set->due_date)) {
1077 $setClosed = 1;
1078 if (before($set->open_date)) {
1079 $setClosedMessage = "This homework set is not yet open.";
1080 } elsif (after($set->due_date)) {
316 $setClosedMessage = "This problem set is closed."; 1081 $setClosedMessage = "This homework set is closed.";
317 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")) {
318 $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.";
319 } else { 1089 # } else {
320 $setClosedMessage .= " Additional attempts will not be recorded."; 1090 # $setClosedMessage .= " Additional attempts will not be recorded.";
321 } 1091 # }
322 } 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.)";
323 print CGI::p( 1095 print CGI::p(
1096 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
324 "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():'',
325 $problem->attempted 1099 $problem->attempted
326 ? "Your recorded score is $lastScore." . CGI::br() 1100 ? "Your overall recorded score is $lastScore. $notCountedMessage" . CGI::br()
327 : "", 1101 : "",
328 "You have $attemptsLeft $attemptsLeftNoun remaining.", CGI::br(), 1102 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
329 $setClosedMessage, 1103 );
1104 }else {
1105 print CGI::p($pg->{state}->{state_summary_msg});
1106 }
1107 print CGI::end_div();
1108
1109 # save state for viewOptions
1110 print CGI::hidden(
1111 -name => "showOldAnswers",
1112 -value => $will{showOldAnswers}
1113 ),
1114
1115 CGI::hidden(
1116 -name => "displayMode",
1117 -value => $self->{displayMode}
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
1135 print CGI::endform();
1136
1137 print CGI::start_div({class=>"problemFooter"});
1138
1139 ## arguments for answer inspection button
1140 #my $prof_url = $ce->{webworkURLs}->{oldProf};
1141 #my $webworkURL = $ce->{webworkURLs}->{root};
1142 #my $cgi_url = $prof_url;
1143 #$cgi_url=~ s|/[^/]*$||; # clip profLogin.pl
1144 #my $authen_args = $self->url_authen_args();
1145 #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
1146
1147 my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
1148 courseID => $courseName);
1149 my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
1150
1151 # print answer inspection button
1152 if ($authz->hasPermissions($user, "view_answers")) {
1153 print "\n",
1154 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
1155 $self->hidden_authen_fields,"\n",
1156 CGI::hidden(-name => 'courseID', -value=>$courseName), "\n",
1157 CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
1158 CGI::hidden(-name => 'setID', -value=>$problem->set_id), "\n",
1159 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n",
1160 CGI::p( {-align=>"left"},
1161 CGI::submit(-name => 'action', -value=>'Show Past Answers')
1162 ), "\n",
1163 CGI::endform();
1164 }
1165
1166 ## feedback form url
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 #
1171 ##print feedback form
1172 #print
1173 # CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
1174 # $self->hidden_authen_fields,"\n",
1175 # CGI::hidden("module", __PACKAGE__),"\n",
1176 # CGI::hidden("set", $set->set_id),"\n",
1177 # CGI::hidden("problem", $problem->problem_id),"\n",
1178 # CGI::hidden("displayMode", $self->{displayMode}),"\n",
1179 # CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n",
1180 # CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
1181 # CGI::hidden("showHints", $will{showHints}),"\n",
1182 # CGI::hidden("showSolutions", $will{showSolutions}),"\n",
1183 # CGI::p({-align=>"left"},
1184 # CGI::submit(-name=>"feedbackForm", -label=>"Email instructor")
1185 # ),
1186 # CGI::endform(),"\n";
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},
330 ); 1197 );
331 1198
332 # BY THE WAY..........
333 # we have to figure out some way to tell the student if their NEW answer,
334 # on THIS attempt, has been recorded. however, this is decided in part by
335 # the grader, so is there any way for us to know? we can rule out several
336 # cases where the answer is NOT being recorded, because of things decided
337 # in &canRecordAnswers...
338
339 print CGI::hr(); 1199 print CGI::end_div();
340
341 # main form
342 print
343 CGI::startform("POST", $r->uri),
344 $self->hidden_authen_fields,
345 $self->viewOptions,
346 CGI::p(CGI::i($pg->{result}->{msg})),
347 CGI::p($pg->{body_text}),
348 CGI::p(CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers")),
349 CGI::endform();
350
351 # warning output
352 if ($pg->{warnings} ne "") {
353 print CGI::hr(), warningOutput($pg->{warnings});
354 }
355 1200
356 # debugging stuff 1201 # debugging stuff
1202 if (0) {
357 #print 1203 print
358 # hr(), 1204 CGI::hr(),
359 # h2("debugging information"), 1205 CGI::h2("debugging information"),
360 # h3("form fields"), 1206 CGI::h3("form fields"),
361 # ref2string($formFields), 1207 ref2string($self->{formFields}),
362 # h3("user object"), 1208 CGI::h3("user object"),
363 # ref2string($user), 1209 ref2string($self->{user}),
364 # h3("set object"), 1210 CGI::h3("set object"),
365 # ref2string($set), 1211 ref2string($set),
366 # h3("problem object"), 1212 CGI::h3("problem object"),
367 # ref2string($problem), 1213 ref2string($problem),
368 # h3("PG object"), 1214 CGI::h3("PG object"),
369 # ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 1215 ref2string($pg, {'WeBWorK::PG::Translator' => 1});
1216 }
370 1217
371 return ""; 1218 return "";
372} 1219}
373 1220
374##### output utilities #####
375
376# this is used by ProblemSet.pm too, so don't fuck it up
377sub translationError($$) {
378 my ($error, $details) = @_;
379 return
380 CGI::h2("Software Error"),
381 CGI::p(<<EOF),
382WeBWorK has encountered a software error while attempting to process this problem.
383It is likely that there is an error in the problem itself.
384If you are a student, contact your professor to have the error corrected.
385If you are a professor, please consut the error output below for more informaiton.
386EOF
387 CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
388 CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
389}
390
391# this is used by ProblemSet.pm too, so don't fuck it up
392sub warningOutput($) {
393 my $warnings = shift;
394
395 return
396 CGI::h2("Software Warnings"),
397 CGI::p(<<EOF),
398WeBWorK has encountered warnings while attempting to process this problem.
399It is likely that this indicates an error or ambiguity in the problem itself.
400If you are a student, contact your professor to have the problem corrected.
401If you are a professor, please consut the error output below for more informaiton.
402EOF
403 CGI::h3("Warning messages"),
404 CGI::blockquote(CGI::pre($warnings)),
405 ;
406}
407
408sub attemptResults($$$) {
409 my $pg = shift;
410 my $showAttemptAnswers = shift;
411 my $showCorrectAnswers = shift;
412 my $showAttemptResults = $showAttemptAnswers && shift;
413 my $problemResult = $pg->{result}; # the overall result of the problem
414 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
415
416 my $header = CGI::th("answer");
417 $header .= $showAttemptAnswers ? CGI::th("attempt") : "";
418 $header .= $showCorrectAnswers ? CGI::th("correct") : "";
419 $header .= $showAttemptResults ? CGI::th("result") : "";
420 $header .= $showAttemptAnswers ? CGI::th("messages") : "";
421 my @tableRows = ( $header );
422 my $numCorrect;
423 foreach my $name (@answerNames) {
424 my $answerResult = $pg->{answers}->{$name};
425 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
426 my $correctAnswer = $answerResult->{correct_ans};
427 my $answerScore = $answerResult->{score};
428 my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : "";
429
430 $numCorrect += $answerScore > 0;
431 my $resultString = $answerScore ? "correct" : "incorrect";
432
433 # get rid of the goofy prefix on the answer names (supposedly, the format
434 # of the answer names is changeable. this only fixes
435 $name =~ s/^AnSwEr//;
436
437 my $row = CGI::td($name);
438 $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : "";
439 $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : "";
440 $row .= $showAttemptResults ? CGI::td($resultString) : "";
441 $row .= $answerMessage ? CGI::td($answerMessage) : "";
442 push @tableRows, $row;
443 }
444
445 my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions";
446 my $scorePercent = int ($problemResult->{score} * 100) . "\%";
447 my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of "
448 . scalar @answerNames . " correct, for a score of $scorePercent.";
449 return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary);
450}
451
452sub viewOptions($) {
453 my $self = shift;
454 my $displayMode = $self->{displayMode};
455 my %must = %{ $self->{must} };
456 my %can = %{ $self->{can} };
457 my %will = %{ $self->{will} };
458
459 my $optionLine;
460 $can{showOldAnswers} and $optionLine .= join "",
461 "Show: &nbsp;",
462 CGI::checkbox(
463 -name => "showOldAnswers",
464 -checked => $will{showOldAnswers},
465 -label => "Saved answers",
466 ), "&nbsp;&nbsp;";
467 $can{showCorrectAnswers} and $optionLine .= join "",
468 CGI::checkbox(
469 -name => "showCorrectAnswers",
470 -checked => $will{showCorrectAnswers},
471 -label => "Correct answers",
472 ), "&nbsp;&nbsp;";
473 $can{showHints} and $optionLine .= join "",
474 CGI::checkbox(
475 -name => "showHints",
476 -checked => $will{showHints},
477 -label => "Hints",
478 ), "&nbsp;&nbsp;";
479 $can{showSolutions} and $optionLine .= join "",
480 CGI::checkbox(
481 -name => "showSolutions",
482 -checked => $will{showSolutions},
483 -label => "Solutions",
484 ), "&nbsp;&nbsp;";
485 $optionLine and $optionLine .= join "", CGI::br();
486
487 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"},
488 "View equations as: &nbsp;",
489 CGI::radio_group(
490 -name => "displayMode",
491 -values => ['plainText', 'formattedText', 'images'],
492 -default => $displayMode,
493 -labels => {
494 plainText => "plain text",
495 formattedText => "formatted text",
496 images => "images",
497 }
498 ), CGI::br(),
499 $optionLine,
500 CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"),
501 );
502}
503
504##### permission queries #####
505
506# this stuff should be abstracted out into the permissions system
507# however, the permission system only knows about things in the
508# course environment and the username. hmmm...
509
510# also, i should fix these so that they have a consistent calling
511# format -- perhaps:
512# canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
513
514sub canShowCorrectAnswers($$) {
515 my ($permissionLevel, $answerDate) = @_;
516 return $permissionLevel > 0 || time > $answerDate;
517}
518
519sub canShowSolutions($$) {
520 my ($permissionLevel, $answerDate) = @_;
521 return canShowCorrectAnswers($permissionLevel, $answerDate);
522}
523
524sub canRecordAnswers($$$$$) {
525 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
526 my $permHigh = $permissionLevel > 0;
527 my $timeOK = time >= $openDate && time <= $dueDate;
528 my $attemptsOK = $attempts <= $maxAttempts;
529 return $permHigh || ($timeOK && $attemptsOK);
530}
531
532sub mustRecordAnswers($) {
533 my ($permissionLevel) = @_;
534 return $permissionLevel == 0;
535}
536
5371; 12211;

Legend:
Removed from v.558  
changed lines
  Added in v.3973

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9