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

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

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

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

Legend:
Removed from v.1507  
changed lines
  Added in v.4031

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9