[system] / trunk / webwork-modperl / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

Annotation of /trunk/webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3653 - (view) (download) (as text)

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9