[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 399 Revision 1128
1################################################################################
2# WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
3# $Id$
4################################################################################
5
1package WeBWorK::ContentGenerator::Problem; 6package WeBWorK::ContentGenerator::Problem;
2our @ISA = qw(WeBWorK::ContentGenerator); 7use base qw(WeBWorK::ContentGenerator);
8
9=head1 NAME
10
11WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
12
13=cut
3 14
4use strict; 15use strict;
5use warnings; 16use warnings;
6use lib '/home/malsyned/xmlrpc/daemon'; 17use CGI qw();
7use lib '/Users/gage/webwork-modperl/lib'; 18use File::Path qw(rmtree);
8use PGtranslator5; 19use File::Temp qw(tempdir);
9use WeBWorK::ContentGenerator; 20use WeBWorK::Form;
10use Apache::Constants qw(:common); 21use WeBWorK::PG;
22use WeBWorK::PG::IO;
23use WeBWorK::Utils qw(writeLog encodeAnswers decodeAnswers ref2string);
24use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
11 25
12############################################################################### 26############################################################
13# Configuration 27#
28# user
29# effectiveUser
30# key
31#
32# displayMode
33# showOldAnswers
34# showCorrectAnswers
35# showHints
36# showSolutions
37#
38# AnSwEr# - answer blanks in problem
39#
40# redisplay - name of the "Redisplay Problem" button
41# submitAnswers - name of "Submit Answers" button
42# checkAnswers - name of the "Check Answers" button
43# previewAnswers - name of the "Preview Answers" button
44#
14############################################################################### 45############################################################
15my $USER_DIRECTORY = '/Users/gage';
16my $COURSE_SCRIPTS_DIRECTORY = "$USER_DIRECTORY/webwork/system/courseScripts/";
17my $MACRO_DIRECTORY = "$USER_DIRECTORY/webwork-modperl/courses/demoCourse/templates/macros/";
18my $TEMPLATE_DIRECTORY = "$USER_DIRECTORY/rochester_problib/";
19my $TEMP_URL = "http://127.0.0.1/~gage/rochester_problibtmp/";
20##my $HTML_DIRECTORY = "/Users/gage/Sites/rochester_problib/" #already obtained from courseEnvironment
21my $HTML_URL = "http://127.0.0.1/~gage/rochester_problib/";
22my $TEMP_DIRECTORY = ""; # has to be here... for now
23 46
24############################################################################### 47sub pre_header_initialize {
25# End configuration 48 my ($self, $setName, $problemNumber) = @_;
26############################################################################### 49 my $r = $self->{r};
50 my $courseEnv = $self->{ce};
51 my $db = $self->{db};
52 my $userName = $r->param('user');
53 my $effectiveUserName = $r->param('effectiveUser');
54 my $key = $r->param('key');
55 my $user = $db->getUser($userName);
56 my $effectiveUser = $db->getUser($effectiveUserName);
57
58 # obtain the effective user set, or if that is not yet defined obtain global set
59 my $set = $db->getMergedSet($effectiveUserName, $setName);
60 unless (defined $set) {
61 my $userSetClass = $courseEnv->{dbLayout}->{set_user}->{record};
62 $set = global2user($userSetClass, $db->getGlobalSet($setName));
63 $set->psvn('000');
64 }
65 my $psvn = $set->psvn();
66
67 # obtain the effective user problem, or if that is not yet defined obtain global problem
68 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber);
69 unless (defined $problem) {
70 my $userProblemClass = $courseEnv->{dbLayout}->{problem_user}->{record};
71 $problem = global2user($userProblemClass, $db->getGlobalProblem($setName,$problemNumber));
72
73# $problem->max_attempts(-1); # default is infinite number of attempts
74# $problem->value;
75# $problem->problem_seed;
76# $problem->source_file;
77 $problem->user_id($userName); # is this the right value for this unassigned problem? FIXME
78 $problem->status(0);
79 $problem->attempted(0);
80 $problem->num_correct(0);
81 $problem->num_incorrect(0);
82 $problem->last_answer(' ');
83 }
84 #$problem = $db->getGlobalProblem($setName, $problemNumber) unless defined($problem);
85 # FIXME
86 # a better solution at this point would be to take set and problem, convert them to global_user type
87 # so that they have the right methods.
88 # Stuff the local copy of $set and $problem with default data where it won't have been defined
89 # Make sure that nothing bad is stored back in the database.
90 # It would be nice to store lastAnswer somewhere -- perhaps that could be done as a special case.
91
92
93 # This supplies a psvn if $set doesn't have it. Unfortunately the problem is called on to provide
94 # data in many places and it might not even have methods defined.
95
96 # global sets will not have a defined psvn
97# my $psvn;
98# if ($set->can('psvn') ) {
99# $psvn = $set->psvn();
100# } else { # we are viewing an unassigned problem set, psvn's are irrelevant
101# $psvn = '0000';
102# }
103
104 my $permissionLevel = $db->getPermissionLevel($userName)->permission();
105
106 $self->{userName} = $userName;
107 $self->{user} = $user;
108 $self->{effectiveUser} = $effectiveUser;
109 $self->{set} = $set;
110 $self->{problem} = $problem;
111 $self->{permissionLevel} = $permissionLevel;
112
113 ##### form processing #####
114
115 # set options from form fields (see comment at top of file for names)
116 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode};
117 my $redisplay = $r->param("redisplay");
118 my $submitAnswers = $r->param("submitAnswers");
119 my $checkAnswers = $r->param("checkAnswers");
120 my $previewAnswers = $r->param("previewAnswers");
121
122 # fields which may be defined when using Problem Editor
123 my $override_seed = ($permissionLevel>=10) ? $r->param('problemSeed') : undef;
124 my $override_problem_source = ($permissionLevel>=10) ? $r->param('sourceFilePath') : undef;
125 my $editMode = undef;
126 my $submit_button = $r->param('submit_button');
127 if ( defined($submit_button ) ) {
128 $editMode = "temporaryFile" if $submit_button eq 'Refresh';
129 $editMode = 'savedFile' if $submit_button eq 'Save';
130 }
131
132 #override using the source file data from the form field
133 $problem->source_file($override_problem_source) if defined($override_problem_source);
134 $problem->problem_seed($override_seed) if defined($override_seed);
135
136 # store path to source file for title.
137 $self->{problem_source_name} = $problem->source_file;
138 $self->{edit_mode} = $editMode;
139# $self->{current_problem_source} = (defined($override_problem_source) ) ?
140# $override_problem_source :
141# $problem->source_file;
142 # coerce form fields into CGI::Vars format
143 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
144
145 $self->{displayMode} = $displayMode;
146 $self->{redisplay} = $redisplay;
147 $self->{submitAnswers} = $submitAnswers;
148 $self->{checkAnswers} = $checkAnswers;
149 $self->{previewAnswers} = $previewAnswers;
150 $self->{formFields} = $formFields;
151
152
153 ##### permissions #####
154
155 # are we allowed to view this problem?
156 $self->{isOpen} = time >= $set->open_date || $permissionLevel > 0;
157 return unless $self->{isOpen};
158
159 # what does the user want to do?
160 my %want = (
161 showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers},
162 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers},
163 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints},
164 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions},
165 recordAnswers => $submitAnswers,
166 checkAnswers => $checkAnswers,
167 );
168
169 # are certain options enforced?
170 my %must = (
171 showOldAnswers => 0,
172 showCorrectAnswers => 0,
173 showHints => 0,
174 showSolutions => 0,
175 recordAnswers => mustRecordAnswers($permissionLevel),
176 checkAnswers => 0,
177 );
178
179 # does the user have permission to use certain options?
180 my %can = (
181 showOldAnswers => 1,
182 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
183 showHints => 1,
184 showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
185 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
186 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
187 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
188 checkAnswers => canCheckAnswers($permissionLevel, $set->answer_date),
189 );
190
191 # final values for options
192 my %will;
193 foreach (keys %must) {
194 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
195 }
196
197 ##### sticky answers #####
198
199 if (not $submitAnswers and $will{showOldAnswers}) {
200 # do this only if new answers are NOT being submitted
201 my %oldAnswers = decodeAnswers($problem->last_answer);
202 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
203 }
204
205 ##### translation #####
206
207 my $pg = WeBWorK::PG->new(
208 $courseEnv,
209 $effectiveUser,
210 $key,
211 $set,
212 $problem,
213 $psvn,
214 $formFields,
215 { # translation options
216 displayMode => $displayMode,
217 override_seed => $override_seed,
218 override_problem_source =>$override_problem_source,
219 showHints => $will{showHints},
220 showSolutions => $will{showSolutions},
221 refreshMath2img => $will{showHints} || $will{showSolutions},
222 processAnswers => 1,
223 },
224 );
225
226 ##### fix hint/solution options #####
227
228 $can{showHints} &&= $pg->{flags}->{hintExists};
229 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
230
231 ##### store fields #####
232
233 $self->{want} = \%want;
234 $self->{must} = \%must;
235 $self->{can} = \%can;
236 $self->{will} = \%will;
237
238 $self->{pg} = $pg;
239}
240
241sub if_warnings($$) {
242 my ($self, $arg) = @_;
243 return 0 unless $self->{isOpen};
244 return $self->{pg}->{warnings} ne "";
245}
246
247sub if_errors($$) {
248 my ($self, $arg) = @_;
249 return 0 unless $self->{isOpen};
250 return $self->{pg}->{flags}->{error_flag};
251}
252
253sub head {
254 my $self = shift;
255 return "" unless $self->{isOpen};
256 return $self->{pg}->{head_text} if $self->{pg}->{head_text};
257}
258
259sub path {
260 my $self = shift;
261 my $args = $_[-1];
262 my $setName = $self->{set}->set_id;
263 my $problemNumber = $self->{problem}->problem_id;
264
265 my $ce = $self->{ce};
266 my $root = $ce->{webworkURLs}->{root};
267 my $courseName = $ce->{courseName};
268 return $self->pathMacro($args,
269 "Home" => "$root",
270 $courseName => "$root/$courseName",
271 $setName => "$root/$courseName/$setName",
272 "Problem $problemNumber" => "",
273 );
274}
275
276sub siblings {
277 my $self = shift;
278 my $setName = $self->{set}->set_id;
279 my $problemNumber = $self->{problem}->problem_id;
280
281 my $ce = $self->{ce};
282 my $db = $self->{db};
283 my $root = $ce->{webworkURLs}->{root};
284 my $courseName = $ce->{courseName};
285
286 print CGI::strong("Problems"), CGI::br();
287
288 my $effectiveUser = $self->{r}->param("effectiveUser");
289 my @problems;
290 push @problems, $db->getMergedProblem($effectiveUser, $setName, $_)
291 foreach ($db->listUserProblems($effectiveUser, $setName));
292 foreach my $problem (sort { $a->problem_id <=> $b->problem_id } @problems) {
293 print CGI::a({-href=>"$root/$courseName/$setName/".$problem->problem_id."/?"
294 . $self->url_authen_args . "&displayMode=" . $self->{displayMode}},
295 "Problem ".$problem->problem_id), CGI::br();
296 }
297}
298
299sub nav {
300 my $self = shift;
301 my $args = $_[-1];
302 my $setName = $self->{set}->set_id;
303 my $problemNumber = $self->{problem}->problem_id;
304
305 my $ce = $self->{ce};
306 my $db = $self->{db};
307 my $root = $ce->{webworkURLs}->{root};
308 my $courseName = $ce->{courseName};
309
310 my $wwdb = $self->{wwdb};
311 my $effectiveUser = $self->{r}->param("effectiveUser");
312 my $tail = "&displayMode=".$self->{displayMode};
313
314 my @links = ("Problem List" , "$root/$courseName/$setName", "navProbList");
315
316 my $prevProblem = $db->getMergedProblem($effectiveUser, $setName, $problemNumber-1);
317 my $nextProblem = $db->getMergedProblem($effectiveUser, $setName, $problemNumber+1);
318 unshift @links, "Previous Problem" , ($prevProblem
319 ? "$root/$courseName/$setName/".$prevProblem->problem_id
320 : "") , "navPrev";
321 push @links, "Next Problem" , ($nextProblem
322 ? "$root/$courseName/$setName/".$nextProblem->problem_id
323 : "") , "navNext";
324
325 return $self->navMacro($args, $tail, @links);
326}
27 327
28sub title { 328sub title {
29 my ($self, $problem_set, $problem) = @_; 329 my $self = shift;
30 my $r = $self->{r}; 330 my $setName = $self->{set}->set_id;
31 my $user = $r->param('user');
32 return "Problem $problem of problem set $problem_set for $user";
33}
34
35###############################################################################
36#
37# INITIALIZATION
38#
39# The following code initializes an instantiation of PGtranslator5 in the
40# parent process. This initialized object is then share with each of the
41# children forked from this parent process by the daemon.
42#
43# As far as I can tell, the child processes don't share any variable values even
44# though their namespaces are the same.
45###############################################################################
46# First some dummy values to use for testing.
47# These should be available from the problemEnvironment(it might be ok to assume that PG and dangerousMacros
48# live in the courseScripts (system level macros) directory.
49
50#print STDERR "Begin intitalization\n";
51my $dummy_envir = { courseScriptsDirectory => $COURSE_SCRIPTS_DIRECTORY,
52 displayMode => 'HTML_tth',
53 macroDirectory => $MACRO_DIRECTORY,
54 cgiURL => 'foo_cgiURL'};
55
56
57my $PG_PL = "${COURSE_SCRIPTS_DIRECTORY}PG.pl";
58my $DANGEROUS_MACROS_PL = "${COURSE_SCRIPTS_DIRECTORY}dangerousMacros.pl";
59my @MODULE_LIST = ( "Exporter", "DynaLoader", "GD", "WWPlot", "Fun",
60 "Circle", "Label", "PGrandom", "Units", "Hermite",
61 "List", "Match","Multiple", "Select", "AlgParser",
62 "AnswerHash", "Fraction", "VectorField", "Complex1",
63 "Complex", "MatrixReal1", "Matrix","Distributions",
64 "Regression"
65);
66my @EXTRA_PACKAGES = ( "AlgParserWithImplicitExpand", "Expr",
67 "ExprWithImplicitExpand", "AnswerEvaluator",
68
69);
70my $INITIAL_MACRO_PACKAGES = <<END_OF_TEXT;
71 DOCUMENT();
72 loadMacros(
73 "PGbasicmacros.pl",
74 "PGchoicemacros.pl",
75 "PGanswermacros.pl",
76 "PGnumericalmacros.pl",
77 "PGgraphmacros.pl",
78 "PGauxiliaryFunctions.pl",
79 "PGmatrixmacros.pl",
80 "PGcomplexmacros.pl",
81 "PGstatisticsmacros.pl"
82
83 );
84
85 TEXT("Hello world");
86
87 ENDDOCUMENT();
88
89END_OF_TEXT
90 331
91#These here documents have their drawbacks. KEEP END_OF_TEXT left justified!!!!!! 332 my $file_action;
92 333 my $edit_mode = $self->{edit_mode};
93############################################################################### 334 if ( not defined($edit_mode) ) {
94# Now to define the body subroutine which does the hard work. 335 $file_action = '';
95############################################################################### 336 } elsif ( $edit_mode eq 'temporaryFile') {
96 337 $file_action .= 'Editing temporary file : '. CGI::br() . $self->{problem_source_name};
97 338 } elsif ( $edit_mode eq 'savedFile' ){
98#my $SOURCE1 = $INITIAL_MACRO_PACKAGES; 339 $file_action .= 'Problem saved to : '. CGI::br() . $self->{problem_source_name};
340 }
341 my $problemNumber = $self->{problem}->problem_id . " : " . $file_action;
342
343 return "$setName : Problem $problemNumber";
344}
99 345
100sub body { 346sub body {
101 my ($self, $problem_set, $problem) = @_;
102 my $r = $self->{r};
103 my $courseEnvironment = $self->{courseEnvironment};
104 my $user = $r->param('user');
105
106 my $rh = {}; # this needs to be set to a hash containing CGI params
107
108
109 my $SOURCE1 = readFile("$problem_set/$problem.pg");
110 print STDERR "SOURCEFILE: \n$SOURCE1\n\n";
111
112 ###########################################################################
113 # The pg problem class should have a method for installing it's problemEnvironment
114 ###########################################################################
115
116 my $problemEnvir_rh = defineProblemEnvir($self);
117
118
119 ##################################################################################
120 # Prime the PGtranslator object and set it loose
121 ##################################################################################
122
123
124 ###############################################################################
125
126 ###############################################################################
127 #Create the PG translator.
128 ###############################################################################
129
130 my $pt = new PGtranslator5; #pt stands for problem translator;
131
132
133 # All of these hard coded directories need to be drawn from courseEnvironment.
134 # In addition I don't think that PGtranslator uses this stack internally yet.
135 # Passing these directories through the problemEnvironment variable is what
136 # is currently being done, but I don't think it is quite right, at least for most
137 # of them.
138
139
140 $pt ->rh_directories( { courseScriptsDirectory => $COURSE_SCRIPTS_DIRECTORY,
141 macroDirectory => $MACRO_DIRECTORY,
142 ,
143 templateDirectory => $TEMPLATE_DIRECTORY,
144 tempDirectory => $TEMP_DIRECTORY,
145 }
146 );
147
148 ###############################################################################
149 # First we load the modules from courseScripts directory.
150 # These do the "heavy lifting" in terms of formatting, creating graphs, and
151 # performing other heavy duty algorithms.
152 #
153 ###############################################################################
154
155 $pt -> evaluate_modules( @MODULE_LIST);
156 $pt -> load_extra_packages( @EXTRA_PACKAGES );
157
158 ###############################################################################
159 # Load the environment constants. Some are used by the PGtranslator object but
160 # most of them are installed inside the Safe compartment where the problem
161 # runs.
162 ###############################################################################
163 #$pt -> environment($dummy_envir);
164 $pt -> environment($problemEnvir_rh);
165
166
167 # I've forgotten what this does exactly :-)
168 $pt->initialize();
169
170 ###############################################################################
171 # PG.pl contains the basic code which defines the problem interface, input and output.
172 # dangerousMacros.pl contains subroutines which have access to the hard drive and
173 # and the directory structure. All use of external resources by the problem is supposed
174 # to go through these subroutines. The idea is to put the potentially dangerous
175 # algorithms in on place so they can be watched closely.
176 # These two files are evaluated in the Safe compartment without any restrictions.
177 # They have full use of the perl commands.
178 ###############################################################################
179 my $loadErrors = $pt -> unrestricted_load($PG_PL );
180 print STDERR "$loadErrors\n" if ($loadErrors);
181 $loadErrors = $pt -> unrestricted_load($DANGEROUS_MACROS_PL);
182 print STDERR "$loadErrors\n" if ($loadErrors);
183
184 ###############################################################################
185 # Now set the mask to restrict the operations which can be performed within
186 # a problem or a macro file.
187 ###############################################################################
188 $pt-> set_mask();
189
190 # print "\nPG.pl: $PG_PL<br>\n";
191 # print "DANGEROUS_MACROS_PL: $DANGEROUS_MACROS_PL<br>\n";
192 # print "Print dummy environment<br>\n";
193 # print pretty_print_rh($dummy_envir), "<p>\n\n";
194
195 # Read in the source code for the problem
196
197 #$INITIAL_MACRO_PACKAGES =~ tr /\r/\n/; # change everything to unix line endings.
198 $SOURCE1 =~ tr /\r/\n/;
199 #print STDERR "Source again \n $SOURCE1";
200 $pt->source_string( $SOURCE1 );
201
202 ###############################################################################
203 # Install a safety filter for screening student answers. The default is now the blank
204 # filter since the answer evaluators do a pretty good job of recompiling and screening
205 # student's answers. Still, you could prohibit back ticks, or something of the kind.
206 ###############################################################################
207
208 $pt ->rf_safety_filter( \&safetyFilter); # install blank safety filter
209
210
211 print STDERR "New PGtranslator object inititialization completed.<br>\n";
212 ################################################################################
213 ## This ends the initialization of the PGtranslator object
214 ################################################################################
215
216
217 ################################################################################
218 # Run the problem (output the html text) but also store it within the object.
219 # The correct answers are also calculated and stored within the object
220 ################################################################################
221 $pt ->translate();
222
223 #print problem output
224 print "Problem goes here<p>\n";
225 print "Problem output <br>\n";
226 print "################################################################################<br><br>";
227 print ${$pt->r_text()};
228 print "<br><br>################################################################################<br>";
229 print "<p>End of problem output<br>";
230
231
232 #print source code
233 print "Source code<pre>\n";
234 print $SOURCE1;
235 print "</pre>End source code<p>";
236 ################################################################################
237 # The format for the output is described here. We'll need a local variable
238 # to handle the warnings. From within the problem the warning command
239 # has been slaved to the __WARNINGS__ routine which is defined in Global.
240 # We'll need to provide an alternate mechanism.
241 # The base64 encoding is only needed for xml transmission.
242 ################################################################################
243 print "################################################################################<br>";
244 print "Warnings output<br>";
245 my $WARNINGS = "Let this be a warning:";
246
247 print $WARNINGS;
248
249 ################################################################################
250 # Install the standard problem grader. See gage/xmlrpc/daemon.pm or processProblem8 for detailed
251 # code on how to choose which problem grader to install, depending on courseEnvironment and problem data.
252 # See also PG.pl which provides for problem by problem overrides.
253 ################################################################################
254
255 $pt->rf_problem_grader($pt->rf_std_problem_grader);
256
257 ################################################################################
258 # creates and stores a hash of answer results inside the object: $rh_answer_results
259 ################################################################################
260 $pt -> process_answers($rh->{envir}->{inputs_ref});
261
262
263 # THE UPDATE AND GRADING LOGIC COULD USE AN OVERHAUL. IT WAS SOMEWHAT CONSTRAINED
264 # BY LEGACY CONDITIONS IN THE ORIGINAL PROCESSPROBLEM8. IT'S NOT BAD
265 # BUT IT COULD PROBABLY BE MADE A LITTLE MORE STRAIGHT FORWARD.
266 ################################################################################
267 # updates the problem state stored by the translator object from the problemEnvironment data
268 ################################################################################
269
270 # $pt->rh_problem_state({ recorded_score => $rh->{problem_state}->{recorded_score},
271 # num_of_correct_ans => $rh->{problem_state}->{num_of_correct_ans} ,
272 # num_of_incorrect_ans => $rh->{problem_state}->{num_of_incorrect_ans}
273 # } );
274 ################################################################################
275 # grade the problem (and update the problem state again.)
276 ################################################################################
277
278 # Define an entry order -- the default is the order they are received from the browser.
279 # (Which as I understand it is NOT guaranteed to be the Left->Right Up-> Down order we're
280 # used to in the West.
281
282 my %PG_FLAGS = $pt->h_flags;
283 my $ra_answer_entry_order = ( defined($PG_FLAGS{ANSWER_ENTRY_ORDER}) ) ?
284 $PG_FLAGS{ANSWER_ENTRY_ORDER} : [ keys %{$pt->rh_evaluated_answers} ] ;
285 # Decide whether any answers were submitted.
286 my $answers_submitted = 0;
287 $answers_submitted = 1 if defined( $rh->{answer_form_submitted} ) and 1 == $rh->{answer_form_submitted};
288 # If there are answers, grade them
289 my ($rh_problem_result,$rh_problem_state) = $pt->grade_problem( answers_submitted => $answers_submitted,
290 ANSWER_ENTRY_ORDER => $ra_answer_entry_order
291 ); # grades the problem.
292
293 # Output format expected by Webwork.pm (and I believe processProblem8, but check.)
294 my $out = {
295 text => ${$pt ->r_text()}, # encode_base64( ${$pt ->r_text()} ),
296 header_text => $pt->r_header, # encode_base64( ${ $pt->r_header } ),
297 answers => $pt->rh_evaluated_answers,
298 errors => $pt-> errors(),
299 WARNINGS => $WARNINGS, #encode_base64($WARNINGS ),
300 problem_result => $rh_problem_result,
301 problem_state => $rh_problem_state,
302 PG_flag => \%PG_FLAGS
303 };
304 ##########################################################################################
305 # Debugging printout of environment tables
306 ##########################################################################################
307
308 print "<P>Request item<P>\n\n";
309 print "<TABLE border=\"3\">";
310 print $self->print_form_data('<tr><td>','</td><td>','</td></tr>');
311 print "</table>\n";
312 print "path info <br>\n";
313 print $r->path_info();
314 print "<P>\n\ncourseEnvironment<P>\n\n";
315 print pretty_print_rh($courseEnvironment);
316 print "<P>\n\nproblemEnvironment<P>\n\n";
317 print pretty_print_rh($problemEnvir_rh);
318
319 ##########################################################################################
320 # End
321 ##########################################################################################
322 "";
323}
324# End the"body" routine for the Problem object.
325
326
327sub safetyFilter {
328 my $answer = shift; # accepts one answer and checks it
329 my $submittedAnswer = $answer;
330 $answer = '' unless defined $answer;
331 my ($errorno);
332 $answer =~ tr/\000-\037/ /;
333 #### Return if answer field is empty ########
334 unless ($answer =~ /\S/) {
335# $errorno = "<BR>No answer was submitted.";
336 $errorno = 0; ## don't report blank answer as error
337
338 return ($answer,$errorno);
339 }
340 ######### replace ^ with ** (for exponentiation)
341 # $answer =~ s/\^/**/g;
342 ######### Return if forbidden characters are found
343 unless ($answer =~ /^[a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\(\)]+$/ ) {
344 $answer =~ tr/a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\(\)/#/c;
345 $errorno = "<BR>There are forbidden characters in your answer: $submittedAnswer<BR>";
346
347 return ($answer,$errorno);
348 }
349
350 $errorno = 0;
351 return($answer, $errorno);
352}
353
354
355
356
357########################################################################################
358# This is the problemEnvironment structure that needs to be filled out in order to provide
359# information to PGtranslator which in turn supports the problem environment
360########################################################################################
361
362sub defineProblemEnvir {
363 my $self = shift; 347 my $self = shift;
364 my $r = $self->{r};
365 my $courseEnvironment = $self->{courseEnvironment};
366 my %envir=();
367# $envir{'refSubmittedAnswers'} = $refSubmittedAnswers if defined($refSubmittedAnswers);
368 $envir{'psvnNumber'} = 123456789;
369 $envir{'psvn'} = 123456789;
370 $envir{'studentName'} = 'Jane Doe';
371 $envir{'studentLogin'} = 'jd001m';
372 $envir{'studentID'} = 'xxx-xx-4321';
373 $envir{'sectionName'} = 'gage';
374 $envir{'sectionNumber'} = '111foobar';
375 $envir{'recitationName'} = 'gage_recitation';
376 $envir{'recitationNumber'} = '11_foobar recitation';
377 $envir{'setNumber'} = 'setAlgebraicGeometry';
378 $envir{'questionNumber'} = 43;
379 $envir{'probNum'} = 43;
380 $envir{'openDate'} = 3014438528;
381 $envir{'formattedOpenDate'} = '3/4/02';
382 $envir{'dueDate'} = 4014438528;
383 $envir{'formattedDueDate'} = '10/4/04';
384 $envir{'answerDate'} = 4014438528;
385 $envir{'formattedAnswerDate'} = '10/4/04';
386 $envir{'problemValue'} = 1;
387 $envir{'fileName'} = 'problem1';
388 $envir{'probFileName'} = 'problem1';
389 $envir{'languageMode'} = 'HTML_tth';
390 $envir{'displayMode'} = 'HTML_tth';
391 $envir{'outputMode'} = 'HTML_tth';
392 $envir{'courseName'} = $courseEnvironment ->{courseName};
393 $envir{'sessionKey'} = 'asdf';
394
395# initialize constants for PGanswermacros.pl
396 $envir{'numRelPercentTolDefault'} = .1;
397 $envir{'numZeroLevelDefault'} = 1E-14;
398 $envir{'numZeroLevelTolDefault'} = 1E-12;
399 $envir{'numAbsTolDefault'} = .001;
400 $envir{'numFormatDefault'} = '';
401 $envir{'functRelPercentTolDefault'} = .1;
402 $envir{'functZeroLevelDefault'} = 1E-14;
403 $envir{'functZeroLevelTolDefault'} = 1E-12;
404 $envir{'functAbsTolDefault'} = .001;
405 $envir{'functNumOfPoints'} = 3;
406 $envir{'functVarDefault'} = 'x';
407 $envir{'functLLimitDefault'} = .0000001;
408 $envir{'functULimitDefault'} = .9999999;
409 $envir{'functMaxConstantOfIntegration'} = 1E8;
410# kludge check definition of number of attempts again. The +1 is because this is used before the current answer is evaluated.
411 $envir{'numOfAttempts'} = 2; #&getProblemNumOfCorrectAns($probNum,$psvn)
412 # &getProblemNumOfIncorrectAns($probNum,$psvn)+1;
413
414#
415#
416# defining directorys and URLs
417 $envir{'templateDirectory'} = $courseEnvironment ->{courseDirs}->{templates};
418############ $envir{'classDirectory'} = $Global::classDirectory;
419# $envir{'cgiDirectory'} = $Global::cgiDirectory;
420# $envir{'cgiURL'} = getWebworkCgiURL();
421
422# $envir{'scriptDirectory'} = $Global::scriptDirectory;##omit
423 $envir{'webworkDocsURL'} = 'http://webwork.math.rochester.edu';
424 $envir{'externalTTHPath'} = '/usr/local/bin/tth';
425 348
426 349 return CGI::p(CGI::font({-color=>"red"}, "This problem is not available because the problem set that contains it is not yet open."))
427# 350 unless $self->{isOpen};
428 $envir{'inputs_ref'} = $r->param; 351
429 $envir{'problemSeed'} = 3245; 352 # unpack some useful variables
430 $envir{'displaySolutionsQ'} = 1; 353 my $r = $self->{r};
431 $envir{'displayHintsQ'} = 1; 354 my $db = $self->{db};
432 355 my $set = $self->{set};
433# Directory values -- do we really need them here? 356 my $problem = $self->{problem};
434 $envir{courseScriptsDirectory} = $COURSE_SCRIPTS_DIRECTORY; 357 my $permissionLevel = $self->{permissionLevel};
435 $envir{macroDirectory} = $MACRO_DIRECTORY; 358 my $submitAnswers = $self->{submitAnswers};
436 $envir{templateDirectory} = $TEMPLATE_DIRECTORY; 359 my $checkAnswers = $self->{checkAnswers};
437 $envir{tempDirectory} = $TEMP_DIRECTORY; 360 my $previewAnswers = $self->{previewAnswers};
438 $envir{tempURL} = $TEMP_URL; 361 my %want = %{ $self->{want} };
439 $envir{htmlURL} = $HTML_URL; 362 my %can = %{ $self->{can} };
440 $envir{'htmlDirectory'} = $courseEnvironment ->{courseDirectory}->{html}; 363 my %must = %{ $self->{must} };
441 # here is a way to pass environment variables defined in webworkCourse.ph 364 my %will = %{ $self->{will} };
442# my $k; 365 my $pg = $self->{pg};
443# foreach $k (keys %Global::PG_environment ) { 366
444# $envir{$k} = $Global::PG_environment{$k}; 367 ##### translation errors? #####
368
369 if ($pg->{flags}->{error_flag}) {
370 return $self->errorOutput($pg->{errors}, $pg->{body_text});
445# } 371 }
446 \%envir; 372
447} 373 ##### answer processing #####
448 374
449######################################################################################## 375 # if answers were submitted:
450# This recursive pretty_print function will print a hash and its sub hashes. 376 if ($submitAnswers) {
451######################################################################################## 377 # get a "pure" (unmerged) UserProblem to modify
452sub pretty_print_rh { 378 # this will be undefined if the problem has not been assigned to this user
453 my $r_input = shift; 379 my $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id);
454 my $out = ''; 380 # store answers in DB for sticky answers
455 if ( not ref($r_input) ) { 381 my %answersToStore;
456 $out = $r_input; # not a reference 382 my %answerHash = %{ $pg->{answers} };
457 } elsif (is_hash_ref($r_input)) { 383 $answersToStore{$_} = $answerHash{$_}->{original_student_ans}
458 local($^W) = 0; 384 foreach (keys %answerHash);
459 $out .= "<TABLE border = \"2\" cellpadding = \"3\" BGCOLOR = \"#FFFFFF\">"; 385 my $answerString = encodeAnswers(%answersToStore,
460 foreach my $key (sort keys %$r_input ) { 386 @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} });
461 $out .= "<tr><TD> $key</TD><TD>=&gt;</td><td>&nbsp;".pretty_print_rh($r_input->{$key}) . "</td></tr>";
462 } 387
463 $out .="</table>"; 388 $problem->last_answer($answerString);
464 } elsif (is_array_ref($r_input) ) { 389 # if $pureProblem is defined ( there is a user ) then record the last answer.
465 my @array = @$r_input; 390 # FIXME (we're assuming that not being able to get a pure problem is enough to determine
466 $out .= "( " ; 391 # whether or not the problem database needs to be updated. This should be thought through
467 while (@array) { 392 # more carefully to be sure.
468 $out .= pretty_print_rh(shift @array) . " , "; 393 if ( defined($pureProblem) ) {
394 $pureProblem->last_answer($answerString);
395 $db->putUserProblem($pureProblem);
396 #die "pureProblem = ", defined($pureProblem);
469 } 397
470 $out .= " )";
471 } elsif (ref($r_input) eq 'CODE') {
472 $out = "$r_input";
473 } else {
474 $out = $r_input;
475 }
476 $out;
477}
478
479sub is_hash_ref {
480 my $in =shift;
481 my $save_SIG_die_trap = $SIG{__DIE__};
482 $SIG{__DIE__} = sub {CORE::die(@_) };
483 my $out = eval{ %{ $in } };
484 $out = ($@ eq '') ? 1 : 0;
485 $@='';
486 $SIG{__DIE__} = $save_SIG_die_trap;
487 $out;
488}
489sub is_array_ref {
490 my $in =shift;
491 my $save_SIG_die_trap = $SIG{__DIE__};
492 $SIG{__DIE__} = sub {CORE::die(@_) };
493 my $out = eval{ @{ $in } };
494 $out = ($@ eq '') ? 1 : 0;
495 $@='';
496 $SIG{__DIE__} = $save_SIG_die_trap;
497 $out;
498}
499
500######
501# Utility for slurping souce files
502#######
503
504sub readFile {
505 my $input = shift; # The set and problem: 'set0/prob1.pg'
506 my $filePath =$TEMPLATE_DIRECTORY .$input;
507 print STDERR "Reading problem from file $filePath \n";
508 print STDERR "<br>Reading problem from file $filePath <br>\n";
509 my $out;
510 print "The file is readable = ", -r $filePath, "\n";
511 if (-r $filePath) {
512 open IN, "<$filePath" or print STDERR "Hey, this file was supposed to be readable\n";
513 local($/)=undef;
514 $out = <IN>;
515 close(IN);
516 } else {
517 print "Could not read file at |$filePath|";
518 print STDERR "Could not read file at |$filePath|";
519 }
520 return($out);
521}
522
523my $foo =0;
524
525# The warning mechanism. This needs to be turned into an object of its own
526###############
527## Error message routines cribbed from CGI
528###############
529
530BEGIN { #error message routines cribbed from CGI
531
532 my $CarpLevel = 0; # How many extra package levels to skip on carp.
533 my $MaxEvalLen = 0; # How much eval '...text...' to show. 0 = all.
534
535 sub longmess {
536 my $error = shift;
537 my $mess = "";
538 my $i = 1 + $CarpLevel;
539 my ($pack,$file,$line,$sub,$eval,$require);
540
541 while (($pack,$file,$line,$sub,undef,undef,$eval,$require) = caller($i++)) {
542 if ($error =~ m/\n$/) {
543 $mess .= $error;
544 }
545 else {
546 if (defined $eval) {
547 if ($require) {
548 $sub = "require $eval";
549 }
550 else {
551 $eval =~ s/[\\\']/\\$&/g;
552 if ($MaxEvalLen && length($eval) > $MaxEvalLen) {
553 substr($eval,$MaxEvalLen) = '...';
554 }
555 $sub = "eval '$eval'";
556 }
557 }
558 elsif ($sub eq '(eval)') {
559 $sub = 'eval {...}';
560 }
561
562 $mess .= "\t$sub " if $error eq "called";
563 $mess .= "$error at $file line $line\n";
564 }
565
566 $error = "called";
567 } 398
568 399 # store state in DB if it makes sense
569 $mess || $error; 400 if ($will{recordAnswers}) {
570 } 401 $problem->status($pg->{state}->{recorded_score});
571} 402 $problem->attempted(1);
572############### 403 $problem->num_correct($pg->{state}->{num_of_correct_ans});
573### Our error messages for giving maximum feedback to the user for errors within problems. 404 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
574############### 405 $pureProblem->status($pg->{state}->{recorded_score});
575BEGIN { 406 $pureProblem->attempted(1);
576 sub PG_floating_point_exception_handler { # 1st argument is signal name 407 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
577 my($sig) = @_; 408 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
578 print "Content-type: text/html\n\n<H4>There was a floating point arithmetic error (exception SIG$sig )</H4>--perhaps 409 $db->putUserProblem($pureProblem);
579 you divided by zero or took the square root of a negative number? 410 # write to the transaction log, just to make sure
580 <BR>\n Use the back button to return to the previous page and recheck your entries.<BR>\n"; 411 writeLog($self->{ce}, "transaction",
581 exit(0); 412 $problem->problem_id."\t".
582 } 413 $problem->set_id."\t".
583 414 $problem->user_id."\t".
584 $SIG{'FPE'} = \&PG_floating_point_exception_handler; 415 $problem->source_file."\t".
585#!/usr/bin/perl -w 416 $problem->value."\t".
586 sub PG_warnings_handler { 417 $problem->max_attempts."\t".
587 my @input = @_; 418 $problem->problem_seed."\t".
588 my $msg_string = longmess(@_); 419 $pureProblem->status."\t".
589 my @msg_array = split("\n",$msg_string); 420 $pureProblem->attempted."\t".
590 my $out_string = ''; 421 $pureProblem->last_answer."\t".
591 422 $pureProblem->num_correct."\t".
592 # Extra stack information is provided in this next block 423 $pureProblem->num_incorrect
593 # If the warning message does NOT end in \n then a line 424 );
594 # number is appended (see Perl manual about warn function)
595 # The presence of the line number is detected below and extra
596 # stack information is added.
597 # To suppress the line number and the extra stack information
598 # add \n to the end of a warn message (in .pl files. In .pg
599 # files add ~~n instead
600
601 if ($input[$#input]=~/line \d*\.\s*$/) {
602 $out_string .= "##More details: <BR>\n----";
603 foreach my $line (@msg_array) {
604 chomp($line);
605 next unless $line =~/\w+\:\:/;
606 $out_string .= "----" .$line . "<BR>\n";
607 } 425 }
608 } 426 }
609 427 }
610 $Global::WARNINGS .="* " . join("<BR>",@input) . "<BR>\n" . $out_string . 428 # logging student answers
611 "<BR>\n--------------------------------------<BR>\n<BR>\n"; 429 my $pastAnswerLog = undef;
612 $Global::background_plain_url = $Global::background_warn_url; 430 if (defined( $self->{ce}->{webworkFiles}->{logs}->{'pastAnswerList'} )) {
613 $Global::bg_color = '#FF99CC'; #for warnings -- this change may come too late 431
432 $pastAnswerLog = $self->{ce}->{webworkFiles}->{logs}->{'pastAnswerList'};
433
434 if ($submitAnswers and defined($pastAnswerLog) ) {
435 my $answerString = "";
436 my %answerHash = %{ $pg->{answers} };
437 $answerString = $answerString . $answerHash{$_}->{original_student_ans}."\t"
438 foreach (sort keys %answerHash);
439 $answerString = '' unless defined($answerString); # insure string is defined.
440 writeLog($self->{ce}, "pastAnswerList",
441 '|'.$problem->user_id.
442 '|'.$problem->set_id.
443 '|'.$problem->problem_id.'|'."\t".
444 time()."\t".
445 $answerString,
446
447 );
448
614 } 449 }
615
616 $SIG{__WARN__}=\&PG_warnings_handler;
617 450
618 $SIG{__DIE__} = sub { 451 }
619 my $message = longmess(@_); 452 # end logging student answers
620 $message =~ s/\n/<BR>\n/; 453
621 my ($package, $filename, $line) = caller(); 454 ##### output #####
622 # use standard die for errors eminating from XML::Parser::Expat 455 print CGI::start_div({class=>"problemHeader"});
623 # it uses a trapped eval which sometimes fails -- apparently on purpose 456 # attempt summary
624 # and the error is handled by Expat itself. We don't want 457 if ($submitAnswers or $will{showCorrectAnswers}) {
625 # to interfer with that. 458 # print this if user submitted answers OR requested correct answers
626 459 print $self->attemptResults($pg, $submitAnswers,
627 if ($package eq 'XML::Parser::Expat') { 460 $will{showCorrectAnswers},
628 die @_; 461 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
629 } 462 } elsif ($checkAnswers) {
630 #print "$package $filename $line \n"; 463 # print this if user previewed answers
464 print $self->attemptResults($pg, 1, 0, 1, 1, 1);
465 # show attempt answers
466 # don't show correct answers
467 # show attempt results (correctness)
468 # don't show attempt previews
469 } elsif ($previewAnswers) {
470 # print this if user previewed answers
471 print $self->attemptResults($pg, 1, 0, 0, 0, 1);
472 # show attempt answers
473 # don't show correct answers
474 # don't show attempt results (correctness)
475 # show attempt previews
476 }
477
478 print CGI::end_div();
479
480 print CGI::start_div({class=>"problem"});
481 #print CGI::hr();
482 # main form
483 print
484 CGI::startform("POST", $r->uri),
485 $self->hidden_authen_fields,
486 CGI::p($pg->{body_text}),
487 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})),
488 CGI::p(
489 ($can{recordAnswers}
490 ? CGI::submit(-name=>"submitAnswers",
491 -label=>"Submit Answers")
492 : ""),
493 ($can{checkAnswers}
494 ? CGI::submit(-name=>"checkAnswers",
495 -label=>"Check Answers")
496 : ""),
497 CGI::submit(-name=>"previewAnswers",
498 -label=>"Preview Answers"),
499 );
500 print CGI::end_div();
501
502 print CGI::start_div({class=>"scoreSummary"});
503 # score summary
504 my $attempts = $problem->num_correct + $problem->num_incorrect;
505 my $attemptsNoun = $attempts != 1 ? "times" : "time";
506 my $lastScore = sprintf("%.0f%%", $problem->status * 100); # Round to whole number
507 my ($attemptsLeft, $attemptsLeftNoun);
508 if ($problem->max_attempts == -1) {
509 # unlimited attempts
510 $attemptsLeft = "unlimited";
511 $attemptsLeftNoun = "attempts";
512 } else {
513 $attemptsLeft = $problem->max_attempts - $attempts;
514 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
515 }
516
517 my $setClosed = 0;
518 my $setClosedMessage;
519 if (time < $set->open_date or time > $set->due_date) {
520 $setClosed = 1;
521 $setClosedMessage = "This problem set is closed.";
522 if ($permissionLevel > 0) {
523 $setClosedMessage .= " Since you are a privileged user, additional attempts will be recorded.";
524 } else {
525 $setClosedMessage .= " Additional attempts will not be recorded.";
526 }
527 }
528 print CGI::p(
529 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
530 $problem->attempted
531 ? "Your recorded score is $lastScore." . CGI::br()
532 : "",
533 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
534 );
535 print CGI::end_div();
536# print CGI::hr(), CGI::start_div({class=>"viewOptions"});
537# print $self->viewOptions(),CGI::end_div(),
538# save state for viewOptions
539 print CGI::hidden(-name => "showOldAnswers",
540 -value => $will{showOldAnswers},
541 ),
542 CGI::hidden(-name => "showCorrectAnswers",
543 -value => $will{showCorrectAnswers},
544 ),
545 CGI::hidden(-name => "showHints",
546 -value => $will{showHints},
547 ),
548 CGI::hidden(-name => "showSolutions",
549 -value => $will{showSolutions},
550 ),
551 CGI::hidden(-name => "displayMode",
552 -value => $self->{displayMode}
553 );
554 print CGI::endform();
555
556 print CGI::start_div({class=>"problemFooter"});
557 # feedback form
558 my $ce = $self->{ce};
559 my $root = $ce->{webworkURLs}->{root};
560 my $courseName = $ce->{courseName};
561 my $feedbackURL = "$root/$courseName/feedback/";
562
563 # arguments for answer inspection button
564 my $prof_url = $ce->{webworkURLs}->{oldProf};
565 my $cgi_url = $prof_url;
566 $cgi_url=~ s|/[^/]*$||; # clip profLogin.pl
567 my $authen_args = $self->url_authen_args();
568 my $showPastAnswersURL = "$cgi_url/showPastAnswers.pl";
569
570
571 print CGI::end_div();
572 print CGI::start_div();
573 # print answer inspection button
574 if ($self->{permissionLevel} >0) {
575
576
577 print "\n",
578 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
579 $self->hidden_authen_fields,"\n",
580 CGI::hidden(-name => 'course', -value=>$courseName), "\n",
581 CGI::hidden(-name => 'probNum', -value=>$problem->problem_id), "\n",
582 CGI::hidden(-name => 'setNum', -value=>$problem->set_id), "\n",
583 CGI::hidden(-name => 'User', -value=>$problem->user_id), "\n",
584 CGI::p( {-align=>"left"},
585 CGI::submit(-name => 'action', -value=>'Show Past Answers')
586 ), "\n",
587 CGI::endform();
588
589
590
591 } #print feedback form
592
593
594 print
595 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
596 $self->hidden_authen_fields,"\n",
597 CGI::hidden("module", __PACKAGE__),"\n",
598 CGI::hidden("set", $set->set_id),"\n",
599 CGI::hidden("problem", $problem->problem_id),"\n",
600 CGI::hidden("displayMode", $self->{displayMode}),"\n",
601 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n",
602 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
603 CGI::hidden("showHints", $will{showHints}),"\n",
604 CGI::hidden("showSolutions", $will{showSolutions}),"\n",
605 CGI::p({-align=>"left"},
606 CGI::submit(-name=>"feedbackForm", -label=>"Contact instructor")
607 ),
608 CGI::endform(),"\n";
609
610 # FIXME print editor link
611 # print editor link if the user is an instructor AND the file is not in temporary editing mode
612 if ($self->{permissionLevel}>=10 and ( (not defined($self->{edit_mode})) or $self->{edit_mode} eq 'savedFile') ) {
613 print CGI::a({-href=>$ce->{webworkURLs}->{root}."/$courseName/instructor/pgProblemEditor/".$set->set_id.
614 '/'.$problem->problem_id.'?'.$self->url_authen_args},'Edit this problem');
615 }
616
617 print CGI::end_div();
618
619 # end answer inspection button
620 # warning output
621 if ($pg->{warnings} ne "") {
622 print CGI::hr(), $self->warningOutput($pg->{warnings});
623 }
624
625 # debugging stuff
626 if (0) {
631 print 627 print
632 "Content-type: text/html\r\n\r\n <h4>Software error</h4> <p>\n\n$message\n<p>\n 628 CGI::hr(),
633 Please inform the webwork meister.<p>\n 629 CGI::h2("debugging information"),
634 In addition to the error message above the following warnings were detected: 630 CGI::h3("form fields"),
635 <HR> 631 ref2string($self->{formFields}),
636 $Global::WARNINGS; 632 CGI::h3("user object"),
637 <HR> 633 ref2string($self->{user}),
638 It's sometimes hard to tell exactly what has gone wrong since the 634 CGI::h3("set object"),
639 full error message may have been sent to 635 ref2string($set),
640 standard error instead of to standard out. 636 CGI::h3("problem object"),
641 <p> To debug you can 637 ref2string($problem),
642 <ul> 638 CGI::h3("PG object"),
643 <li> guess what went wrong and try to fix it. 639 ref2string($pg, {'WeBWorK::PG::Translator' => 1});
644 <li> call the offending script directly from the command line
645 of unix
646 <li> enable the debugging features by redefining
647 \$cgiURL in Global.pm and checking the redirection scripts in
648 system/cgi. This will force the standard error to be placed
649 in the standard out pipe as well.
650 <li> Run tail -f error_log <br>
651 from the unix command line to see error messages from the webserver.
652 The standard error output is being placed in the error_log file for the apache
653 web server. To run this command you have to be in the directory containing the
654 error_log or enter the full path name of the error_log. <p>
655 In a standard apache installation, this file is at /usr/local/apache/logs/error_log<p>
656 In a RedHat Linux installation, this file is at /var/log/httpd/error_log<p>
657 At Rochester this file is at /ww/logs/error_log.
658 </ul>
659 Good luck.<p>\n" ;
660 }; 640 }
641
642 return "";
643}
661 644
645##### output utilities #####
662 646
647sub attemptResults($$$$$$) {
648 my $self = shift;
649 my $pg = shift;
650 my $showAttemptAnswers = shift;
651 my $showCorrectAnswers = shift;
652 my $showAttemptResults = $showAttemptAnswers && shift;
653 my $showSummary = shift;
654 my $showAttemptPreview = shift || 0;
655 my $problemResult = $pg->{result}; # the overall result of the problem
656 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
657
658 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
659
660 my $header = CGI::th("Part");
661 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
662 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
663 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
664 $header .= $showAttemptResults ? CGI::th("Result") : "";
665 $header .= $showMessages ? CGI::th("messages") : "";
666 my @tableRows = ( $header );
667 my $numCorrect;
668 foreach my $name (@answerNames) {
669 my $answerResult = $pg->{answers}->{$name};
670 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
671 my $preview = ($showAttemptPreview
672 ? $self->previewAnswer($answerResult)
673 : "");
674 my $correctAnswer = $answerResult->{correct_ans};
675 my $answerScore = $answerResult->{score};
676 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
677
678 $numCorrect += $answerScore > 0;
679 my $resultString = $answerScore ? "correct" : "incorrect";
680
681 # get rid of the goofy prefix on the answer names (supposedly, the format
682 # of the answer names is changeable. this only fixes it for "AnSwEr"
683 $name =~ s/^AnSwEr//;
684
685 my $row = CGI::td($name);
686 $row .= $showAttemptAnswers ? CGI::td(nbsp($studentAnswer)) : "";
687 $row .= $showAttemptPreview ? CGI::td(nbsp($preview)) : "";
688 $row .= $showCorrectAnswers ? CGI::td(nbsp($correctAnswer)) : "";
689 $row .= $showAttemptResults ? CGI::td(nbsp($resultString)) : "";
690 $row .= $answerMessage ? CGI::td(nbsp($answerMessage)) : "";
691 push @tableRows, $row;
692 }
693
694 my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
695 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
696 my $summary = "On this attempt, you answered $numCorrect out of "
697 . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
698 return CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) . ($showSummary ? CGI::p($summary) : "");
699}
700sub nbsp {
701 my $str = shift;
702 ($str) ? $str : '&nbsp;'; # returns non-breaking space for empty strings
703}
704sub viewOptions($) {
705 my $self = shift;
706 my $displayMode = $self->{displayMode};
707 my %must = %{ $self->{must} };
708 my %can = %{ $self->{can} };
709 my %will = %{ $self->{will} };
710
711 my $optionLine;
712 $can{showOldAnswers} and $optionLine .= join "",
713 "Show: &nbsp;".CGI::br(),
714 CGI::checkbox(
715 -name => "showOldAnswers",
716 -checked => $will{showOldAnswers},
717 -label => "Saved answers",
718 ), "&nbsp;&nbsp;".CGI::br();
719 $can{showCorrectAnswers} and $optionLine .= join "",
720 CGI::checkbox(
721 -name => "showCorrectAnswers",
722 -checked => $will{showCorrectAnswers},
723 -label => "Correct answers",
724 ), "&nbsp;&nbsp;".CGI::br();
725 $can{showHints} and $optionLine .= join "",
726 CGI::checkbox(
727 -name => "showHints",
728 -checked => $will{showHints},
729 -label => "Hints",
730 ), "&nbsp;&nbsp;".CGI::br();
731 $can{showSolutions} and $optionLine .= join "",
732 CGI::checkbox(
733 -name => "showSolutions",
734 -checked => $will{showSolutions},
735 -label => "Solutions",
736 ), "&nbsp;&nbsp;".CGI::br();
737 $optionLine and $optionLine .= join "", CGI::br();
738
739 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
740 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br(),
741 CGI::radio_group(
742 -name => "displayMode",
743 -values => ['plainText', 'formattedText', 'images'],
744 -default => $displayMode,
745 -linebreak=>'true',
746 -labels => {
747 plainText => "plain",
748 formattedText => "formatted",
749 images => "images",
750 }
751 ), CGI::br(),CGI::hr(),
752 $optionLine,
753 CGI::submit(-name=>"redisplay", -label=>"Save Options"),
754 );
755}
663 756
757sub previewAnswer($$) {
758 my ($self, $answerResult) = @_;
759 my $ce = $self->{ce};
760 my $effectiveUser = $self->{effectiveUser};
761 my $set = $self->{set};
762 my $problem = $self->{problem};
763 my $displayMode = $self->{displayMode};
764
765 # note: right now, we have to do things completely differently when we are
766 # rendering math from INSIDE the translator and from OUTSIDE the translator.
767 # so we'll just deal with each case explicitly here. there's some code
768 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
769
770 my $tex = $answerResult->{preview_latex_string};
771
772 return "" if $tex eq "";
773
774 if ($displayMode eq "plainText") {
775 return $tex;
776 } elsif ($displayMode eq "formattedText") {
777 my $tthCommand = $ce->{externalPrograms}->{tth}
778 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
779 . "\\(".$tex."\\)\n"
780 . "END_OF_INPUT\n";
781
782 # call tth
783 my $result = `$tthCommand`;
784 if ($?) {
785 return "<b>[tth failed: $? $@]</b>";
786 }
787 return $result;
788 } elsif ($displayMode eq "images") {
789 # how are we going to name this?
790 my $targetPathCommon = "/m2i/"
791 . $effectiveUser->user_id . "."
792 . $set->set_id . "."
793 . $problem->problem_id . "."
794 . $answerResult->{ans_name} . ".png";
795
796 # figure out where to put things
797 my $wd = tempdir("webwork-dvipng-XXXXXXXX", DIR => $ce->{courseDirs}->{html_temp});
798 my $latex = $ce->{externalPrograms}->{latex};
799 my $dvipng = $ce->{externalPrograms}->{dvipng};
800 my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon;
801 # should use surePathToTmpFile, but we have to
802 # isolate it from the problem enivronment first
803 my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon;
804
805 # call dvipng to generate a preview
806 dvipng($wd, $latex, $dvipng, $tex, $targetPath);
807 rmtree($wd, 0, 0);
808 if (-e $targetPath) {
809 return "<img src=\"$targetURL\" alt=\"$tex\" />";
810 } else {
811 return "<b>[math2img failed]</b>";
812 }
813 }
814}
815
816sub options {
817 my $self=shift;
818 my $out;
819 $out .=join("",
820 CGI::start_form("POST", $self->{r}->uri),
821 $self->hidden_authen_fields,
822 CGI::hr(),
823 CGI::start_div({class=>"viewOptions"}),
824 $self->viewOptions(),CGI::end_div(),
825 CGI::end_form()
826 );
827return $out;
828
829}
830##### logging subroutine ####
831
832
833
834##### permission queries #####
835
836# this stuff should be abstracted out into the permissions system
837# however, the permission system only knows about things in the
838# course environment and the username. hmmm...
839
840# also, i should fix these so that they have a consistent calling
841# format -- perhaps:
842# canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
843
844sub canShowCorrectAnswers($$) {
845 my ($permissionLevel, $answerDate) = @_;
846 return $permissionLevel > 0 || time > $answerDate;
847}
848
849sub canShowSolutions($$) {
850 my ($permissionLevel, $answerDate) = @_;
851 return canShowCorrectAnswers($permissionLevel, $answerDate);
852}
853
854sub canRecordAnswers($$$$$) {
855 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
856 my $permHigh = $permissionLevel > 0;
857 my $timeOK = time >= $openDate && time <= $dueDate;
858 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
859 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
860 return $recordAnswers;
861}
862
863sub canCheckAnswers($$) {
864 my ($permissionLevel, $answerDate) = @_;
865 my $permHigh = $permissionLevel > 0;
866 my $timeOK = time >= $answerDate;
867 my $recordAnswers = $permHigh || $timeOK;
868 return $recordAnswers;
869}
870
871sub mustRecordAnswers($) {
872 my ($permissionLevel) = @_;
873 return $permissionLevel == 0;
664} 874}
665 875
6661; 8761;

Legend:
Removed from v.399  
changed lines
  Added in v.1128

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9