[system] / branches / rel-2-2-dev / webwork2 / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

Diff of /branches/rel-2-2-dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

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

Legend:
Removed from v.1016  
changed lines
  Added in v.4070

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9