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

Annotation of /branches/gage_dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4235 - (view) (download) (as text)
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9