[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 2504 Revision 2505
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.152 2004/07/06 16:12:09 sh002i Exp $ 4# $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.153 2004/07/06 21:23:58 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) = @_;
123 my $authz = $self->r->authz;
124 if ($User->user_id ne $EffectiveUser->user_id) {
125 return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
126 }
127 if (before($Set->open_date)) {
128 return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
129 } elsif (between($Set->open_date, $Set->due_date)) {
130 my $max_attempts = $Problem->max_attempts;
131 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + 1;
132 if ($max_attempts == -1 or $attempts_used < $max_attempts) {
133 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts");
134 } else {
135 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts");
136 }
137 } elsif (between($Set->due_date, $Set->close_date)) {
138 return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
139 } elsif (after($Set->close_date)) {
140 return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
141 }
142}
143
144sub can_checkAnswers {
145 my ($self, $User, $PermissionLevel, $EffectiveUser, $Set, $Problem) = @_;
146 my $authz = $self->r->authz;
147
148 if (before($Set->open_date)) {
149 return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
150 } elsif (between($Set->open_date, $Set->due_date)) {
151 my $max_attempts = $Problem->max_attempts;
152 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + 1;
153 if ($max_attempts == -1 or $attempts_used < $max_attempts) {
154 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts");
155 } else {
156 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts");
157 }
158 } elsif (between($Set->due_date, $Set->close_date)) {
159 return $authz->hasPermissions($User->user_id, "check_answers_after_due_date");
160 } elsif (after($Set->close_date)) {
161 return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date");
162 }
163}
164
165# Helper functions for calculating times
166sub before { return time < $_[0] }
167sub after { return time > $_[0] }
168sub between { my $t = time; return $t > $_[0] && $t < $_[1] }
169
170################################################################################
171# output utilities
172################################################################################
173
174sub attemptResults {
175 my $self = shift;
176 my $pg = shift;
177 my $showAttemptAnswers = shift;
178 my $showCorrectAnswers = shift;
179 my $showAttemptResults = $showAttemptAnswers && shift;
180 my $showSummary = shift;
181 my $showAttemptPreview = shift || 0;
182
183 my $ce = $self->r->ce;
184
185 my $problemResult = $pg->{result}; # the overall result of the problem
186 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
187
188 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
189
190 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
191
192 # to make grabbing these options easier, we'll pull them out now...
193 my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
194
195 my $imgGen = WeBWorK::PG::ImageGenerator->new(
196 tempDir => $ce->{webworkDirs}->{tmp},
197 latex => $ce->{externalPrograms}->{latex},
198 dvipng => $ce->{externalPrograms}->{dvipng},
199 useCache => 1,
200 cacheDir => $ce->{webworkDirs}->{equationCache},
201 cacheURL => $ce->{webworkURLs}->{equationCache},
202 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
203 dvipng_align => $imagesModeOptions{dvipng_align},
204 dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
205 );
206
207 my $header;
208 #$header .= CGI::th("Part");
209 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
210 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
211 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
212 $header .= $showAttemptResults ? CGI::th("Result") : "";
213 $header .= $showMessages ? CGI::th("Messages") : "";
214 my @tableRows = ( $header );
215 my $numCorrect = 0;
216 foreach my $name (@answerNames) {
217 my $answerResult = $pg->{answers}->{$name};
218 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
219 my $preview = ($showAttemptPreview
220 ? $self->previewAnswer($answerResult, $imgGen)
221 : "");
222 my $correctAnswer = $answerResult->{correct_ans};
223 my $answerScore = $answerResult->{score};
224 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
225 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
226 $numCorrect += $answerScore > 0;
227 my $resultString = $answerScore == 1 ? "correct" : "incorrect";
228
229 # get rid of the goofy prefix on the answer names (supposedly, the format
230 # of the answer names is changeable. this only fixes it for "AnSwEr"
231 #$name =~ s/^AnSwEr//;
232
233 my $row;
234 #$row .= CGI::td($name);
235 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
236 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : "";
237 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
238 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : "";
239 $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : "";
240 push @tableRows, $row;
241 }
242
243 # render equation images
244 $imgGen->render(refresh => 1);
245
246# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
247 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
248# FIXME -- I left the old code in in case we have to back out.
249# my $summary = "On this attempt, you answered $numCorrect out of "
250# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
251 my $summary = "";
252 if (scalar @answerNames == 1) {
253 if ($numCorrect == scalar @answerNames) {
254 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
255 } else {
256 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
257 }
258 } else {
259 if ($numCorrect == scalar @answerNames) {
260 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
261 } else {
262 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
263 }
264 }
265
266 return
267 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
268 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
269}
270
271sub viewOptions {
272 my ($self) = @_;
273 my $ce = $self->r->ce;
274
275 # don't show options if we don't have anything to show
276 return if $self->{invalidSet} or $self->{invalidProblem};
277 return unless $self->{isOpen};
278
279 my $displayMode = $self->{displayMode};
280 my %must = %{ $self->{must} };
281 my %can = %{ $self->{can} };
282 my %will = %{ $self->{will} };
283
284 my $optionLine;
285 $can{showOldAnswers} and $optionLine .= join "",
286 "Show: &nbsp;".CGI::br(),
287 CGI::checkbox(
288 -name => "showOldAnswers",
289 -checked => $will{showOldAnswers},
290 -label => "Saved answers",
291 ), "&nbsp;&nbsp;".CGI::br();
292
293 $optionLine and $optionLine .= join "", CGI::br();
294
295 my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
296 my @active_modes = grep { exists $display_modes{$_} }
297 @{$ce->{pg}->{displayModes}};
298 my $modeLine = (scalar(@active_modes) > 1) ?
299 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
300 CGI::radio_group(
301 -name => "displayMode",
302 -values => \@active_modes,
303 -default => $displayMode,
304 -linebreak=>'true',
305 -labels => {
306 plainText => "plain",
307 formattedText => "formatted",
308 images => "images",
309 jsMath => "jsMath",
310 asciimath => "asciimath",
311 },
312 ). CGI::br().CGI::hr() : '';
313
314 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
315 $modeLine,
316 $optionLine,
317 CGI::submit(-name=>"redisplay", -label=>"Apply Options"),
318 );
319}
320
321sub previewAnswer {
322 my ($self, $answerResult, $imgGen) = @_;
323 my $ce = $self->r->ce;
324 my $effectiveUser = $self->{effectiveUser};
325 my $set = $self->{set};
326 my $problem = $self->{problem};
327 my $displayMode = $self->{displayMode};
328
329 # note: right now, we have to do things completely differently when we are
330 # rendering math from INSIDE the translator and from OUTSIDE the translator.
331 # so we'll just deal with each case explicitly here. there's some code
332 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
333
334 my $tex = $answerResult->{preview_latex_string};
335
336 return "" unless defined $tex and $tex ne "";
337
338 if ($displayMode eq "plainText") {
339 return $tex;
340 } elsif ($displayMode eq "formattedText") {
341 my $tthCommand = $ce->{externalPrograms}->{tth}
342 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
343 . "\\(".$tex."\\)\n"
344 . "END_OF_INPUT\n";
345
346 # call tth
347 my $result = `$tthCommand`;
348 if ($?) {
349 return "<b>[tth failed: $? $@]</b>";
350 } else {
351 return $result;
352 }
353 } elsif ($displayMode eq "images") {
354 $imgGen->add($tex);
355 } elsif ($displayMode eq "jsMath") {
356 return '<DIV CLASS="math">'.$tex.'</DIV>' ;
357 }
358}
359
360################################################################################
361# Template escape implementations
362################################################################################
69 363
70sub pre_header_initialize { 364sub pre_header_initialize {
71 my ($self) = @_; 365 my ($self) = @_;
72 my $r = $self->r; 366 my $r = $self->r;
73 my $ce = $r->ce; 367 my $ce = $r->ce;
232 return if $self->{invalidSet} || $self->{invalidProblem}; 526 return if $self->{invalidSet} || $self->{invalidProblem};
233 527
234 ##### permissions ##### 528 ##### permissions #####
235 529
236 # are we allowed to view this problem? 530 # are we allowed to view this problem?
237 $self->{isOpen} = time >= $set->open_date || $authz->hasPermissions($userName, "view_unopened_sets"); 531 $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets");
238 return unless $self->{isOpen}; 532 return unless $self->{isOpen};
239 533
240 # what does the user want to do? 534 # what does the user want to do?
241 my %want = ( 535 my %want = (
242 showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers}, 536 showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers},
251 my %must = ( 545 my %must = (
252 showOldAnswers => 0, 546 showOldAnswers => 0,
253 showCorrectAnswers => 0, 547 showCorrectAnswers => 0,
254 showHints => 0, 548 showHints => 0,
255 showSolutions => 0, 549 showSolutions => 0,
256 recordAnswers => mustRecordAnswers($permissionLevel), 550 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
257 checkAnswers => 0, 551 checkAnswers => 0,
258 ); 552 );
259 553
260 # does the user have permission to use certain options? 554 # does the user have permission to use certain options?
555 my @args = ($user, $PermissionLevel, $effectiveUser, $set, $problem);
261 my %can = ( 556 my %can = (
262 showOldAnswers => 1, 557 showOldAnswers => $self->can_showOldAnswers(@args),
263 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), 558 showCorrectAnswers => $self->can_showCorrectAnswers(@args),
264 showHints => 1, 559 showHints => $self->can_showHints(@args),
265 showSolutions => canShowSolutions($permissionLevel, $set->answer_date), 560 showSolutions => $self->can_showSolutions(@args),
266 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, 561 recordAnswers => $self->can_recordAnswers(@args),
267 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), 562 checkAnswers => $self->can_checkAnswers(@args),
268 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
269 checkAnswers => canCheckAnswers($permissionLevel, $set->due_date),
270 ); 563 );
271 564
565# # does the user have permission to use certain options?
566# my %can = (
567# showOldAnswers => 1,
568# showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
569# showHints => 1,
570# showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
571# recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
572# $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
573# # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
574# checkAnswers => canCheckAnswers($permissionLevel, $set->due_date),
575# );
576#
272 # more complicated logic for showing check answer button: 577# # more complicated logic for showing check answer button:
273 # checkAnswers button shows up after due date -- once a student can't record anymore 578# # checkAnswers button shows up after due date -- once a student can't record anymore
274 # checkAnswers button always shows up when an instructor or TA is acting 579# # checkAnswers button always shows up when an instructor or TA is acting
275 # as someone else (the $user and $effectiveUserName aren't the same). 580# # as someone else (the $user and $effectiveUserName aren't the same).
276 $can{checkAnswers} = ( 581# $can{checkAnswers} = (
277 # $can{recordAnswers} will be false if the due date has passed OR the 582# # $can{recordAnswers} will be false if the due date has passed OR the
278 # student has used up all of her attempts 583# # student has used up all of her attempts
279 ($can{checkAnswers} and not $can{recordAnswers}) 584# ($can{checkAnswers} and not $can{recordAnswers})
280 or 585# or
281 ( 586# (
282 # FIXME: this is not the right way to check for this. 587# # FIXME: this is not the right way to check for this.
283 # also, canCheckAnswers() will show this button if the permission 588# # also, canCheckAnswers() will show this button if the permission
284 # level is positive, which is always true when an instructor is 589# # level is positive, which is always true when an instructor is
285 # acting as a student 590# # acting as a student
286 defined($userName) 591# defined($userName)
287 and 592# and
288 defined($effectiveUserName) 593# defined($effectiveUserName)
289 and 594# and
290 ($userName ne $effectiveUserName) 595# ($userName ne $effectiveUserName)
291 ) 596# )
292 ); 597# );
293 598#
294 # more complicated logic for showing "submit answer" button: 599# # more complicated logic for showing "submit answer" button:
295 # We hide the submit answer button if someone is acting as a student 600# # We hide the submit answer button if someone is acting as a student
296 # This prevents errors where you accidently submit the answer for a student 601# # This prevents errors where you accidently submit the answer for a student
297 # Not sure whether this a feature or a bug 602# # Not sure whether this a feature or a bug
298 $can{recordAnswers} = ( 603# $can{recordAnswers} = (
299 $can{recordAnswers} 604# $can{recordAnswers}
300 and not 605# and not
301 ( 606# (
302 # FIXME: this is not the right way to check for this. 607# # FIXME: this is not the right way to check for this.
303 defined($userName) 608# defined($userName)
304 and 609# and
305 defined($effectiveUserName) 610# defined($effectiveUserName)
306 and 611# and
307 ($userName ne $effectiveUserName) 612# ($userName ne $effectiveUserName)
308 ) 613# )
309 ); 614# );
310 615
311 # final values for options 616 # final values for options
312 my %will; 617 my %will;
313 foreach (keys %must) { 618 foreach (keys %must) {
314 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 619 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
341 processAnswers => 1, 646 processAnswers => 1,
342 }, 647 },
343 ); 648 );
344 649
345 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); 650 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer);
651
346 ##### fix hint/solution options ##### 652 ##### fix hint/solution options #####
347 653
348 $can{showHints} &&= $pg->{flags}->{hintExists} 654 $can{showHints} &&= $pg->{flags}->{hintExists}
349 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 655 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
350 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 656 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
523 my %will = %{ $self->{will} }; 829 my %will = %{ $self->{will} };
524 my $pg = $self->{pg}; 830 my $pg = $self->{pg};
525 831
526 my $courseName = $urlpath->arg("courseID"); 832 my $courseName = $urlpath->arg("courseID");
527 833
834 # FIXME: move editor link to top, next to problem number.
835 # format as "[edit]" like we're doing with course info file, etc.
836 # add edit link for set as well.
528 my $editorLink = ""; 837 my $editorLink = "";
529 # if we are here without a real problem set, carry that through 838 # if we are here without a real problem set, carry that through
530 my $forced_field = []; 839 my $forced_field = [];
531 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if 840 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if
532 ($set->set_id eq 'Undefined_Set'); 841 ($set->set_id eq 'Undefined_Set');
606 $pureProblem->last_answer."\t". 915 $pureProblem->last_answer."\t".
607 $pureProblem->num_correct."\t". 916 $pureProblem->num_correct."\t".
608 $pureProblem->num_incorrect 917 $pureProblem->num_incorrect
609 ); 918 );
610 } else { 919 } else {
611 if (time < $set->open_date or time > $set->due_date) { 920 if (before($set->open_date) or after($set->due_date)) {
612 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; 921 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed.";
613 } else { 922 } else {
614 $scoreRecordedMessage = "Your score was not recorded."; 923 $scoreRecordedMessage = "Your score was not recorded.";
615 } 924 }
616 } 925 }
617 } else { 926 } else {
618 $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you."; 927 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
619 } 928 }
620 } 929 }
621 930
622 # logging student answers 931 # logging student answers
623 932
665 974
666 # attempt summary 975 # attempt summary
667 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 976 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything.
668 # until after the due date 977 # until after the due date
669 # do I need to check $will{showCorrectAnswers} to make preflight work?? 978 # do I need to check $will{showCorrectAnswers} to make preflight work??
670 if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) { 979 if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) {
671 # print this if user submitted answers OR requested correct answers 980 # print this if user submitted answers OR requested correct answers
672 981
673 print $self->attemptResults($pg, 1, 982 print $self->attemptResults($pg, 1,
674 $will{showCorrectAnswers}, 983 $will{showCorrectAnswers},
675 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 984 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
690 # show attempt previews 999 # show attempt previews
691 } 1000 }
692 1001
693 print CGI::end_div(); 1002 print CGI::end_div();
694 1003
1004 # main form
1005 print CGI::startform("POST", $r->uri);
1006 print $self->hidden_authen_fields;
1007
695 print CGI::start_div({class=>"problem"}); 1008 print CGI::start_div({class=>"problem"});
696
697 # main form
698 print
699 CGI::startform("POST", $r->uri),
700 $self->hidden_authen_fields,
701 CGI::p($pg->{body_text}), 1009 print CGI::p($pg->{body_text});
702 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})), 1010 print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
703 CGI::p( 1011 print CGI::end_div();
1012
1013 print CGI::start_p();
1014
704 ($can{showCorrectAnswers} 1015 if ($can{showCorrectAnswers}) {
705 ? CGI::checkbox( 1016 print CGI::checkbox(
706 -name => "showCorrectAnswers", 1017 -name => "showCorrectAnswers",
707 -checked => $will{showCorrectAnswers}, 1018 -checked => $will{showCorrectAnswers},
708 -label => "Show correct answers", 1019 -label => "Show correct answers",
709 ) ." "
710 : "" ),
711 ($can{showHints}
712 ? '<div style="color:red">'. CGI::checkbox(
713 -name => "showHints",
714 -checked => $will{showHints},
715 -label => "Show Hints",
716 ) . "</div> "
717 : " " ),
718 ($can{showSolutions}
719 ? CGI::checkbox(
720 -name => "showSolutions",
721 -checked => $will{showSolutions},
722 -label => "Show Solutions",
723 ) . " "
724 : " " ),CGI::br(),
725 CGI::submit(-name=>"previewAnswers",
726 -label=>"Preview Answers"),
727 ($can{recordAnswers}
728 ? CGI::submit(-name=>"submitAnswers",
729 -label=>"Submit Answers")
730 : ""),
731 ( $can{checkAnswers}
732 ? CGI::submit(-name=>"checkAnswers",
733 -label=>"Check Answers")
734 : ""),
735 ); 1020 );
1021 }
1022 if ($can{showHints}) {
1023 print CGI::div({style=>"color:red"},
1024 CGI::checkbox(
1025 -name => "showHints",
1026 -checked => $will{showHints},
1027 -label => "Show Hints",
1028 )
1029 );
1030 }
1031 if ($can{showSolutions}) {
1032 print CGI::checkbox(
1033 -name => "showSolutions",
1034 -checked => $will{showSolutions},
1035 -label => "Show Solutions",
1036 );
1037 }
1038
1039 if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) {
1040 print CGI::br();
1041 }
1042
1043 print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers");
1044 if ($can{checkAnswers}) {
1045 print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers");
1046 }
1047 if ($can{recordAnswers}) {
1048 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers");
1049 }
1050
736 print CGI::end_div(); 1051 print CGI::end_p();
737 1052
738 print CGI::start_div({class=>"scoreSummary"}); 1053 print CGI::start_div({class=>"scoreSummary"});
739 1054
740 # score summary 1055 # score summary
741 my $attempts = $problem->num_correct + $problem->num_incorrect; 1056 my $attempts = $problem->num_correct + $problem->num_incorrect;
742 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 1057 my $attemptsNoun = $attempts != 1 ? "times" : "time";
751 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 1066 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
752 } 1067 }
753 1068
754 my $setClosed = 0; 1069 my $setClosed = 0;
755 my $setClosedMessage; 1070 my $setClosedMessage;
756 if (time < $set->open_date or time > $set->due_date) { 1071 if (before($set->open_date) or after($set->due_date)) {
757 $setClosed = 1; 1072 $setClosed = 1;
758 $setClosedMessage = "This problem set is closed."; 1073 $setClosedMessage = "This problem set is closed.";
759 if ($authz->hasPermissions($user, "view_answers")) { 1074 if ($authz->hasPermissions($user, "view_answers")) {
760 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 1075 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
761 } else { 1076 } else {
876 } 1191 }
877 1192
878 return ""; 1193 return "";
879} 1194}
880 1195
881##### output utilities #####
882
883sub attemptResults {
884 my $self = shift;
885 my $pg = shift;
886 my $showAttemptAnswers = shift;
887 my $showCorrectAnswers = shift;
888 my $showAttemptResults = $showAttemptAnswers && shift;
889 my $showSummary = shift;
890 my $showAttemptPreview = shift || 0;
891
892 my $ce = $self->r->ce;
893
894 my $problemResult = $pg->{result}; # the overall result of the problem
895 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
896
897 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
898
899 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
900
901 # to make grabbing these options easier, we'll pull them out now...
902 my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
903
904 my $imgGen = WeBWorK::PG::ImageGenerator->new(
905 tempDir => $ce->{webworkDirs}->{tmp},
906 latex => $ce->{externalPrograms}->{latex},
907 dvipng => $ce->{externalPrograms}->{dvipng},
908 useCache => 1,
909 cacheDir => $ce->{webworkDirs}->{equationCache},
910 cacheURL => $ce->{webworkURLs}->{equationCache},
911 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
912 dvipng_align => $imagesModeOptions{dvipng_align},
913 dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
914 );
915
916 my $header;
917 #$header .= CGI::th("Part");
918 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
919 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
920 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
921 $header .= $showAttemptResults ? CGI::th("Result") : "";
922 $header .= $showMessages ? CGI::th("Messages") : "";
923 my @tableRows = ( $header );
924 my $numCorrect = 0;
925 foreach my $name (@answerNames) {
926 my $answerResult = $pg->{answers}->{$name};
927 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
928 my $preview = ($showAttemptPreview
929 ? $self->previewAnswer($answerResult, $imgGen)
930 : "");
931 my $correctAnswer = $answerResult->{correct_ans};
932 my $answerScore = $answerResult->{score};
933 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
934 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
935 $numCorrect += $answerScore > 0;
936 my $resultString = $answerScore == 1 ? "correct" : "incorrect";
937
938 # get rid of the goofy prefix on the answer names (supposedly, the format
939 # of the answer names is changeable. this only fixes it for "AnSwEr"
940 #$name =~ s/^AnSwEr//;
941
942 my $row;
943 #$row .= CGI::td($name);
944 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
945 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : "";
946 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
947 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : "";
948 $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : "";
949 push @tableRows, $row;
950 }
951
952 # render equation images
953 $imgGen->render(refresh => 1);
954
955# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
956 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
957# FIXME -- I left the old code in in case we have to back out.
958# my $summary = "On this attempt, you answered $numCorrect out of "
959# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
960 my $summary = "";
961 if (scalar @answerNames == 1) {
962 if ($numCorrect == scalar @answerNames) {
963 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
964 } else {
965 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
966 }
967 } else {
968 if ($numCorrect == scalar @answerNames) {
969 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
970 } else {
971 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
972 }
973 }
974
975 return
976 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
977 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
978}
979
980#sub nbsp {
981# my $str = shift;
982# ($str =~/\S/) ? $str : '&nbsp;' ; # returns non-breaking space for empty strings
983# # tricky cases: $str =0;
984# # $str is a complex number
985#}
986
987sub viewOptions {
988 my ($self) = @_;
989 my $ce = $self->r->ce;
990
991 # don't show options if we don't have anything to show
992 return if $self->{invalidSet} or $self->{invalidProblem};
993 return unless $self->{isOpen};
994
995 my $displayMode = $self->{displayMode};
996 my %must = %{ $self->{must} };
997 my %can = %{ $self->{can} };
998 my %will = %{ $self->{will} };
999
1000 my $optionLine;
1001 $can{showOldAnswers} and $optionLine .= join "",
1002 "Show: &nbsp;".CGI::br(),
1003 CGI::checkbox(
1004 -name => "showOldAnswers",
1005 -checked => $will{showOldAnswers},
1006 -label => "Saved answers",
1007 ), "&nbsp;&nbsp;".CGI::br();
1008
1009 $optionLine and $optionLine .= join "", CGI::br();
1010
1011 my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
1012 my @active_modes = grep { exists $display_modes{$_} }
1013 @{$ce->{pg}->{displayModes}};
1014 my $modeLine = (scalar(@active_modes)>1) ?
1015 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
1016 CGI::radio_group(
1017 -name => "displayMode",
1018 -values => \@active_modes,
1019 -default => $displayMode,
1020 -linebreak=>'true',
1021 -labels => {
1022 plainText => "plain",
1023 formattedText => "formatted",
1024 images => "images",
1025 jsMath => "jsMath",
1026 asciimath => "asciimath",
1027 },
1028 ). CGI::br().CGI::hr() : '';
1029
1030 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
1031 $modeLine,
1032 $optionLine,
1033 CGI::submit(-name=>"redisplay", -label=>"Apply Options"),
1034 );
1035}
1036
1037sub previewAnswer {
1038 my ($self, $answerResult, $imgGen) = @_;
1039 my $ce = $self->r->ce;
1040 my $effectiveUser = $self->{effectiveUser};
1041 my $set = $self->{set};
1042 my $problem = $self->{problem};
1043 my $displayMode = $self->{displayMode};
1044
1045 # note: right now, we have to do things completely differently when we are
1046 # rendering math from INSIDE the translator and from OUTSIDE the translator.
1047 # so we'll just deal with each case explicitly here. there's some code
1048 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
1049
1050 my $tex = $answerResult->{preview_latex_string};
1051
1052 return "" unless defined $tex and $tex ne "";
1053
1054 if ($displayMode eq "plainText") {
1055 return $tex;
1056 } elsif ($displayMode eq "formattedText") {
1057 my $tthCommand = $ce->{externalPrograms}->{tth}
1058 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
1059 . "\\(".$tex."\\)\n"
1060 . "END_OF_INPUT\n";
1061
1062 # call tth
1063 my $result = `$tthCommand`;
1064 if ($?) {
1065 return "<b>[tth failed: $? $@]</b>";
1066 }
1067 return $result;
1068 } elsif ($displayMode eq "images") {
1069 $imgGen->add($tex);
1070 } elsif ($displayMode eq "jsMath") {
1071
1072 return '<DIV CLASS="math">'.$tex.'</DIV>' ;
1073
1074
1075
1076
1077 }
1078}
1079
1080##### permission queries #####
1081
1082# this stuff should be abstracted out into the permissions system
1083# however, the permission system only knows about things in the
1084# course environment and the username. hmmm...
1085
1086# also, i should fix these so that they have a consistent calling
1087# format -- perhaps:
1088# canPERM($ce, $user, $set, $problem, $permissionLevel)
1089
1090sub canShowCorrectAnswers($$) {
1091 my ($permissionLevel, $answerDate) = @_;
1092 return $permissionLevel > 0 || time > $answerDate;
1093}
1094
1095sub canShowSolutions($$) {
1096 my ($permissionLevel, $answerDate) = @_;
1097 return canShowCorrectAnswers($permissionLevel, $answerDate);
1098}
1099
1100sub canRecordAnswers($$$$$) {
1101 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
1102 my $permHigh = $permissionLevel > 0;
1103 my $timeOK = time >= $openDate && time <= $dueDate;
1104 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
1105 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
1106 return $recordAnswers;
1107}
1108
1109sub canCheckAnswers($$) {
1110 my ($permissionLevel, $dueDate) = @_;
1111 my $permHigh = $permissionLevel > 0;
1112 my $timeOK = time >= $dueDate;
1113 my $recordAnswers = $permHigh || $timeOK;
1114 return $recordAnswers;
1115}
1116
1117sub mustRecordAnswers($) {
1118 my ($permissionLevel) = @_;
1119 return $permissionLevel == 0;
1120}
11211; 11961;

Legend:
Removed from v.2504  
changed lines
  Added in v.2505

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9