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

Diff of /trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

Revision 2398 Revision 2735
1################################################################################ 1################################################################################
2# WeBWorK Online Homework Delivery System 2# WeBWorK Online Homework Delivery System
3# Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/ 3# Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
4# $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.144 2004/06/18 14:11:28 toenail Exp $ 4# $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.159 2004/08/26 01:34:30 jj Exp $
5# 5#
6# This program is free software; you can redistribute it and/or modify it under 6# This program is free software; you can redistribute it and/or modify it under
7# the terms of either: (a) the GNU General Public License as published by the 7# the terms of either: (a) the GNU General Public License as published by the
8# Free Software Foundation; either version 2, or (at your option) any later 8# Free Software Foundation; either version 2, or (at your option) any later
9# version, or (b) the "Artistic License" which comes with this package. 9# version, or (b) the "Artistic License" which comes with this package.
35use WeBWorK::DB::Utils qw(global2user user2global findDefaults); 35use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
36use WeBWorK::Timing; 36use WeBWorK::Timing;
37 37
38use WeBWorK::Utils::Tasks qw(fake_set fake_problem); 38use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
39 39
40############################################################ 40################################################################################
41# CGI param interface to this module (up-to-date as of v1.153)
42################################################################################
43
44# Standard params:
41# 45#
42# user 46# user - user ID of real user
43# effectiveUser 47# key - session key
44# key 48# effectiveUser - user ID of effective user
45# 49#
46# editMode 50# Integration with PGProblemEditor:
47# sourceFilePath - path to file to be editted
48# problemSeed - problem seed for editted problem
49#
50# displayMode - type of display (ie formatted, images, asciimath, etc)
51#
52# showOldAnswers
53# showCorrectAnswers
54# showHints
55# showSolutions
56# 51#
57# AnSwEr# - answer blanks in problem 52# editMode - if set, indicates alternate problem source location.
53# can be "temporaryFile" or "savedFile".
58# 54#
59# redisplay - name of the "Redisplay Problem" button 55# sourceFilePath - path to file to be edited
60# submitAnswers - name of "Submit Answers" button 56# problemSeed - force problem seed to value
61# checkAnswers - name of the "Check Answers" button 57# success - success message to display
62# previewAnswers - name of the "Preview Answers" button 58# failure - failure message to display
63#
64# success - success message (from PGProblemEditor)
65# failure - failure message (from PGProblemEditor)
66# 59#
60# Rendering options:
61#
62# displayMode - name of display mode to use
63#
64# showOldAnswers - request that last entered answer be shown (if allowed)
65# showCorrectAnswers - request that correct answers be shown (if allowed)
66# showHints - request that hints be shown (if allowed)
67# showSolutions - request that solutions be shown (if allowed)
68#
69# Problem interaction:
70#
71# AnSwEr# - answer blanks in problem
72#
73# redisplay - name of the "Redisplay Problem" button
74# submitAnswers - name of "Submit Answers" button
75# checkAnswers - name of the "Check Answers" button
76# previewAnswers - name of the "Preview Answers" button
77
67############################################################ 78################################################################################
79# "can" methods
80################################################################################
68 81
82# Subroutines to determine if a user "can" perform an action. Each subroutine is
83# called with the following arguments:
84#
85# ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem)
86
87sub can_showOldAnswers {
88 #my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
89
90 return 1;
91}
92
93sub can_showCorrectAnswers {
94 my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
95 my $authz = $self->r->authz;
96
97 return
98 after($Set->answer_date)
99 ||
100 $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")
101 ;
102}
103
104sub can_showHints {
105 #my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
106
107 return 1;
108}
109
110sub can_showSolutions {
111 my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
112 my $authz = $self->r->authz;
113
114 return
115 after($Set->answer_date)
116 ||
117 $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date")
118 ;
119}
120
121sub can_recordAnswers {
122 my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
123 my $authz = $self->r->authz;
124 my $thisAttempt = $submitAnswers ? 1 : 0;
125 if ($User->user_id ne $EffectiveUser->user_id) {
126 return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
127 }
128 if (before($Set->open_date)) {
129 return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
130 } elsif (between($Set->open_date, $Set->due_date)) {
131 my $max_attempts = $Problem->max_attempts;
132 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
133 if ($max_attempts == -1 or $attempts_used < $max_attempts) {
134 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts");
135 } else {
136 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts");
137 }
138 } elsif (between($Set->due_date, $Set->answer_date)) {
139 return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
140 } elsif (after($Set->answer_date)) {
141 return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
142 }
143}
144
145sub can_checkAnswers {
146 my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
147 my $authz = $self->r->authz;
148 my $thisAttempt = $submitAnswers ? 1 : 0;
149
150 if (before($Set->open_date)) {
151 return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
152 } elsif (between($Set->open_date, $Set->due_date)) {
153 my $max_attempts = $Problem->max_attempts;
154 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
155 if ($max_attempts == -1 or $attempts_used < $max_attempts) {
156 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts");
157 } else {
158 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts");
159 }
160 } elsif (between($Set->due_date, $Set->answer_date)) {
161 return $authz->hasPermissions($User->user_id, "check_answers_after_due_date");
162 } elsif (after($Set->answer_date)) {
163 return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date");
164 }
165}
166
167# Helper functions for calculating times
168sub before { return time <= $_[0] }
169sub after { return time >= $_[0] }
170sub between { my $t = time; return $t > $_[0] && $t < $_[1] }
171
172################################################################################
173# output utilities
174################################################################################
175
176sub attemptResults {
177 my $self = shift;
178 my $pg = shift;
179 my $showAttemptAnswers = shift;
180 my $showCorrectAnswers = shift;
181 my $showAttemptResults = $showAttemptAnswers && shift;
182 my $showSummary = shift;
183 my $showAttemptPreview = shift || 0;
184
185 my $ce = $self->r->ce;
186
187 my $problemResult = $pg->{result}; # the overall result of the problem
188 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
189
190 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
191
192 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
193
194 # to make grabbing these options easier, we'll pull them out now...
195 my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
196
197 my $imgGen = WeBWorK::PG::ImageGenerator->new(
198 tempDir => $ce->{webworkDirs}->{tmp},
199 latex => $ce->{externalPrograms}->{latex},
200 dvipng => $ce->{externalPrograms}->{dvipng},
201 useCache => 1,
202 cacheDir => $ce->{webworkDirs}->{equationCache},
203 cacheURL => $ce->{webworkURLs}->{equationCache},
204 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
205 dvipng_align => $imagesModeOptions{dvipng_align},
206 dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
207 );
208
209 my $header;
210 #$header .= CGI::th("Part");
211 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
212 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
213 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
214 $header .= $showAttemptResults ? CGI::th("Result") : "";
215 $header .= $showMessages ? CGI::th("Messages") : "";
216 my @tableRows = ( $header );
217 my $numCorrect = 0;
218 foreach my $name (@answerNames) {
219 my $answerResult = $pg->{answers}->{$name};
220 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
221 my $preview = ($showAttemptPreview
222 ? $self->previewAnswer($answerResult, $imgGen)
223 : "");
224 my $correctAnswer = $answerResult->{correct_ans};
225 my $answerScore = $answerResult->{score};
226 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
227 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
228 $numCorrect += $answerScore > 0;
229 my $resultString = $answerScore == 1 ? "correct" : "incorrect";
230
231 # get rid of the goofy prefix on the answer names (supposedly, the format
232 # of the answer names is changeable. this only fixes it for "AnSwEr"
233 #$name =~ s/^AnSwEr//;
234
235 my $row;
236 #$row .= CGI::td($name);
237 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
238 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : "";
239 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
240 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : "";
241 $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : "";
242 push @tableRows, $row;
243 }
244
245 # render equation images
246 $imgGen->render(refresh => 1);
247
248# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
249 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
250# FIXME -- I left the old code in in case we have to back out.
251# my $summary = "On this attempt, you answered $numCorrect out of "
252# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
253 my $summary = "";
254 if (scalar @answerNames == 1) {
255 if ($numCorrect == scalar @answerNames) {
256 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
257 } else {
258 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
259 }
260 } else {
261 if ($numCorrect == scalar @answerNames) {
262 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
263 } else {
264 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
265 }
266 }
267
268 return
269 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
270 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
271}
272
273sub viewOptions {
274 my ($self) = @_;
275 my $ce = $self->r->ce;
276
277 # don't show options if we don't have anything to show
278 return if $self->{invalidSet} or $self->{invalidProblem};
279 return unless $self->{isOpen};
280
281 my $displayMode = $self->{displayMode};
282 my %must = %{ $self->{must} };
283 my %can = %{ $self->{can} };
284 my %will = %{ $self->{will} };
285
286 my $optionLine;
287 $can{showOldAnswers} and $optionLine .= join "",
288 "Show: &nbsp;".CGI::br(),
289 CGI::checkbox(
290 -name => "showOldAnswers",
291 -checked => $will{showOldAnswers},
292 -label => "Saved answers",
293 ), "&nbsp;&nbsp;".CGI::br();
294
295 $optionLine and $optionLine .= join "", CGI::br();
296
297 my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
298 my @active_modes = grep { exists $display_modes{$_} }
299 @{$ce->{pg}->{displayModes}};
300 my $modeLine = (scalar(@active_modes) > 1) ?
301 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
302 CGI::radio_group(
303 -name => "displayMode",
304 -values => \@active_modes,
305 -default => $displayMode,
306 -linebreak=>'true',
307 -labels => {
308 plainText => "plain",
309 formattedText => "formatted",
310 images => "images",
311 jsMath => "jsMath",
312 asciimath => "asciimath",
313 },
314 ). CGI::br().CGI::hr() : '';
315
316 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
317 $modeLine,
318 $optionLine,
319 CGI::submit(-name=>"redisplay", -label=>"Apply Options"),
320 );
321}
322
323sub previewAnswer {
324 my ($self, $answerResult, $imgGen) = @_;
325 my $ce = $self->r->ce;
326 my $effectiveUser = $self->{effectiveUser};
327 my $set = $self->{set};
328 my $problem = $self->{problem};
329 my $displayMode = $self->{displayMode};
330
331 # note: right now, we have to do things completely differently when we are
332 # rendering math from INSIDE the translator and from OUTSIDE the translator.
333 # so we'll just deal with each case explicitly here. there's some code
334 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
335
336 my $tex = $answerResult->{preview_latex_string};
337
338 return "" unless defined $tex and $tex ne "";
339
340 if ($displayMode eq "plainText") {
341 return $tex;
342 } elsif ($displayMode eq "formattedText") {
343 my $tthCommand = $ce->{externalPrograms}->{tth}
344 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
345 . "\\(".$tex."\\)\n"
346 . "END_OF_INPUT\n";
347
348 # call tth
349 my $result = `$tthCommand`;
350 if ($?) {
351 return "<b>[tth failed: $? $@]</b>";
352 } else {
353 return $result;
354 }
355 } elsif ($displayMode eq "images") {
356 $imgGen->add($tex);
357 } elsif ($displayMode eq "jsMath") {
358 return '<DIV CLASS="math">'.$tex.'</DIV>' ;
359 }
360}
361
362################################################################################
363# Template escape implementations
364################################################################################
69 365
70sub pre_header_initialize { 366sub pre_header_initialize {
71 my ($self) = @_; 367 my ($self) = @_;
72 my $r = $self->r; 368 my $r = $self->r;
73 my $ce = $r->ce; 369 my $ce = $r->ce;
133 my $userProblemClass = $db->{problem_user}->{record}; 429 my $userProblemClass = $db->{problem_user}->{record};
134 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked 430 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
135 # if the global problem doesn't exist either, bail! 431 # if the global problem doesn't exist either, bail!
136 if(not defined $globalProblem) { 432 if(not defined $globalProblem) {
137 my $sourceFilePath = $r->param("sourceFilePath"); 433 my $sourceFilePath = $r->param("sourceFilePath");
434 # These are problems from setmaker. If declared invalid, they won't come up
138 $self->{invalidProblem} = $self->{invalidSet} = 1 if defined $sourceFilePath; 435 $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
139# die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath; 436# die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
140 $problem = fake_problem($db); 437 $problem = fake_problem($db);
141 $problem->problem_id(1); 438 $problem->problem_id(1);
142 $problem->source_file($sourceFilePath); 439 $problem->source_file($sourceFilePath);
143 $problem->user_id($effectiveUserName); 440 $problem->user_id($effectiveUserName);
231 return if $self->{invalidSet} || $self->{invalidProblem}; 528 return if $self->{invalidSet} || $self->{invalidProblem};
232 529
233 ##### permissions ##### 530 ##### permissions #####
234 531
235 # are we allowed to view this problem? 532 # are we allowed to view this problem?
236 $self->{isOpen} = time >= $set->open_date || $authz->hasPermissions($user, "view_unopened_sets"); 533 $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets");
237 return unless $self->{isOpen}; 534 return unless $self->{isOpen};
238 535
239 # what does the user want to do? 536 # what does the user want to do?
240 my %want = ( 537 my %want = (
241 showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers}, 538 showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers},
242 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers}, 539 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
243 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints}, 540 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints},
244 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions}, 541 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions},
245 recordAnswers => $submitAnswers, 542 recordAnswers => $submitAnswers,
246 checkAnswers => $checkAnswers, 543 checkAnswers => $checkAnswers,
544 getSubmitButton => 1,
247 ); 545 );
248 546
249 # are certain options enforced? 547 # are certain options enforced?
250 my %must = ( 548 my %must = (
251 showOldAnswers => 0, 549 showOldAnswers => 0,
252 showCorrectAnswers => 0, 550 showCorrectAnswers => 0,
253 showHints => 0, 551 showHints => 0,
254 showSolutions => 0, 552 showSolutions => 0,
255 recordAnswers => mustRecordAnswers($permissionLevel), 553 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
256 checkAnswers => 0, 554 checkAnswers => 0,
555 getSubmitButton => 0,
257 ); 556 );
258 557
259 # does the user have permission to use certain options? 558 # does the user have permission to use certain options?
559 my @args = ($user, $PermissionLevel, $effectiveUser, $set, $problem);
260 my %can = ( 560 my %can = (
261 showOldAnswers => 1, 561 showOldAnswers => $self->can_showOldAnswers(@args),
262 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), 562 showCorrectAnswers => $self->can_showCorrectAnswers(@args),
263 showHints => 1, 563 showHints => $self->can_showHints(@args),
264 showSolutions => canShowSolutions($permissionLevel, $set->answer_date), 564 showSolutions => $self->can_showSolutions(@args),
265 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, 565 recordAnswers => $self->can_recordAnswers(@args, 0),
266 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), 566 checkAnswers => $self->can_checkAnswers(@args, $submitAnswers),
267 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem 567 getSubmitButton => $self->can_recordAnswers(@args, $submitAnswers),
268 checkAnswers => canCheckAnswers($permissionLevel, $set->due_date),
269 ); 568 );
270 569
570# # does the user have permission to use certain options?
571# my %can = (
572# showOldAnswers => 1,
573# showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
574# showHints => 1,
575# showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
576# recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
577# $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
578# # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
579# checkAnswers => canCheckAnswers($permissionLevel, $set->due_date),
580# );
581#
271 # more complicated logic for showing check answer button: 582# # more complicated logic for showing check answer button:
272 # checkAnswers button shows up after due date -- once a student can't record anymore 583# # checkAnswers button shows up after due date -- once a student can't record anymore
273 # checkAnswers button always shows up when an instructor or TA is acting 584# # checkAnswers button always shows up when an instructor or TA is acting
274 # as someone else (the $user and $effectiveUserName aren't the same). 585# # as someone else (the $user and $effectiveUserName aren't the same).
275 $can{checkAnswers} = ( 586# $can{checkAnswers} = (
276 # $can{recordAnswers} will be false if the due date has passed OR the 587# # $can{recordAnswers} will be false if the due date has passed OR the
277 # student has used up all of her attempts 588# # student has used up all of her attempts
278 ($can{checkAnswers} and not $can{recordAnswers}) 589# ($can{checkAnswers} and not $can{recordAnswers})
279 or 590# or
280 ( 591# (
281 # FIXME: this is not the right way to check for this. 592# # FIXME: this is not the right way to check for this.
282 # also, canCheckAnswers() will show this button if the permission 593# # also, canCheckAnswers() will show this button if the permission
283 # level is positive, which is always true when an instructor is 594# # level is positive, which is always true when an instructor is
284 # acting as a student 595# # acting as a student
285 defined($userName) 596# defined($userName)
286 and 597# and
287 defined($effectiveUserName) 598# defined($effectiveUserName)
288 and 599# and
289 ($userName ne $effectiveUserName) 600# ($userName ne $effectiveUserName)
290 ) 601# )
291 ); 602# );
292 603#
293 # more complicated logic for showing "submit answer" button: 604# # more complicated logic for showing "submit answer" button:
294 # We hide the submit answer button if someone is acting as a student 605# # We hide the submit answer button if someone is acting as a student
295 # This prevents errors where you accidently submit the answer for a student 606# # This prevents errors where you accidently submit the answer for a student
296 # Not sure whether this a feature or a bug 607# # Not sure whether this a feature or a bug
297 $can{recordAnswers} = ( 608# $can{recordAnswers} = (
298 $can{recordAnswers} 609# $can{recordAnswers}
299 and not 610# and not
300 ( 611# (
301 # FIXME: this is not the right way to check for this. 612# # FIXME: this is not the right way to check for this.
302 defined($userName) 613# defined($userName)
303 and 614# and
304 defined($effectiveUserName) 615# defined($effectiveUserName)
305 and 616# and
306 ($userName ne $effectiveUserName) 617# ($userName ne $effectiveUserName)
307 ) 618# )
308 ); 619# );
309 620
310 # final values for options 621 # final values for options
311 my %will; 622 my %will;
312 foreach (keys %must) { 623 foreach (keys %must) {
313 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 624 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
340 processAnswers => 1, 651 processAnswers => 1,
341 }, 652 },
342 ); 653 );
343 654
344 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); 655 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer);
656
345 ##### fix hint/solution options ##### 657 ##### fix hint/solution options #####
346 658
347 $can{showHints} &&= $pg->{flags}->{hintExists} 659 $can{showHints} &&= $pg->{flags}->{hintExists}
348 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 660 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
349 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 661 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
491 my $ce = $r->ce; 803 my $ce = $r->ce;
492 my $db = $r->db; 804 my $db = $r->db;
493 my $authz = $r->authz; 805 my $authz = $r->authz;
494 my $urlpath = $r->urlpath; 806 my $urlpath = $r->urlpath;
495 my $user = $r->param('user'); 807 my $user = $r->param('user');
808 my $effectiveUser = $r->param('effectiveUser');
496 809
497 if ($self->{invalidSet}) { 810 if ($self->{invalidSet}) {
498 return CGI::div({class=>"ResultsWithError"}, 811 return CGI::div({class=>"ResultsWithError"},
499 CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . ".")); 812 CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . "."));
500 } 813 }
522 my %will = %{ $self->{will} }; 835 my %will = %{ $self->{will} };
523 my $pg = $self->{pg}; 836 my $pg = $self->{pg};
524 837
525 my $courseName = $urlpath->arg("courseID"); 838 my $courseName = $urlpath->arg("courseID");
526 839
840 # FIXME: move editor link to top, next to problem number.
841 # format as "[edit]" like we're doing with course info file, etc.
842 # add edit link for set as well.
527 my $editorLink = ""; 843 my $editorLink = "";
528 # if we are here without a real problem set, carry that through 844 # if we are here without a real problem set, carry that through
529 my $forced_field = []; 845 my $forced_field = [];
530 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if 846 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if
531 ($set->set_id eq 'Undefined_Set'); 847 ($set->set_id eq 'Undefined_Set');
605 $pureProblem->last_answer."\t". 921 $pureProblem->last_answer."\t".
606 $pureProblem->num_correct."\t". 922 $pureProblem->num_correct."\t".
607 $pureProblem->num_incorrect 923 $pureProblem->num_incorrect
608 ); 924 );
609 } else { 925 } else {
610 if (time < $set->open_date or time > $set->due_date) { 926 if (before($set->open_date) or after($set->due_date)) {
611 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; 927 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed.";
612 } else { 928 } else {
613 $scoreRecordedMessage = "Your score was not recorded."; 929 $scoreRecordedMessage = "Your score was not recorded.";
614 } 930 }
615 } 931 }
616 } else { 932 } else {
617 $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you."; 933 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
618 } 934 }
619 } 935 }
620 936
621 # logging student answers 937 # logging student answers
622 938
623 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; 939 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
624 if ( defined($answer_log ) and defined($pureProblem)) { 940 if ( defined($answer_log ) and defined($pureProblem)) {
625 if ($submitAnswers ) { 941 if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) {
626 my $answerString = ""; 942 my $answerString = ""; my $scores = "";
627 my %answerHash = %{ $pg->{answers} }; 943 my %answerHash = %{ $pg->{answers} };
628 # FIXME this is the line 552 error. make sure original student ans is defined. 944 # FIXME this is the line 552 error. make sure original student ans is defined.
629 # The fact that it is not defined is probably due to an error in some answer evaluator. 945 # The fact that it is not defined is probably due to an error in some answer evaluator.
630 # But I think it is useful to suppress this error message in the log. 946 # But I think it is useful to suppress this error message in the log.
631 foreach (sort keys %answerHash) { 947 foreach (sort keys %answerHash) {
632 my $student_ans = $answerHash{$_}->{original_student_ans} ||''; 948 my $orig_ans = $answerHash{$_}->{original_student_ans};
949 my $student_ans = defined $orig_ans ? $orig_ans : '';
633 $answerString .= $student_ans."\t" 950 $answerString .= $student_ans."\t";
951 $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0";
634 } 952 }
635 $answerString = '' unless defined($answerString); # insure string is defined. 953 $answerString = '' unless defined($answerString); # insure string is defined.
636 writeCourseLog($self->{ce}, "answer_log", 954 writeCourseLog($self->{ce}, "answer_log",
637 join("", 955 join("",
638 '|', $problem->user_id, 956 '|', $problem->user_id,
639 '|', $problem->set_id, 957 '|', $problem->set_id,
640 '|', $problem->problem_id, 958 '|', $problem->problem_id,
641 '|',"\t", 959 '|', $scores, "\t",
642 time(),"\t", 960 time(),"\t",
643 $answerString, 961 $answerString,
644 ), 962 ),
645 ); 963 );
646 964
664 982
665 # attempt summary 983 # attempt summary
666 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 984 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything.
667 # until after the due date 985 # until after the due date
668 # do I need to check $will{showCorrectAnswers} to make preflight work?? 986 # do I need to check $will{showCorrectAnswers} to make preflight work??
669 if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) { 987 if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) {
670 # print this if user submitted answers OR requested correct answers 988 # print this if user submitted answers OR requested correct answers
671 989
672 print $self->attemptResults($pg, 1, 990 print $self->attemptResults($pg, 1,
673 $will{showCorrectAnswers}, 991 $will{showCorrectAnswers},
674 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 992 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
689 # show attempt previews 1007 # show attempt previews
690 } 1008 }
691 1009
692 print CGI::end_div(); 1010 print CGI::end_div();
693 1011
1012 # main form
1013 print CGI::startform("POST", $r->uri);
1014 print $self->hidden_authen_fields;
1015
694 print CGI::start_div({class=>"problem"}); 1016 print CGI::start_div({class=>"problem"});
695
696 # main form
697 print
698 CGI::startform("POST", $r->uri),
699 $self->hidden_authen_fields,
700 CGI::p($pg->{body_text}), 1017 print CGI::p($pg->{body_text});
701 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})), 1018 print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
702 CGI::p( 1019 print CGI::end_div();
1020
1021 print CGI::start_p();
1022
703 ($can{showCorrectAnswers} 1023 if ($can{showCorrectAnswers}) {
704 ? CGI::checkbox( 1024 print CGI::checkbox(
705 -name => "showCorrectAnswers", 1025 -name => "showCorrectAnswers",
706 -checked => $will{showCorrectAnswers}, 1026 -checked => $will{showCorrectAnswers},
707 -label => "Show correct answers", 1027 -label => "Show correct answers",
708 ) ." "
709 : "" ),
710 ($can{showHints}
711 ? '<div style="color:red">'. CGI::checkbox(
712 -name => "showHints",
713 -checked => $will{showHints},
714 -label => "Show Hints",
715 ) . "</div> "
716 : " " ),
717 ($can{showSolutions}
718 ? CGI::checkbox(
719 -name => "showSolutions",
720 -checked => $will{showSolutions},
721 -label => "Show Solutions",
722 ) . " "
723 : " " ),CGI::br(),
724 CGI::submit(-name=>"previewAnswers",
725 -label=>"Preview Answers"),
726 ($can{recordAnswers}
727 ? CGI::submit(-name=>"submitAnswers",
728 -label=>"Submit Answers")
729 : ""),
730 ( $can{checkAnswers}
731 ? CGI::submit(-name=>"checkAnswers",
732 -label=>"Check Answers")
733 : ""),
734 ); 1028 );
1029 }
1030 if ($can{showHints}) {
1031 print CGI::div({style=>"color:red"},
1032 CGI::checkbox(
1033 -name => "showHints",
1034 -checked => $will{showHints},
1035 -label => "Show Hints",
1036 )
1037 );
1038 }
1039 if ($can{showSolutions}) {
1040 print CGI::checkbox(
1041 -name => "showSolutions",
1042 -checked => $will{showSolutions},
1043 -label => "Show Solutions",
1044 );
1045 }
1046
1047 if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) {
1048 print CGI::br();
1049 }
1050
1051 print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers");
1052 if ($can{checkAnswers}) {
1053 print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers");
1054 }
1055 if ($can{getSubmitButton}) {
1056 if ($user ne $effectiveUser) {
1057 # if acting as a student, make it clear that answer submissions will
1058 # apply to the student's records, not the professor's.
1059 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser");
1060 } else {
1061 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers");
1062 }
1063 }
1064
735 print CGI::end_div(); 1065 print CGI::end_p();
736 1066
737 print CGI::start_div({class=>"scoreSummary"}); 1067 print CGI::start_div({class=>"scoreSummary"});
738 1068
739 # score summary 1069 # score summary
740 my $attempts = $problem->num_correct + $problem->num_incorrect; 1070 my $attempts = $problem->num_correct + $problem->num_incorrect;
750 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 1080 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
751 } 1081 }
752 1082
753 my $setClosed = 0; 1083 my $setClosed = 0;
754 my $setClosedMessage; 1084 my $setClosedMessage;
755 if (time < $set->open_date or time > $set->due_date) { 1085 if (before($set->open_date) or after($set->due_date)) {
756 $setClosed = 1; 1086 $setClosed = 1;
757 $setClosedMessage = "This problem set is closed."; 1087 $setClosedMessage = "This problem set is closed.";
758 if ($authz->hasPermissions($user, "view_answers")) { 1088 if ($authz->hasPermissions($user, "view_answers")) {
759 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 1089 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
760 } else { 1090 } else {
875 } 1205 }
876 1206
877 return ""; 1207 return "";
878} 1208}
879 1209
880##### output utilities #####
881
882sub attemptResults {
883 my $self = shift;
884 my $pg = shift;
885 my $showAttemptAnswers = shift;
886 my $showCorrectAnswers = shift;
887 my $showAttemptResults = $showAttemptAnswers && shift;
888 my $showSummary = shift;
889 my $showAttemptPreview = shift || 0;
890
891 my $ce = $self->r->ce;
892
893 my $problemResult = $pg->{result}; # the overall result of the problem
894 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
895
896 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
897
898 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
899 my $imgGen = WeBWorK::PG::ImageGenerator->new(
900 tempDir => $ce->{webworkDirs}->{tmp},
901 latex => $ce->{externalPrograms}->{latex},
902 dvipng => $ce->{externalPrograms}->{dvipng},
903 useCache => 1,
904 cacheDir => $ce->{webworkDirs}->{equationCache},
905 cacheURL => $ce->{webworkURLs}->{equationCache},
906 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
907 );
908
909 my $header;
910 #$header .= CGI::th("Part");
911 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
912 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
913 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
914 $header .= $showAttemptResults ? CGI::th("Result") : "";
915 $header .= $showMessages ? CGI::th("Messages") : "";
916 my @tableRows = ( $header );
917 my $numCorrect;
918 foreach my $name (@answerNames) {
919 my $answerResult = $pg->{answers}->{$name};
920 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
921 my $preview = ($showAttemptPreview
922 ? $self->previewAnswer($answerResult, $imgGen)
923 : "");
924 my $correctAnswer = $answerResult->{correct_ans};
925 my $answerScore = $answerResult->{score};
926 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
927 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
928 $numCorrect += $answerScore > 0;
929 my $resultString = $answerScore == 1 ? "correct" : "incorrect";
930
931 # get rid of the goofy prefix on the answer names (supposedly, the format
932 # of the answer names is changeable. this only fixes it for "AnSwEr"
933 #$name =~ s/^AnSwEr//;
934
935 my $row;
936 #$row .= CGI::td($name);
937 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
938 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : "";
939 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
940 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : "";
941 $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : "";
942 push @tableRows, $row;
943 }
944
945 # render equation images
946 $imgGen->render(refresh => 1);
947
948# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
949 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
950# FIXME -- I left the old code in in case we have to back out.
951# my $summary = "On this attempt, you answered $numCorrect out of "
952# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
953 my $summary = "";
954 if (scalar @answerNames == 1) {
955 if ($numCorrect == scalar @answerNames) {
956 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
957 } else {
958 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
959 }
960 } else {
961 if ($numCorrect == scalar @answerNames) {
962 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
963 } else {
964 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
965 }
966 }
967
968 return
969 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
970 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
971}
972
973#sub nbsp {
974# my $str = shift;
975# ($str =~/\S/) ? $str : '&nbsp;' ; # returns non-breaking space for empty strings
976# # tricky cases: $str =0;
977# # $str is a complex number
978#}
979
980sub viewOptions {
981 my ($self) = @_;
982 my $ce = $self->r->ce;
983
984 # don't show options if we don't have anything to show
985 return if $self->{invalidSet} or $self->{invalidProblem};
986 return unless $self->{isOpen};
987
988 my $displayMode = $self->{displayMode};
989 my %must = %{ $self->{must} };
990 my %can = %{ $self->{can} };
991 my %will = %{ $self->{will} };
992
993 my $optionLine;
994 $can{showOldAnswers} and $optionLine .= join "",
995 "Show: &nbsp;".CGI::br(),
996 CGI::checkbox(
997 -name => "showOldAnswers",
998 -checked => $will{showOldAnswers},
999 -label => "Saved answers",
1000 ), "&nbsp;&nbsp;".CGI::br();
1001
1002 $optionLine and $optionLine .= join "", CGI::br();
1003
1004 my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
1005 my @active_modes = grep { exists $display_modes{$_} }
1006 @{$ce->{pg}->{displayModes}};
1007 my $modeLine = (scalar(@active_modes)>1) ?
1008 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
1009 CGI::radio_group(
1010 -name => "displayMode",
1011 -values => \@active_modes,
1012 -default => $displayMode,
1013 -linebreak=>'true',
1014 -labels => {
1015 plainText => "plain",
1016 formattedText => "formatted",
1017 images => "images",
1018 jsMath => "jsMath",
1019 asciimath => "asciimath",
1020 },
1021 ). CGI::br().CGI::hr() : '';
1022
1023 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
1024 $modeLine,
1025 $optionLine,
1026 CGI::submit(-name=>"redisplay", -label=>"Save Options"),
1027 );
1028}
1029
1030sub previewAnswer {
1031 my ($self, $answerResult, $imgGen) = @_;
1032 my $ce = $self->r->ce;
1033 my $effectiveUser = $self->{effectiveUser};
1034 my $set = $self->{set};
1035 my $problem = $self->{problem};
1036 my $displayMode = $self->{displayMode};
1037
1038 # note: right now, we have to do things completely differently when we are
1039 # rendering math from INSIDE the translator and from OUTSIDE the translator.
1040 # so we'll just deal with each case explicitly here. there's some code
1041 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
1042
1043 my $tex = $answerResult->{preview_latex_string};
1044
1045 return "" unless defined $tex and $tex ne "";
1046
1047 if ($displayMode eq "plainText") {
1048 return $tex;
1049 } elsif ($displayMode eq "formattedText") {
1050 my $tthCommand = $ce->{externalPrograms}->{tth}
1051 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
1052 . "\\(".$tex."\\)\n"
1053 . "END_OF_INPUT\n";
1054
1055 # call tth
1056 my $result = `$tthCommand`;
1057 if ($?) {
1058 return "<b>[tth failed: $? $@]</b>";
1059 }
1060 return $result;
1061 } elsif ($displayMode eq "images") {
1062 $imgGen->add($tex);
1063 } elsif ($displayMode eq "jsMath") {
1064
1065 return '<DIV CLASS="math">'.$tex.'</DIV>' ;
1066
1067
1068
1069
1070 }
1071}
1072
1073##### permission queries #####
1074
1075# this stuff should be abstracted out into the permissions system
1076# however, the permission system only knows about things in the
1077# course environment and the username. hmmm...
1078
1079# also, i should fix these so that they have a consistent calling
1080# format -- perhaps:
1081# canPERM($ce, $user, $set, $problem, $permissionLevel)
1082
1083sub canShowCorrectAnswers($$) {
1084 my ($permissionLevel, $answerDate) = @_;
1085 return $permissionLevel > 0 || time > $answerDate;
1086}
1087
1088sub canShowSolutions($$) {
1089 my ($permissionLevel, $answerDate) = @_;
1090 return canShowCorrectAnswers($permissionLevel, $answerDate);
1091}
1092
1093sub canRecordAnswers($$$$$) {
1094 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
1095 my $permHigh = $permissionLevel > 0;
1096 my $timeOK = time >= $openDate && time <= $dueDate;
1097 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
1098 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
1099 return $recordAnswers;
1100}
1101
1102sub canCheckAnswers($$) {
1103 my ($permissionLevel, $dueDate) = @_;
1104 my $permHigh = $permissionLevel > 0;
1105 my $timeOK = time >= $dueDate;
1106 my $recordAnswers = $permHigh || $timeOK;
1107 return $recordAnswers;
1108}
1109
1110sub mustRecordAnswers($) {
1111 my ($permissionLevel) = @_;
1112 return $permissionLevel == 0;
1113}
11141; 12101;

Legend:
Removed from v.2398  
changed lines
  Added in v.2735

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9