[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 388 Revision 683
1################################################################################
2# WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
3# $Id$
4################################################################################
5
1package WeBWorK::ContentGenerator::Problem; 6package WeBWorK::ContentGenerator::Problem;
2our @ISA = qw(WeBWorK::ContentGenerator); 7
3use lib '/Users/gage/webwork/xmlrpc/daemon'; 8=head1 NAME
4use lib '/Users/gage/webwork-modperl/lib'; 9
5use PGtranslator5; 10WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
11
12=cut
13
14use strict;
15use warnings;
6use WeBWorK::ContentGenerator; 16use base qw(WeBWorK::ContentGenerator);
7use Apache::Constants qw(:common); 17use CGI qw();
18use File::Temp qw(tempdir);
19use WeBWorK::Form;
20use WeBWorK::PG;
21use WeBWorK::PG::IO;
22use WeBWorK::Utils qw(writeLog encodeAnswers decodeAnswers ref2string);
23
24############################################################
25#
26# user
27# key
28#
29# displayMode
30# showOldAnswers
31# showCorrectAnswers
32# showHints
33# showSolutions
34#
35# AnSwEr# - answer blanks in problem
36#
37# redisplay - name of the "Redisplay Problem" button
38# submitAnswers - name of "Submit Answers" button
39#
40############################################################
41
42sub pre_header_initialize {
43 my ($self, $setName, $problemNumber) = @_;
44 my $courseEnv = $self->{courseEnvironment};
45 my $r = $self->{r};
46 my $userName = $r->param('user');
47
48 ##### database setup #####
49
50 my $cldb = WeBWorK::DB::Classlist->new($courseEnv);
51 my $wwdb = WeBWorK::DB::WW->new($courseEnv);
52 my $authdb = WeBWorK::DB::Auth->new($courseEnv);
53
54 my $user = $cldb->getUser($userName);
55 my $set = $wwdb->getSet($userName, $setName);
56 my $problem = $wwdb->getProblem($userName, $setName, $problemNumber);
57 my $psvn = $wwdb->getPSVN($userName, $setName);
58 my $permissionLevel = $authdb->getPermissions($userName);
59
60 ##### form processing #####
61
62 # set options from form fields (see comment at top of file for names)
63 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode};
64 my $redisplay = $r->param("redisplay");
65 my $submitAnswers = $r->param("submitAnswers");
66 my $previewAnswers = $r->param("previewAnswers");
67
68 # coerce form fields into CGI::Vars format
69 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
70
71 ##### permissions #####
72
73 # what does the user want to do?
74 my %want = (
75 showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers},
76 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers},
77 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints},
78 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions},
79 recordAnswers => $r->param("recordAnswers") || 1,
80 );
81
82 # are certain options enforced?
83 my %must = (
84 showOldAnswers => 0,
85 showCorrectAnswers => 0,
86 showHints => 0,
87 showSolutions => 0,
88 recordAnswers => mustRecordAnswers($permissionLevel),
89 );
90
91 # does the user have permission to use certain options?
92 my %can = (
93 showOldAnswers => 1,
94 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
95 showHints => 1,
96 showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
97 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
98 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
99 # num_correct+num_incorrect+1 -- as this happens before updating $problem
100 );
101
102 # final values for options
103 my %will;
104 foreach (keys %must) {
105 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
106 #warn "$_: can? $can{$_} want? $want{$_} must? $must{$_} will? $will{$_}\n";
107 }
108
109 ##### sticky answers #####
110
111 if (not $submitAnswers and $will{showOldAnswers}) {
112 # do this only if new answers are NOT being submitted
113 my %oldAnswers = decodeAnswers($problem->last_answer);
114 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
115 }
116
117 ##### translation #####
118
119 my $pg = WeBWorK::PG->new(
120 $courseEnv,
121 $user,
122 $r->param('key'),
123 $set,
124 $problem,
125 $psvn,
126 $formFields,
127 { # translation options
128 displayMode => $displayMode,
129 showHints => $will{showHints},
130 showSolutions => $will{showSolutions},
131 refreshMath2img => $will{showHints} || $will{showSolutions},
132 # try leaving processAnswers on all the time?
133 processAnswers => 1, #$submitAnswers ? 1 : 0,
134 },
135 );
136
137 ##### store fields #####
138
139 $self->{cldb} = $cldb;
140 $self->{wwdb} = $wwdb;
141 $self->{authdb} = $authdb;
142
143 $self->{user} = $user;
144 $self->{set} = $set;
145 $self->{problem} = $problem;
146 $self->{permissionLevel} = $permissionLevel;
147
148 $self->{displayMode} = $displayMode;
149 $self->{redisplay} = $redisplay;
150 $self->{submitAnswers} = $submitAnswers;
151 $self->{previewAnswers} = $previewAnswers;
152 $self->{formFields} = $formFields;
153
154 $self->{want} = \%want;
155 $self->{must} = \%must;
156 $self->{can} = \%can;
157 $self->{will} = \%will;
158
159 $self->{pg} = $pg;
160}
161
162sub if_warnings($$) {
163 my ($self, $arg) = @_;
164 return $self->{pg}->{warnings} ne "";
165}
166
167sub if_errors($$) {
168 my ($self, $arg) = @_;
169 return $self->{pg}->{flags}->{error_flag};
170}
171
172sub head {
173 my $self = shift;
174
175 return $self->{pg}->{head_text} if $self->{pg}->{head_text};
176}
177
178sub path {
179 my $self = shift;
180 my $args = $_[-1];
181 my $setName = $self->{set}->id;
182 my $problemNumber = $self->{problem}->id;
183
184 my $ce = $self->{courseEnvironment};
185 my $root = $ce->{webworkURLs}->{root};
186 my $courseName = $ce->{courseName};
187 return $self->pathMacro($args,
188 "Home" => "$root",
189 $courseName => "$root/$courseName",
190 $setName => "$root/$courseName/$setName",
191 "Problem $problemNumber" => "",
192 );
193}
194
195sub siblings {
196 my $self = shift;
197 my $setName = $self->{set}->id;
198 my $problemNumber = $self->{problem}->id;
199
200 my $ce = $self->{courseEnvironment};
201 my $root = $ce->{webworkURLs}->{root};
202 my $courseName = $ce->{courseName};
203
204 print CGI::strong("Problems"), CGI::br();
205
206 my $wwdb = $self->{wwdb};
207 my $user = $self->{r}->param("user");
208 my @problems;
209 push @problems, $wwdb->getProblem($user, $setName, $_)
210 foreach ($wwdb->getProblems($user, $setName));
211 foreach my $problem (sort { $a->id <=> $b->id } @problems) {
212 print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?"
213 . $self->url_authen_args}, "Problem ".$problem->id), CGI::br();
214 }
215}
216
217sub nav {
218 my $self = shift;
219 my $args = $_[-1];
220 my $setName = $self->{set}->id;
221 my $problemNumber = $self->{problem}->id;
222
223 my $ce = $self->{courseEnvironment};
224 my $root = $ce->{webworkURLs}->{root};
225 my $courseName = $ce->{courseName};
226
227 my $wwdb = $self->{wwdb};
228 my $user = $self->{r}->param("user");
229
230 my @links = ("Problem List" => "$root/$courseName/$setName");
231
232 my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1);
233 my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1);
234 unshift @links, "Previous Problem" => $prevProblem
235 ? "$root/$courseName/$setName/".$prevProblem->id
236 : "";
237 push @links, "Next Problem" => $nextProblem
238 ? "$root/$courseName/$setName/".$nextProblem->id
239 : "";
240
241 return $self->navMacro($args, @links);
242}
8 243
9sub title { 244sub title {
10 my ($self, $problem_set, $problem) = @_; 245 my $self = shift;
11 my $r = $self->{r}; 246 my $setName = $self->{set}->id;
12 my $user = $r->param('user'); 247 my $problemNumber = $self->{problem}->id;
13 return "Problem $problem of problem set $problem_set for $user"; 248
249 return "$setName : Problem $problemNumber";
14} 250}
15 251
16sub body { 252sub body {
17 my ($self, $problem_set, $problem) = @_;
18 my $r = $self->{r};
19 my $courseEnvironment = $self->{courseEnvironment};
20 my $user = $r->param('user');
21
22 print "Problem goes here<p>\n";
23
24 print "<P>Request item<P>\n\n";
25 print "<TABLE border=\"3\">";
26 print $self->print_form_data('<tr><td>','</td><td>','</td></tr>');
27 print "</table>\n";
28 print "<P>\n\ncourseEnvironment<P>\n\n";
29 print pretty_print_rh($courseEnvironment);
30
31 ###########################################################################
32 # The pg problem class should have a method for installing it's problemEnvironment
33 ###########################################################################
34
35 $problemEnvir_rh = defineProblemEnvir($self);
36
37 print "<P>\n\nproblemEnvironment<P>\n\n";
38 print pretty_print_rh($problemEnvir_rh);
39# my $sig = do "pgGenerator.pl" ;
40# print "File not found $1" unless defined(sig);
41# print "Errors $@";
42# print pgHTML();
43
44 "";
45}
46
47
48########################################################################################
49# This is the structure that needs to be filled out in order to call PGtranslator;
50########################################################################################
51
52sub defineProblemEnvir {
53 my $self = shift; 253 my $self = shift;
54 my $r = $self->{r};
55 my $courseEnvironment = $self->{courseEnvironment};
56 my %envir=();
57# $envir{'refSubmittedAnswers'} = $refSubmittedAnswers if defined($refSubmittedAnswers);
58 $envir{'psvnNumber'} = 123456789;
59 $envir{'psvn'} = 123456789;
60 $envir{'studentName'} = 'Jane Doe';
61 $envir{'studentLogin'} = 'jd001m';
62 $envir{'studentID'} = 'xxx-xx-4321';
63 $envir{'sectionName'} = 'gage';
64 $envir{'sectionNumber'} = '111foobar';
65 $envir{'recitationName'} = 'gage_recitation';
66 $envir{'recitationNumber'} = '11_foobar recitation';
67 $envir{'setNumber'} = 'setAlgebraicGeometry';
68 $envir{'questionNumber'} = 43;
69 $envir{'probNum'} = 43;
70 $envir{'openDate'} = 3014438528;
71 $envir{'formattedOpenDate'} = '3/4/02';
72 $envir{'dueDate'} = 4014438528;
73 $envir{'formattedDueDate'} = '10/4/04';
74 $envir{'answerDate'} = 4014438528;
75 $envir{'formattedAnswerDate'} = '10/4/04';
76 $envir{'problemValue'} = 1;
77 $envir{'fileName'} = 'problem1';
78 $envir{'probFileName'} = 'problem1';
79 $envir{'languageMode'} = 'HTML_tth';
80 $envir{'displayMode'} = 'HTML_tth';
81 $envir{'outputMode'} = 'HTML_tth';
82 $envir{'courseName'} = $courseEnvironment ->{courseName};
83 $envir{'sessionKey'} = 'asdf';
84
85# initialize constants for PGanswermacros.pl
86 $envir{'numRelPercentTolDefault'} = .1;
87 $envir{'numZeroLevelDefault'} = 1E-14;
88 $envir{'numZeroLevelTolDefault'} = 1E-12;
89 $envir{'numAbsTolDefault'} = .001;
90 $envir{'numFormatDefault'} = '';
91 $envir{'functRelPercentTolDefault'} = .1;
92 $envir{'functZeroLevelDefault'} = 1E-14;
93 $envir{'functZeroLevelTolDefault'} = 1E-12;
94 $envir{'functAbsTolDefault'} = .001;
95 $envir{'functNumOfPoints'} = 3;
96 $envir{'functVarDefault'} = 'x';
97 $envir{'functLLimitDefault'} = .0000001;
98 $envir{'functULimitDefault'} = .9999999;
99 $envir{'functMaxConstantOfIntegration'} = 1E8;
100# kludge check definition of number of attempts again. The +1 is because this is used before the current answer is evaluated.
101 $envir{'numOfAttempts'} = 2; #&getProblemNumOfCorrectAns($probNum,$psvn)
102 # &getProblemNumOfIncorrectAns($probNum,$psvn)+1;
103
104#
105#
106# defining directorys and URLs
107 $envir{'templateDirectory'} = $courseEnvironment ->{courseDirs}->{templates};
108############ $envir{'classDirectory'} = $Global::classDirectory;
109# $envir{'cgiDirectory'} = $Global::cgiDirectory;
110# $envir{'cgiURL'} = getWebworkCgiURL();
111# $envir{'macroDirectory'} = getCourseMacroDirectory();
112# $envir{'courseScriptsDirectory'} = getCourseScriptsDirectory();
113 $envir{'htmlDirectory'} = $courseEnvironment ->{courseDirectory}->{html};
114# $envir{'htmlURL'} = getCourseHtmlURL();
115# $envir{'tempDirectory'} = getCourseTempDirectory();
116# $envir{'tempURL'} = getCourseTempURL();
117# $envir{'scriptDirectory'} = $Global::scriptDirectory;##omit
118 $envir{'webworkDocsURL'} = 'http://webwork.math.rochester.edu';
119 $envir{'externalTTHPath'} = '/usr/local/bin/tth';
120 254
121 255 # unpack some useful variables
122# 256 my $r = $self->{r};
123 $envir{'inputs_ref'} = $r->param; 257 my $wwdb = $self->{wwdb};
124 $envir{'problemSeed'} = 3245; 258 my $set = $self->{set};
125 $envir{'displaySolutionsQ'} = 1; 259 my $problem = $self->{problem};
126 $envir{'displayHintsQ'} = 1; 260 my $permissionLevel = $self->{permissionLevel};
127 261 my $submitAnswers = $self->{submitAnswers};
128 # here is a way to pass environment variables defined in webworkCourse.ph 262 my $previewAnswers = $self->{previewAnswers};
129# my $k; 263 my %will = %{ $self->{will} };
130# foreach $k (keys %Global::PG_environment ) { 264 my $pg = $self->{pg};
131# $envir{$k} = $Global::PG_environment{$k}; 265
266 ##### translation errors? #####
267
268 if ($pg->{flags}->{error_flag}) {
269 return translationError($pg->{errors}, $pg->{body_text});
132# } 270 }
133 \%envir; 271
134} 272 ##### answer processing #####
135 273
136######################################################################################## 274 # if answers were submitted:
137# This recursive pretty_print function will print a hash and its sub hashes. 275 if ($submitAnswers) {
138######################################################################################## 276 # store answers in DB for sticky answers
139sub pretty_print_rh { 277 my %answersToStore;
140 my $r_input = shift; 278 my %answerHash = %{ $pg->{answers} };
141 my $out = ''; 279 $answersToStore{$_} = $answerHash{$_}->{original_student_ans}
142 if ( not ref($r_input) ) { 280 foreach (keys %answerHash);
143 $out = $r_input; # not a reference 281 my $answerString = encodeAnswers(%answersToStore,
144 } elsif (is_hash_ref($r_input)) { 282 @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} });
145 local($^W) = 0; 283 $problem->last_answer($answerString);
146 $out .= "<TABLE border = \"2\" cellpadding = \"3\" BGCOLOR = \"#FFFFFF\">"; 284 $wwdb->setProblem($problem);
147 foreach my $key (sort keys %$r_input ) { 285
148 $out .= "<tr><TD> $key</TD><TD>=&gt;</td><td>&nbsp;".pretty_print_rh($r_input->{$key}) . "</td></tr>"; 286 # store state in DB if it makes sense
287 if ($will{recordAnswers}) {
288 $problem->attempted(1);
289 $problem->status($pg->{state}->{recorded_score});
290 $problem->num_correct($pg->{state}->{num_of_correct_ans});
291 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
292 $wwdb->setProblem($problem);
293 # write to the transaction log, just to make sure
294 writeLog($self->{courseEnvironment}, "transaction",
295 $problem->id."\t".
296 $problem->set_id."\t".
297 $problem->login_id."\t".
298 $problem->source_file."\t".
299 $problem->value."\t".
300 $problem->max_attempts."\t".
301 $problem->problem_seed."\t".
302 $problem->status."\t".
303 $problem->attempted."\t".
304 $problem->last_answer."\t".
305 $problem->num_correct."\t".
306 $problem->num_incorrect
307 );
149 } 308 }
150 $out .="</table>"; 309 }
151 } elsif (is_array_ref($r_input) ) { 310
152 my @array = @$r_input; 311 ##### output #####
153 $out .= "( " ; 312
154 while (@array) { 313 # attempt summary
155 $out .= pretty_print_rh(shift @array) . " , "; 314 if ($submitAnswers or $will{showCorrectAnswers}) {
315 # print this if user submitted answers OR requested correct answers
316 print $self->attemptResults($pg, $submitAnswers, $will{showCorrectAnswers},
317 $pg->{flags}->{showPartialCorrectAnswers}, 0);
318 } elsif ($previewAnswers) {
319 # print this if user previewed answers
320 print $self->attemptResults($pg, 1, 0, 0, 1);
321 # don't show correctness
322 # don't show correct answers
323 }
324
325 # score summary
326 my $attempts = $problem->num_correct + $problem->num_incorrect;
327 my $attemptsNoun = $attempts != 1 ? "times" : "time";
328 my $lastScore = int ($problem->status * 100) . "%";
329 my ($attemptsLeft, $attemptsLeftNoun);
330 if ($problem->max_attempts == -1) {
331 # unlimited attempts
332 $attemptsLeft = "unlimited";
333 $attemptsLeftNoun = "attempts";
334 } else {
335 $attemptsLeft = $problem->max_attempts - $attempts;
336 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
337 }
338 my $setClosedMessage;
339 if (time < $set->open_date or time > $set->due_date) {
340 $setClosedMessage = "This problem set is closed.";
341 if ($permissionLevel > 0) {
342 $setClosedMessage .= " Since you are a privileged user, additional attempts will be recorded.";
343 } else {
344 $setClosedMessage .= " Additional attempts will not be recorded.";
156 } 345 }
157 $out .= " )"; 346 }
158 } elsif (ref($r_input) eq 'CODE') { 347 print CGI::p(
159 $out = "$r_input"; 348 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
349 $problem->attempted
350 ? "Your recorded score is $lastScore." . CGI::br()
351 : "",
352 "You have $attemptsLeft $attemptsLeftNoun remaining.", CGI::br(),
353 $setClosedMessage,
354 );
355
356 print CGI::hr();
357
358 # main form
359 print
360 CGI::startform("POST", $r->uri),
361 $self->hidden_authen_fields,
362 CGI::p(CGI::i($pg->{result}->{msg})),
363 CGI::p($pg->{body_text}),
364 CGI::p(
365 CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers"),
366 CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers"),
367 ),
368 $self->viewOptions(),
369 CGI::endform();
370
371 # feedback form
372 my $ce = $self->{courseEnvironment};
373 my $root = $ce->{webworkURLs}->{root};
374 my $courseName = $ce->{courseName};
375 my $feedbackURL = "$root/$courseName/feedback/";
376 print
377 CGI::startform("POST", $feedbackURL),
378 $self->hidden_authen_fields,
379 CGI::hidden("module", __PACKAGE__),
380 CGI::hidden("set", $set->id),
381 CGI::hidden("problem", $problem->id),
382 CGI::hidden("displayMode", $self->{displayMode}),
383 CGI::hidden("showOldAnswers", $will{showOldAnswers}),
384 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),
385 CGI::hidden("showHints", $will{showHints}),
386 CGI::hidden("showSolutions", $will{showSolutions}),
387 CGI::p({-align=>"right"},
388 CGI::submit(-name=>"feedbackForm", -label=>"Send Feedback")
389 ),
390 CGI::endform();
391
392 # warning output
393 if ($pg->{warnings} ne "") {
394 print CGI::hr(), warningOutput($pg->{warnings});
395 }
396
397 # debugging stuff
398 #print
399 # CGI::hr(),
400 # CGI::h2("debugging information"),
401 # CGI::h3("form fields"),
402 # ref2string($self->{formFields}),
403 # CGI::h3("user object"),
404 # ref2string($self->{user}),
405 # CGI::h3("set object"),
406 # ref2string($set),
407 # CGI::h3("problem object"),
408 # ref2string($problem),
409 # CGI::h3("PG object"),
410 # ref2string($pg, {'WeBWorK::PG::Translator' => 1});
411
412 return "";
413}
414
415##### output utilities #####
416
417# this is used by ProblemSet.pm too, so don't fuck it up
418sub translationError($$) {
419 my ($error, $details) = @_;
420 return
421 CGI::h2("Software Error"),
422 CGI::p(<<EOF),
423WeBWorK has encountered a software error while attempting to process this problem.
424It is likely that there is an error in the problem itself.
425If you are a student, contact your professor to have the error corrected.
426If you are a professor, please consut the error output below for more informaiton.
427EOF
428 CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
429 CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
430}
431
432# this is used by ProblemSet.pm too, so don't fuck it up
433sub warningOutput($) {
434 my $warnings = shift;
435
436 return
437 CGI::h2("Software Warnings"),
438 CGI::p(<<EOF),
439WeBWorK has encountered warnings while attempting to process this problem.
440It is likely that this indicates an error or ambiguity in the problem itself.
441If you are a student, contact your professor to have the problem corrected.
442If you are a professor, please consut the error output below for more informaiton.
443EOF
444 CGI::h3("Warning messages"),
445 CGI::blockquote(CGI::pre($warnings)),
446 ;
447}
448
449sub attemptResults($$$$$) {
450 my $self = shift;
451 my $pg = shift;
452 my $showAttemptAnswers = shift;
453 my $showCorrectAnswers = shift;
454 my $showAttemptResults = $showAttemptAnswers && shift;
455 my $showAttemptPreview = shift || 0;
456 my $problemResult = $pg->{result}; # the overall result of the problem
457 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
458
459 my $header = CGI::th("answer");
460 $header .= $showAttemptAnswers ? CGI::th("attempt") : "";
461 $header .= $showAttemptPreview ? CGI::th("preview") : "";
462 $header .= $showCorrectAnswers ? CGI::th("correct") : "";
463 $header .= $showAttemptResults ? CGI::th("result") : "";
464 $header .= $showAttemptAnswers ? CGI::th("messages") : "";
465 my @tableRows = ( $header );
466 my $numCorrect;
467 foreach my $name (@answerNames) {
468 my $answerResult = $pg->{answers}->{$name};
469 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
470 my $preview = ($showAttemptPreview
471 ? $self->previewAnswer($answerResult)
472 : "");
473 my $correctAnswer = $answerResult->{correct_ans};
474 my $answerScore = $answerResult->{score};
475 my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : "";
476
477 $numCorrect += $answerScore > 0;
478 my $resultString = $answerScore ? "correct" : "incorrect";
479
480 # get rid of the goofy prefix on the answer names (supposedly, the format
481 # of the answer names is changeable. this only fixes it for "AnSwEr"
482 $name =~ s/^AnSwEr//;
483
484 my $row = CGI::td($name);
485 $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : "";
486 $row .= $showAttemptPreview ? CGI::td($preview) : "";
487 $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : "";
488 $row .= $showAttemptResults ? CGI::td($resultString) : "";
489 $row .= $answerMessage ? CGI::td($answerMessage) : "";
490 push @tableRows, $row;
491 }
492
493 my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions";
494 my $scorePercent = int ($problemResult->{score} * 100) . "\%";
495 my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of "
496 . scalar @answerNames . " correct, for a score of $scorePercent.";
497 return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary);
498}
499
500sub viewOptions($) {
501 my $self = shift;
502 my $displayMode = $self->{displayMode};
503 my %must = %{ $self->{must} };
504 my %can = %{ $self->{can} };
505 my %will = %{ $self->{will} };
506
507 my $optionLine;
508 $can{showOldAnswers} and $optionLine .= join "",
509 "Show: &nbsp;",
510 CGI::checkbox(
511 -name => "showOldAnswers",
512 -checked => $will{showOldAnswers},
513 -label => "Saved answers",
514 ), "&nbsp;&nbsp;";
515 $can{showCorrectAnswers} and $optionLine .= join "",
516 CGI::checkbox(
517 -name => "showCorrectAnswers",
518 -checked => $will{showCorrectAnswers},
519 -label => "Correct answers",
520 ), "&nbsp;&nbsp;";
521 $can{showHints} and $optionLine .= join "",
522 CGI::checkbox(
523 -name => "showHints",
524 -checked => $will{showHints},
525 -label => "Hints",
526 ), "&nbsp;&nbsp;";
527 $can{showSolutions} and $optionLine .= join "",
528 CGI::checkbox(
529 -name => "showSolutions",
530 -checked => $will{showSolutions},
531 -label => "Solutions",
532 ), "&nbsp;&nbsp;";
533 $optionLine and $optionLine .= join "", CGI::br();
534
535 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"},
536 "View equations as: &nbsp;",
537 CGI::radio_group(
538 -name => "displayMode",
539 -values => ['plainText', 'formattedText', 'images'],
540 -default => $displayMode,
541 -labels => {
542 plainText => "plain text",
543 formattedText => "formatted text",
544 images => "images",
545 }
546 ), CGI::br(),
547 $optionLine,
548 CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"),
549 );
550}
551
552sub previewAnswer($$) {
553 my ($self, $answerResult) = @_;
554 my $ce = $self->{courseEnvironment};
555 my $user = $self->{user};
556 my $set = $self->{set};
557 my $problem = $self->{problem};
558 my $displayMode = $self->{displayMode};
559
560 # note: right now, we have to do things completely differently when we are
561 # rendering math from INSIDE the translator and from OUTSIDE the translator.
562 # so we'll just deal with each case explicitly here. there's some code
563 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
564
565 my $tex = $answerResult->{preview_latex_string};
566
567 if ($displayMode eq "plainText") {
568 return $tex;
569 } elsif ($displayMode eq "formattedText") {
570 my $tthCommand = $ce->{externalPrograms}->{tth}
571 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
572 . "\\($tex\\)\n"
573 . "END_OF_INPUT\n";
574
575
576 # call tth
577 my $result = `$tthCommand`;
578 if ($?) {
579 return "<b>[tth failed: $? $@]</b>";
580 }
581 return $result;
582 } elsif ($displayMode eq "images") {
583 # how are we going to name this?
584 my $targetPathCommon = "/png/"
585 . $user->id . "."
586 . $set->id . "."
587 . $problem->id . "."
588 . $answerResult->{ans_name} . ".png";
589
590 # figure out where to put things
591 my $wd = tempdir("webwork-dvipng-XXXXXXXX", DIR => $ce->{courseDirs}->{html_temp});
592 my $latex = $ce->{externalPrograms}->{latex};
593 my $dvipng = $ce->{externalPrograms}->{dvipng};
594 my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon;
595 # should use surePathToTmpFile, but we have to
596 # isolate it from the problem enivronment first
597 my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon;
598
599 # call dvipng to generate a preview
600 dvipng($wd, $latex, $dvipng, $tex, $targetPath);
601 if (-e $targetPath) {
602 return "<img src=\"$targetURL\" alt=\"$tex\" />";
160 } else { 603 } else {
161 $out = $r_input; 604 return "<b>[math2img failed]</b>";
162 } 605 }
163 $out; 606 }
164} 607}
165 608
166sub is_hash_ref { 609##### permission queries #####
167 my $in =shift; 610
168 my $save_SIG_die_trap = $SIG{__DIE__}; 611# this stuff should be abstracted out into the permissions system
169 $SIG{__DIE__} = sub {CORE::die(@_) }; 612# however, the permission system only knows about things in the
170 my $out = eval{ %{ $in } }; 613# course environment and the username. hmmm...
171 $out = ($@ eq '') ? 1 : 0; 614
172 $@=''; 615# also, i should fix these so that they have a consistent calling
173 $SIG{__DIE__} = $save_SIG_die_trap; 616# format -- perhaps:
174 $out; 617# canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
618
619sub canShowCorrectAnswers($$) {
620 my ($permissionLevel, $answerDate) = @_;
621 return $permissionLevel > 0 || time > $answerDate;
175} 622}
176sub is_array_ref { 623
177 my $in =shift; 624sub canShowSolutions($$) {
178 my $save_SIG_die_trap = $SIG{__DIE__}; 625 my ($permissionLevel, $answerDate) = @_;
179 $SIG{__DIE__} = sub {CORE::die(@_) }; 626 return canShowCorrectAnswers($permissionLevel, $answerDate);
180 my $out = eval{ @{ $in } };
181 $out = ($@ eq '') ? 1 : 0;
182 $@='';
183 $SIG{__DIE__} = $save_SIG_die_trap;
184 $out;
185} 627}
628
629sub canRecordAnswers($$$$$) {
630 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
631 my $permHigh = $permissionLevel > 0;
632 my $timeOK = time >= $openDate && time <= $dueDate;
633 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
634 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
635 return $recordAnswers;
636}
637
638sub mustRecordAnswers($) {
639 my ($permissionLevel) = @_;
640 return $permissionLevel == 0;
641}
642
1861; 6431;

Legend:
Removed from v.388  
changed lines
  Added in v.683

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9