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

Diff of /trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

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

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

Legend:
Removed from v.717  
changed lines
  Added in v.4389

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9