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

Diff of /branches/rel-2-3-dev/webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm

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

Revision 399 Revision 2436
1################################################################################
2# WeBWorK Online Homework Delivery System
3# Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
4# $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.149 2004/06/28 14:31:40 jj 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.
15################################################################################
16
1package WeBWorK::ContentGenerator::Problem; 17package WeBWorK::ContentGenerator::Problem;
2our @ISA = qw(WeBWorK::ContentGenerator); 18use base qw(WeBWorK::ContentGenerator);
19
20=head1 NAME
21
22WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
23
24=cut
3 25
4use strict; 26use strict;
5use warnings; 27use warnings;
6use lib '/home/malsyned/xmlrpc/daemon'; 28use CGI qw();
7use lib '/Users/gage/webwork-modperl/lib'; 29use File::Path qw(rmtree);
8use PGtranslator5; 30use WeBWorK::Form;
31use WeBWorK::PG;
9use WeBWorK::ContentGenerator; 32use WeBWorK::PG::ImageGenerator;
10use Apache::Constants qw(:common); 33use WeBWorK::PG::IO;
34use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory);
35use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
36use WeBWorK::Timing;
11 37
38use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
39
12############################################################################### 40############################################################
13# Configuration 41#
14############################################################################### 42# user
15my $USER_DIRECTORY = '/Users/gage'; 43# effectiveUser
16my $COURSE_SCRIPTS_DIRECTORY = "$USER_DIRECTORY/webwork/system/courseScripts/"; 44# key
17my $MACRO_DIRECTORY = "$USER_DIRECTORY/webwork-modperl/courses/demoCourse/templates/macros/"; 45#
18my $TEMPLATE_DIRECTORY = "$USER_DIRECTORY/rochester_problib/"; 46# editMode
19my $TEMP_URL = "http://127.0.0.1/~gage/rochester_problibtmp/"; 47# sourceFilePath - path to file to be editted
20##my $HTML_DIRECTORY = "/Users/gage/Sites/rochester_problib/" #already obtained from courseEnvironment 48# problemSeed - problem seed for editted problem
21my $HTML_URL = "http://127.0.0.1/~gage/rochester_problib/";
22my $TEMP_DIRECTORY = ""; # has to be here... for now
23
24###############################################################################
25# End configuration
26###############################################################################
27
28sub title {
29 my ($self, $problem_set, $problem) = @_;
30 my $r = $self->{r};
31 my $user = $r->param('user');
32 return "Problem $problem of problem set $problem_set for $user";
33}
34
35###############################################################################
36# 49#
37# INITIALIZATION 50# displayMode - type of display (ie formatted, images, asciimath, etc)
38# 51#
39# The following code initializes an instantiation of PGtranslator5 in the 52# showOldAnswers
40# parent process. This initialized object is then share with each of the 53# showCorrectAnswers
41# children forked from this parent process by the daemon. 54# showHints
55# showSolutions
56#
57# AnSwEr# - answer blanks in problem
58#
59# redisplay - name of the "Redisplay Problem" button
60# submitAnswers - name of "Submit Answers" button
61# checkAnswers - name of the "Check Answers" button
62# previewAnswers - name of the "Preview Answers" button
42# 63#
43# As far as I can tell, the child processes don't share any variable values even 64# success - success message (from PGProblemEditor)
44# though their namespaces are the same. 65# failure - failure message (from PGProblemEditor)
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
91#These here documents have their drawbacks. KEEP END_OF_TEXT left justified!!!!!!
92
93###############################################################################
94# Now to define the body subroutine which does the hard work.
95###############################################################################
96
97
98#my $SOURCE1 = $INITIAL_MACRO_PACKAGES;
99
100sub 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;
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# 66#
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
426
427#
428 $envir{'inputs_ref'} = $r->param;
429 $envir{'problemSeed'} = 3245;
430 $envir{'displaySolutionsQ'} = 1;
431 $envir{'displayHintsQ'} = 1;
432
433# Directory values -- do we really need them here?
434 $envir{courseScriptsDirectory} = $COURSE_SCRIPTS_DIRECTORY;
435 $envir{macroDirectory} = $MACRO_DIRECTORY;
436 $envir{templateDirectory} = $TEMPLATE_DIRECTORY;
437 $envir{tempDirectory} = $TEMP_DIRECTORY;
438 $envir{tempURL} = $TEMP_URL;
439 $envir{htmlURL} = $HTML_URL;
440 $envir{'htmlDirectory'} = $courseEnvironment ->{courseDirectory}->{html};
441 # here is a way to pass environment variables defined in webworkCourse.ph
442# my $k;
443# foreach $k (keys %Global::PG_environment ) {
444# $envir{$k} = $Global::PG_environment{$k};
445# }
446 \%envir;
447}
448
449######################################################################################## 67############################################################
450# This recursive pretty_print function will print a hash and its sub hashes. 68
451######################################################################################## 69
452sub pretty_print_rh { 70sub pre_header_initialize {
453 my $r_input = shift; 71 my ($self) = @_;
454 my $out = ''; 72 my $r = $self->r;
455 if ( not ref($r_input) ) { 73 my $ce = $r->ce;
456 $out = $r_input; # not a reference 74 my $db = $r->db;
457 } elsif (is_hash_ref($r_input)) { 75 my $authz = $r->authz;
458 local($^W) = 0; 76 my $urlpath = $r->urlpath;
459 $out .= "<TABLE border = \"2\" cellpadding = \"3\" BGCOLOR = \"#FFFFFF\">"; 77
460 foreach my $key (sort keys %$r_input ) { 78 my $setName = $urlpath->arg("setID");
461 $out .= "<tr><TD> $key</TD><TD>=&gt;</td><td>&nbsp;".pretty_print_rh($r_input->{$key}) . "</td></tr>"; 79 my $problemNumber = $r->urlpath->arg("problemID");
80 my $userName = $r->param('user');
81 my $effectiveUserName = $r->param('effectiveUser');
82 my $key = $r->param('key');
83
84 my $user = $db->getUser($userName); # checked
85 die "record for user $userName (real user) does not exist."
86 unless defined $user;
87
88 my $effectiveUser = $db->getUser($effectiveUserName); # checked
89 die "record for user $effectiveUserName (effective user) does not exist."
90 unless defined $effectiveUser;
91
92 my $PermissionLevel = $db->getPermissionLevel($userName); # checked
93 die "permission level record for user $userName does not exist (but the user does? odd...)"
94 unless defined $PermissionLevel;
95 my $permissionLevel = $PermissionLevel->permission;
96
97 # obtain the merged set for $effectiveUser
98 my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
99
100 # obtain the merged problem for $effectiveUser
101 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
102
103 my $editMode = $r->param("editMode");
104
105 if ($authz->hasPermissions($userName, "modify_problem_sets")) {
106 # professors are allowed to fabricate sets and problems not
107 # assigned to them (or anyone). this allows them to use the
108 # editor to
462 } 109
463 $out .="</table>"; 110 # if that is not yet defined obtain the global set, convert
464 } elsif (is_array_ref($r_input) ) { 111 # it to a user set, and add fake user data
465 my @array = @$r_input; 112 unless (defined $set) {
466 $out .= "( " ; 113 my $userSetClass = $db->{set_user}->{record};
467 while (@array) { 114 my $globalSet = $db->getGlobalSet($setName); # checked
468 $out .= pretty_print_rh(shift @array) . " , "; 115 # if the global set doesn't exist either, bail!
469 } 116 if(not defined $globalSet) {
470 $out .= " )"; 117 $set = fake_set($db);
471 } elsif (ref($r_input) eq 'CODE') {
472 $out = "$r_input";
473 } else { 118 } else {
474 $out = $r_input; 119 $set = global2user($userSetClass, $globalSet);
475 } 120 $set->psvn(0);
476 $out;
477}
478 121
479sub is_hash_ref { 122 # FIXME: This is a temporary fix to fill in the database
480 my $in =shift; 123 # We want the published field to contain either 1 or 0 so if it has not been set to 0, default to 1
481 my $save_SIG_die_trap = $SIG{__DIE__}; 124 # this will fill in all the empty fields but not change anything that has been specifically set to 1 or 0
482 $SIG{__DIE__} = sub {CORE::die(@_) }; 125 $globalSet->published("1") unless $globalSet->published eq "0";
483 my $out = eval{ %{ $in } }; 126 $db->putGlobalSet($globalSet);
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 }
568
569 $mess || $error;
570 }
571}
572###############
573### Our error messages for giving maximum feedback to the user for errors within problems.
574###############
575BEGIN {
576 sub PG_floating_point_exception_handler { # 1st argument is signal name
577 my($sig) = @_;
578 print "Content-type: text/html\n\n<H4>There was a floating point arithmetic error (exception SIG$sig )</H4>--perhaps
579 you divided by zero or took the square root of a negative number?
580 <BR>\n Use the back button to return to the previous page and recheck your entries.<BR>\n";
581 exit(0);
582 }
583
584 $SIG{'FPE'} = \&PG_floating_point_exception_handler;
585#!/usr/bin/perl -w
586 sub PG_warnings_handler {
587 my @input = @_;
588 my $msg_string = longmess(@_);
589 my @msg_array = split("\n",$msg_string);
590 my $out_string = '';
591
592 # Extra stack information is provided in this next block
593 # If the warning message does NOT end in \n then a line
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 } 127 }
608 } 128 }
609 129
610 $Global::WARNINGS .="* " . join("<BR>",@input) . "<BR>\n" . $out_string . 130 # if that is not yet defined obtain the global problem,
611 "<BR>\n--------------------------------------<BR>\n<BR>\n"; 131 # convert it to a user problem, and add fake user data
612 $Global::background_plain_url = $Global::background_warn_url; 132 unless (defined $problem) {
613 $Global::bg_color = '#FF99CC'; #for warnings -- this change may come too late 133 my $userProblemClass = $db->{problem_user}->{record};
134 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
135 # if the global problem doesn't exist either, bail!
136 if(not defined $globalProblem) {
137 my $sourceFilePath = $r->param("sourceFilePath");
138 # These are problems from setmaker. If declared invalid, they won't come up
139 $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
140# die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
141 $problem = fake_problem($db);
142 $problem->problem_id(1);
143 $problem->source_file($sourceFilePath);
144 $problem->user_id($effectiveUserName);
145 } else {
146 $problem = global2user($userProblemClass, $globalProblem);
147 $problem->user_id($effectiveUserName);
148 $problem->problem_seed(0);
149 $problem->status(0);
150 $problem->attempted(0);
151 $problem->last_answer("");
152 $problem->num_correct(0);
153 $problem->num_incorrect(0);
154 }
614 } 155 }
156
157 # now we're sure we have valid UserSet and UserProblem objects
158 # yay!
159
160 # now deal with possible editor overrides:
161
162 # if the caller is asking to override the source file, and
163 # editMode calls for a temporary file, do so
164 my $sourceFilePath = $r->param("sourceFilePath");
165 if (defined $sourceFilePath and
166 (not defined $editMode or $editMode eq "temporaryFile")) {
167 $problem->source_file($sourceFilePath);
168 }
169
170 # if the problem does not have a source file or no source file has been passed in
171 # then this is really an invalid problem (probably from a bad URL)
172 $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file);
173
174 # if the caller is asking to override the problem seed, do so
175 my $problemSeed = $r->param("problemSeed");
176 if (defined $problemSeed) {
177 $problem->problem_seed($problemSeed);
178 }
615 179
616 $SIG{__WARN__}=\&PG_warnings_handler; 180 my $publishedClass = ($set->published) ? "Published" : "Unpublished";
181 my $publishedText = ($set->published) ? "visible to students." : "hidden from students.";
182 $self->addmessage(CGI::p("This set is " . CGI::font({class=>$publishedClass}, $publishedText)));
183 } else {
617 184
618 $SIG{__DIE__} = sub { 185 # students can't view problems not assigned to them
619 my $message = longmess(@_); 186
620 $message =~ s/\n/<BR>\n/; 187 # A set is valid if it exists and if it is either published or the user is privileged.
621 my ($package, $filename, $line) = caller(); 188 $self->{invalidSet} = ((grep /^$setName/, $db->listUserSets($effectiveUserName)) == 0)
622 # use standard die for errors eminating from XML::Parser::Expat 189 || not defined $set
623 # it uses a trapped eval which sometimes fails -- apparently on purpose 190 || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"));
624 # and the error is handled by Expat itself. We don't want 191 $self->{invalidProblem} = ((grep /^$problemNumber/, $db->listUserProblems($effectiveUserName, $setName)) == 0)
625 # to interfer with that. 192 || not defined $problem
626 193 || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"));
627 if ($package eq 'XML::Parser::Expat') { 194
628 die @_; 195 $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem};
629 } 196 }
630 #print "$package $filename $line \n"; 197
198 $self->{userName} = $userName;
199 $self->{effectiveUserName} = $effectiveUserName;
200 $self->{user} = $user;
201 $self->{effectiveUser} = $effectiveUser;
202 $self->{permissionLevel} = $permissionLevel;
203 $self->{set} = $set;
204 $self->{problem} = $problem;
205 $self->{editMode} = $editMode;
206
207 ##### form processing #####
208
209 # set options from form fields (see comment at top of file for names)
210 my $displayMode = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
211 my $redisplay = $r->param("redisplay");
212 my $submitAnswers = $r->param("submitAnswers");
213 my $checkAnswers = $r->param("checkAnswers");
214 my $previewAnswers = $r->param("previewAnswers");
215
216 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
217
218 $self->{displayMode} = $displayMode;
219 $self->{redisplay} = $redisplay;
220 $self->{submitAnswers} = $submitAnswers;
221 $self->{checkAnswers} = $checkAnswers;
222 $self->{previewAnswers} = $previewAnswers;
223 $self->{formFields} = $formFields;
224
225 # get result and send to message
226 my $success = $r->param("sucess");
227 my $failure = $r->param("failure");
228 $self->addbadmessage(CGI::p($failure)) if $failure;
229 $self->addgoodmessage(CGI::p($success)) if $success;
230
231 # now that we've set all the necessary variables quit out if the set or problem is invalid
232 return if $self->{invalidSet} || $self->{invalidProblem};
233
234 ##### permissions #####
235
236 # are we allowed to view this problem?
237 $self->{isOpen} = time >= $set->open_date || $authz->hasPermissions($user, "view_unopened_sets");
238 return unless $self->{isOpen};
239
240 # what does the user want to do?
241 my %want = (
242 showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers},
243 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
244 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints},
245 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions},
246 recordAnswers => $submitAnswers,
247 checkAnswers => $checkAnswers,
248 );
249
250 # are certain options enforced?
251 my %must = (
252 showOldAnswers => 0,
253 showCorrectAnswers => 0,
254 showHints => 0,
255 showSolutions => 0,
256 recordAnswers => mustRecordAnswers($permissionLevel),
257 checkAnswers => 0,
258 );
259
260 # does the user have permission to use certain options?
261 my %can = (
262 showOldAnswers => 1,
263 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
264 showHints => 1,
265 showSolutions => canShowSolutions($permissionLevel, $set->answer_date),
266 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
267 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
268 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
269 checkAnswers => canCheckAnswers($permissionLevel, $set->due_date),
270 );
271
272 # more complicated logic for showing check answer button:
273 # checkAnswers button shows up after due date -- once a student can't record anymore
274 # checkAnswers button always shows up when an instructor or TA is acting
275 # as someone else (the $user and $effectiveUserName aren't the same).
276 $can{checkAnswers} = (
277 # $can{recordAnswers} will be false if the due date has passed OR the
278 # student has used up all of her attempts
279 ($can{checkAnswers} and not $can{recordAnswers})
280 or
281 (
282 # FIXME: this is not the right way to check for this.
283 # also, canCheckAnswers() will show this button if the permission
284 # level is positive, which is always true when an instructor is
285 # acting as a student
286 defined($userName)
287 and
288 defined($effectiveUserName)
289 and
290 ($userName ne $effectiveUserName)
291 )
292 );
293
294 # more complicated logic for showing "submit answer" button:
295 # We hide the submit answer button if someone is acting as a student
296 # This prevents errors where you accidently submit the answer for a student
297 # Not sure whether this a feature or a bug
298 $can{recordAnswers} = (
299 $can{recordAnswers}
300 and not
301 (
302 # FIXME: this is not the right way to check for this.
303 defined($userName)
304 and
305 defined($effectiveUserName)
306 and
307 ($userName ne $effectiveUserName)
308 )
309 );
310
311 # final values for options
312 my %will;
313 foreach (keys %must) {
314 $will{$_} = $can{$_} && ($want{$_} || $must{$_});
315 }
316
317 ##### sticky answers #####
318
319 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
320 # do this only if new answers are NOT being submitted
321 my %oldAnswers = decodeAnswers($problem->last_answer);
322 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
323 }
324
325 ##### translation #####
326
327 $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer);
328 my $pg = WeBWorK::PG->new(
329 $ce,
330 $effectiveUser,
331 $key,
332 $set,
333 $problem,
334 $set->psvn, # FIXME: this field should be removed
335 $formFields,
336 { # translation options
337 displayMode => $displayMode,
338 showHints => $will{showHints},
339 showSolutions => $will{showSolutions},
340 refreshMath2img => $will{showHints} || $will{showSolutions},
341 processAnswers => 1,
342 },
343 );
344
345 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer);
346 ##### fix hint/solution options #####
347
348 $can{showHints} &&= $pg->{flags}->{hintExists}
349 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
350 $can{showSolutions} &&= $pg->{flags}->{solutionExists};
351
352 ##### store fields #####
353
354 $self->{want} = \%want;
355 $self->{must} = \%must;
356 $self->{can} = \%can;
357 $self->{will} = \%will;
358 $self->{pg} = $pg;
359}
360
361sub if_errors($$) {
362 my ($self, $arg) = @_;
363
364 if ($self->{isOpen}) {
365 return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
366 } else {
367 return !$arg;
368 }
369}
370
371sub head {
372 my ($self) = @_;
373
374 return "" unless $self->{isOpen};
375 return $self->{pg}->{head_text} if $self->{pg}->{head_text};
376}
377
378sub options {
379 my ($self) = @_;
380
381 return "" if $self->{invalidProblem};
382 my $sourceFilePathfield = '';
383 if($self->r->param("sourceFilePath")) {
384 $sourceFilePathfield = CGI::hidden(-name => "sourceFilePath",
385 -value => $self->r->param("sourceFilePath"));
386 }
387
388 return join("",
389 CGI::start_form("POST", $self->{r}->uri),
390 $self->hidden_authen_fields,
391 $sourceFilePathfield,
392 CGI::hr(),
393 CGI::start_div({class=>"viewOptions"}),
394 $self->viewOptions(),
395 CGI::end_div(),
396 CGI::end_form()
397 );
398}
399
400sub siblings {
401 my ($self) = @_;
402 my $r = $self->r;
403 my $db = $r->db;
404 my $urlpath = $r->urlpath;
405
406 # can't show sibling problems if the set is invalid
407 return "" if $self->{invalidSet};
408
409 my $courseID = $urlpath->arg("courseID");
410 my $setID = $self->{set}->set_id;
411 my $eUserID = $r->param("effectiveUser");
412 my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
413
414 print CGI::start_ul({class=>"LinksMenu"});
415 print CGI::start_li();
416 print CGI::span({style=>"font-size:larger"}, "Problems");
417 print CGI::start_ul();
418
419 foreach my $problemID (@problemIDs) {
420 my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
421 courseID => $courseID, setID => $setID, problemID => $problemID);
422 print CGI::li(CGI::a({href=>$self->systemLink($problemPage, params=>{displayMode => $self->{displayMode}})}, "Problem $problemID"));
423 }
424
425 print CGI::end_ul();
426 print CGI::end_li();
427 print CGI::end_ul();
428
429 return "";
430}
431
432sub nav {
433 my ($self, $args) = @_;
434 my $r = $self->r;
435 my $db = $r->db;
436 my $urlpath = $r->urlpath;
437
438 my $courseID = $urlpath->arg("courseID");
439 my $setID = $self->{set}->set_id if !($self->{invalidSet});
440 my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
441 my $eUserID = $r->param("effectiveUser");
442
443 my ($prevID, $nextID);
444
445 if (!$self->{invalidProblem}) {
446 my @problemIDs = $db->listUserProblems($eUserID, $setID);
447 foreach my $id (@problemIDs) {
448 $prevID = $id if $id < $problemID
449 and (not defined $prevID or $id > $prevID);
450 $nextID = $id if $id > $problemID
451 and (not defined $nextID or $id < $nextID);
452 }
453 }
454
455 my @links;
456
457 if ($prevID) {
458 my $prevPage = $urlpath->newFromModule(__PACKAGE__,
459 courseID => $courseID, setID => $setID, problemID => $prevID);
460 push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
461 } else {
462 push @links, "Previous Problem", "", "navPrev";
463 }
464
465 push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList";
466
467 if ($nextID) {
468 my $nextPage = $urlpath->newFromModule(__PACKAGE__,
469 courseID => $courseID, setID => $setID, problemID => $nextID);
470 push @links, "Next Problem", $r->location . $nextPage->path, "navNext";
471 } else {
472 push @links, "Next Problem", "", "navNext";
473 }
474
475 my $tail = "&displayMode=".$self->{displayMode};
476 return $self->navMacro($args, $tail, @links);
477}
478
479sub title {
480 my ($self) = @_;
481
482 # using the url arguments won't break if the set/problem are invalid
483 my $setID = $self->r->urlpath->arg("setID");
484 my $problemID = $self->r->urlpath->arg("problemID");
485
486 return "$setID : $problemID";
487}
488
489sub body {
490 my $self = shift;
491 my $r = $self->r;
492 my $ce = $r->ce;
493 my $db = $r->db;
494 my $authz = $r->authz;
495 my $urlpath = $r->urlpath;
496 my $user = $r->param('user');
497
498 if ($self->{invalidSet}) {
499 return CGI::div({class=>"ResultsWithError"},
500 CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . "."));
501 }
502
503 if ($self->{invalidProblem}) {
504 return CGI::div({class=>"ResultsWithError"},
505 CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . "."));
506 }
507
508 unless ($self->{isOpen}) {
509 return CGI::div({class=>"ResultsWithError"},
510 CGI::p("This problem is not available because the problem set that contains it is not yet open."));
511 }
512 # unpack some useful variables
513 my $set = $self->{set};
514 my $problem = $self->{problem};
515 my $editMode = $self->{editMode};
516 my $permissionLevel = $self->{permissionLevel};
517 my $submitAnswers = $self->{submitAnswers};
518 my $checkAnswers = $self->{checkAnswers};
519 my $previewAnswers = $self->{previewAnswers};
520 my %want = %{ $self->{want} };
521 my %can = %{ $self->{can} };
522 my %must = %{ $self->{must} };
523 my %will = %{ $self->{will} };
524 my $pg = $self->{pg};
525
526 my $courseName = $urlpath->arg("courseID");
527
528 my $editorLink = "";
529 # if we are here without a real problem set, carry that through
530 my $forced_field = [];
531 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if
532 ($set->set_id eq 'Undefined_Set');
533 if ($authz->hasPermissions($user, "modify_problem_sets")) {
534 my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
535 courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id);
536 my $editorURL = $self->systemLink($editorPage, params=>$forced_field);
537 $editorLink = CGI::a({href=>$editorURL}, "Edit this problem");
538 }
539
540 ##### translation errors? #####
541
542 if ($pg->{flags}->{error_flag}) {
543 print $self->errorOutput($pg->{errors}, $pg->{body_text});
544 print $editorLink;
545 return "";
546 }
547
548 ##### answer processing #####
549 $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer);
550 # if answers were submitted:
551 my $scoreRecordedMessage;
552 my $pureProblem;
553 if ($submitAnswers) {
554 # get a "pure" (unmerged) UserProblem to modify
555 # this will be undefined if the problem has not been assigned to this user
556 $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
557 if (defined $pureProblem) {
558 # store answers in DB for sticky answers
559 my %answersToStore;
560 my %answerHash = %{ $pg->{answers} };
561 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!!
562 foreach (keys %answerHash);
563
564 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating
565 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
566 # however we need to store them. Fortunately they are still in the input form.
567 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
568 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names);
569
570 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
571 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
572 my $answerString = encodeAnswers(%answersToStore,
573 @answer_order);
574
575 # store last answer to database
576 $problem->last_answer($answerString);
577 $pureProblem->last_answer($answerString);
578 $db->putUserProblem($pureProblem);
579
580 # store state in DB if it makes sense
581 if ($will{recordAnswers}) {
582 $problem->status($pg->{state}->{recorded_score});
583 $problem->attempted(1);
584 $problem->num_correct($pg->{state}->{num_of_correct_ans});
585 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
586 $pureProblem->status($pg->{state}->{recorded_score});
587 $pureProblem->attempted(1);
588 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
589 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
590 if ($db->putUserProblem($pureProblem)) {
591 $scoreRecordedMessage = "Your score was recorded.";
592 } else {
593 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
594 }
595 # write to the transaction log, just to make sure
596 writeLog($self->{ce}, "transaction",
597 $problem->problem_id."\t".
598 $problem->set_id."\t".
599 $problem->user_id."\t".
600 $problem->source_file."\t".
601 $problem->value."\t".
602 $problem->max_attempts."\t".
603 $problem->problem_seed."\t".
604 $pureProblem->status."\t".
605 $pureProblem->attempted."\t".
606 $pureProblem->last_answer."\t".
607 $pureProblem->num_correct."\t".
608 $pureProblem->num_incorrect
609 );
610 } else {
611 if (time < $set->open_date or time > $set->due_date) {
612 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed.";
613 } else {
614 $scoreRecordedMessage = "Your score was not recorded.";
615 }
616 }
617 } else {
618 $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you.";
619 }
620 }
621
622 # logging student answers
623
624 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
625 if ( defined($answer_log ) and defined($pureProblem)) {
626 if ($submitAnswers ) {
627 my $answerString = "";
628 my %answerHash = %{ $pg->{answers} };
629 # FIXME this is the line 552 error. make sure original student ans is defined.
630 # The fact that it is not defined is probably due to an error in some answer evaluator.
631 # But I think it is useful to suppress this error message in the log.
632 foreach (sort keys %answerHash) {
633 my $student_ans = $answerHash{$_}->{original_student_ans} ||'';
634 $answerString .= $student_ans."\t"
635 }
636 $answerString = '' unless defined($answerString); # insure string is defined.
637 writeCourseLog($self->{ce}, "answer_log",
638 join("",
639 '|', $problem->user_id,
640 '|', $problem->set_id,
641 '|', $problem->problem_id,
642 '|',"\t",
643 time(),"\t",
644 $answerString,
645 ),
646 );
647
648 }
649 }
650
651 $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer);
652
653 ##### output #####
654
655 print CGI::start_div({class=>"problemHeader"});
656
657 # custom message for editor
658 if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) {
659 if ($editMode eq "temporaryFile") {
660 print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file));
661 } elsif ($editMode eq "savedFile") {
662 # taken care of in the initialization phase
663 }
664 }
665
666 # attempt summary
667 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything.
668 # until after the due date
669 # do I need to check $will{showCorrectAnswers} to make preflight work??
670 if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) {
671 # print this if user submitted answers OR requested correct answers
672
673 print $self->attemptResults($pg, 1,
674 $will{showCorrectAnswers},
675 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
676 } elsif ($checkAnswers) {
677 # print this if user previewed answers
678 print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br() );
679 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
680 # show attempt answers
681 # show correct answers if asked
682 # show attempt results (correctness)
683 # show attempt previews
684 } elsif ($previewAnswers) {
685 # print this if user previewed answers
686 print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
687 # show attempt answers
688 # don't show correct answers
689 # don't show attempt results (correctness)
690 # show attempt previews
691 }
692
693 print CGI::end_div();
694
695 print CGI::start_div({class=>"problem"});
696
697 # main form
698 print
699 CGI::startform("POST", $r->uri),
700 $self->hidden_authen_fields,
701 CGI::p($pg->{body_text}),
702 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})),
703 CGI::p(
704 ($can{showCorrectAnswers}
705 ? CGI::checkbox(
706 -name => "showCorrectAnswers",
707 -checked => $will{showCorrectAnswers},
708 -label => "Show correct answers",
709 ) ." "
710 : "" ),
711 ($can{showHints}
712 ? '<div style="color:red">'. CGI::checkbox(
713 -name => "showHints",
714 -checked => $will{showHints},
715 -label => "Show Hints",
716 ) . "</div> "
717 : " " ),
718 ($can{showSolutions}
719 ? CGI::checkbox(
720 -name => "showSolutions",
721 -checked => $will{showSolutions},
722 -label => "Show Solutions",
723 ) . " "
724 : " " ),CGI::br(),
725 CGI::submit(-name=>"previewAnswers",
726 -label=>"Preview Answers"),
727 ($can{recordAnswers}
728 ? CGI::submit(-name=>"submitAnswers",
729 -label=>"Submit Answers")
730 : ""),
731 ( $can{checkAnswers}
732 ? CGI::submit(-name=>"checkAnswers",
733 -label=>"Check Answers")
734 : ""),
735 );
736 print CGI::end_div();
737
738 print CGI::start_div({class=>"scoreSummary"});
739
740 # score summary
741 my $attempts = $problem->num_correct + $problem->num_incorrect;
742 my $attemptsNoun = $attempts != 1 ? "times" : "time";
743 my $lastScore = sprintf("%.0f%%", $problem->status * 100); # Round to whole number
744 my ($attemptsLeft, $attemptsLeftNoun);
745 if ($problem->max_attempts == -1) {
746 # unlimited attempts
747 $attemptsLeft = "unlimited";
748 $attemptsLeftNoun = "attempts";
749 } else {
750 $attemptsLeft = $problem->max_attempts - $attempts;
751 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
752 }
753
754 my $setClosed = 0;
755 my $setClosedMessage;
756 if (time < $set->open_date or time > $set->due_date) {
757 $setClosed = 1;
758 $setClosedMessage = "This problem set is closed.";
759 if ($authz->hasPermissions($user, "view_answers")) {
760 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
761 } else {
762 $setClosedMessage .= " Additional attempts will not be recorded.";
763 }
764 }
765
766 my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)";
767 print CGI::p(
768 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
769 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
770 $problem->attempted
771 ? "Your recorded score is $lastScore. $notCountedMessage" . CGI::br()
772 : "",
773 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
774 );
775 print CGI::end_div();
776
777 # save state for viewOptions
778 print CGI::hidden(
779 -name => "showOldAnswers",
780 -value => $will{showOldAnswers}
781 ),
782
783 CGI::hidden(
784 -name => "displayMode",
785 -value => $self->{displayMode}
786 );
787 print( CGI::hidden(
788 -name => 'editMode',
789 -value => $self->{editMode},
790 )
791 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
792 print( CGI::hidden(
793 -name => 'sourceFilePath',
794 -value => $self->{problem}->{source_file}
795 )) if defined($self->{problem}->{source_file});
796
797 print( CGI::hidden(
798 -name => 'problemSeed',
799 -value => $r->param("problemSeed")
800 )) if defined($r->param("problemSeed"));
801
802 # end of main form
803 print CGI::endform();
804
805 print CGI::start_div({class=>"problemFooter"});
806
807 ## arguments for answer inspection button
808 #my $prof_url = $ce->{webworkURLs}->{oldProf};
809 #my $webworkURL = $ce->{webworkURLs}->{root};
810 #my $cgi_url = $prof_url;
811 #$cgi_url=~ s|/[^/]*$||; # clip profLogin.pl
812 #my $authen_args = $self->url_authen_args();
813 #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
814
815 my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
816 courseID => $courseName);
817 my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
818
819 # print answer inspection button
820 if ($authz->hasPermissions($user, "view_answers")) {
821 print "\n",
822 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
823 $self->hidden_authen_fields,"\n",
824 CGI::hidden(-name => 'courseID', -value=>$courseName), "\n",
825 CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
826 CGI::hidden(-name => 'setID', -value=>$problem->set_id), "\n",
827 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n",
828 CGI::p( {-align=>"left"},
829 CGI::submit(-name => 'action', -value=>'Show Past Answers')
830 ), "\n",
831 CGI::endform();
832 }
833
834 # feedback form url
835 my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback",
836 courseID => $courseName);
837 my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action
838
839 #print feedback form
840 print
841 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
842 $self->hidden_authen_fields,"\n",
843 CGI::hidden("module", __PACKAGE__),"\n",
844 CGI::hidden("set", $set->set_id),"\n",
845 CGI::hidden("problem", $problem->problem_id),"\n",
846 CGI::hidden("displayMode", $self->{displayMode}),"\n",
847 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n",
848 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
849 CGI::hidden("showHints", $will{showHints}),"\n",
850 CGI::hidden("showSolutions", $will{showSolutions}),"\n",
851 CGI::p({-align=>"left"},
852 CGI::submit(-name=>"feedbackForm", -label=>"Email instructor")
853 ),
854 CGI::endform(),"\n";
855
856 # FIXME print editor link
857 print $editorLink; #empty unless it is appropriate to have an editor link.
858
859 print CGI::end_div();
860
861 # debugging stuff
862 if (0) {
631 print 863 print
632 "Content-type: text/html\r\n\r\n <h4>Software error</h4> <p>\n\n$message\n<p>\n 864 CGI::hr(),
633 Please inform the webwork meister.<p>\n 865 CGI::h2("debugging information"),
634 In addition to the error message above the following warnings were detected: 866 CGI::h3("form fields"),
635 <HR> 867 ref2string($self->{formFields}),
636 $Global::WARNINGS; 868 CGI::h3("user object"),
637 <HR> 869 ref2string($self->{user}),
638 It's sometimes hard to tell exactly what has gone wrong since the 870 CGI::h3("set object"),
639 full error message may have been sent to 871 ref2string($set),
640 standard error instead of to standard out. 872 CGI::h3("problem object"),
641 <p> To debug you can 873 ref2string($problem),
642 <ul> 874 CGI::h3("PG object"),
643 <li> guess what went wrong and try to fix it. 875 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 }; 876 }
661 877
662 878 return "";
663
664} 879}
665 880
881##### output utilities #####
882
883sub attemptResults {
884 my $self = shift;
885 my $pg = shift;
886 my $showAttemptAnswers = shift;
887 my $showCorrectAnswers = shift;
888 my $showAttemptResults = $showAttemptAnswers && shift;
889 my $showSummary = shift;
890 my $showAttemptPreview = shift || 0;
891
892 my $ce = $self->r->ce;
893
894 my $problemResult = $pg->{result}; # the overall result of the problem
895 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
896
897 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
898
899 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
900 my $imgGen = WeBWorK::PG::ImageGenerator->new(
901 tempDir => $ce->{webworkDirs}->{tmp},
902 latex => $ce->{externalPrograms}->{latex},
903 dvipng => $ce->{externalPrograms}->{dvipng},
904 useCache => 1,
905 cacheDir => $ce->{webworkDirs}->{equationCache},
906 cacheURL => $ce->{webworkURLs}->{equationCache},
907 cacheDB => $ce->{webworkFiles}->{equationCacheDB},
908 dvipng_align => $ce->{pg}->{renderers}->{dvipng_align},
909 dvipng_depth_db => $ce->{pg}->{renderers}->{dvipng_depth_db},
910 );
911
912 my $header;
913 #$header .= CGI::th("Part");
914 $header .= $showAttemptAnswers ? CGI::th("Entered") : "";
915 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : "";
916 $header .= $showCorrectAnswers ? CGI::th("Correct") : "";
917 $header .= $showAttemptResults ? CGI::th("Result") : "";
918 $header .= $showMessages ? CGI::th("Messages") : "";
919 my @tableRows = ( $header );
920 my $numCorrect = 0;
921 foreach my $name (@answerNames) {
922 my $answerResult = $pg->{answers}->{$name};
923 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
924 my $preview = ($showAttemptPreview
925 ? $self->previewAnswer($answerResult, $imgGen)
926 : "");
927 my $correctAnswer = $answerResult->{correct_ans};
928 my $answerScore = $answerResult->{score};
929 my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
930 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
931 $numCorrect += $answerScore > 0;
932 my $resultString = $answerScore == 1 ? "correct" : "incorrect";
933
934 # get rid of the goofy prefix on the answer names (supposedly, the format
935 # of the answer names is changeable. this only fixes it for "AnSwEr"
936 #$name =~ s/^AnSwEr//;
937
938 my $row;
939 #$row .= CGI::td($name);
940 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
941 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : "";
942 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
943 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : "";
944 $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : "";
945 push @tableRows, $row;
946 }
947
948 # render equation images
949 $imgGen->render(refresh => 1);
950
951# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
952 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
953# FIXME -- I left the old code in in case we have to back out.
954# my $summary = "On this attempt, you answered $numCorrect out of "
955# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
956 my $summary = "";
957 if (scalar @answerNames == 1) {
958 if ($numCorrect == scalar @answerNames) {
959 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
960 } else {
961 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
962 }
963 } else {
964 if ($numCorrect == scalar @answerNames) {
965 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
966 } else {
967 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
968 }
969 }
970
971 return
972 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
973 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
974}
975
976#sub nbsp {
977# my $str = shift;
978# ($str =~/\S/) ? $str : '&nbsp;' ; # returns non-breaking space for empty strings
979# # tricky cases: $str =0;
980# # $str is a complex number
981#}
982
983sub viewOptions {
984 my ($self) = @_;
985 my $ce = $self->r->ce;
986
987 # don't show options if we don't have anything to show
988 return if $self->{invalidSet} or $self->{invalidProblem};
989 return unless $self->{isOpen};
990
991 my $displayMode = $self->{displayMode};
992 my %must = %{ $self->{must} };
993 my %can = %{ $self->{can} };
994 my %will = %{ $self->{will} };
995
996 my $optionLine;
997 $can{showOldAnswers} and $optionLine .= join "",
998 "Show: &nbsp;".CGI::br(),
999 CGI::checkbox(
1000 -name => "showOldAnswers",
1001 -checked => $will{showOldAnswers},
1002 -label => "Saved answers",
1003 ), "&nbsp;&nbsp;".CGI::br();
1004
1005 $optionLine and $optionLine .= join "", CGI::br();
1006
1007 my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
1008 my @active_modes = grep { exists $display_modes{$_} }
1009 @{$ce->{pg}->{displayModes}};
1010 my $modeLine = (scalar(@active_modes)>1) ?
1011 "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
1012 CGI::radio_group(
1013 -name => "displayMode",
1014 -values => \@active_modes,
1015 -default => $displayMode,
1016 -linebreak=>'true',
1017 -labels => {
1018 plainText => "plain",
1019 formattedText => "formatted",
1020 images => "images",
1021 jsMath => "jsMath",
1022 asciimath => "asciimath",
1023 },
1024 ). CGI::br().CGI::hr() : '';
1025
1026 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
1027 $modeLine,
1028 $optionLine,
1029 CGI::submit(-name=>"redisplay", -label=>"Save Options"),
1030 );
1031}
1032
1033sub previewAnswer {
1034 my ($self, $answerResult, $imgGen) = @_;
1035 my $ce = $self->r->ce;
1036 my $effectiveUser = $self->{effectiveUser};
1037 my $set = $self->{set};
1038 my $problem = $self->{problem};
1039 my $displayMode = $self->{displayMode};
1040
1041 # note: right now, we have to do things completely differently when we are
1042 # rendering math from INSIDE the translator and from OUTSIDE the translator.
1043 # so we'll just deal with each case explicitly here. there's some code
1044 # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
1045
1046 my $tex = $answerResult->{preview_latex_string};
1047
1048 return "" unless defined $tex and $tex ne "";
1049
1050 if ($displayMode eq "plainText") {
1051 return $tex;
1052 } elsif ($displayMode eq "formattedText") {
1053 my $tthCommand = $ce->{externalPrograms}->{tth}
1054 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
1055 . "\\(".$tex."\\)\n"
1056 . "END_OF_INPUT\n";
1057
1058 # call tth
1059 my $result = `$tthCommand`;
1060 if ($?) {
1061 return "<b>[tth failed: $? $@]</b>";
1062 }
1063 return $result;
1064 } elsif ($displayMode eq "images") {
1065 $imgGen->add($tex);
1066 } elsif ($displayMode eq "jsMath") {
1067
1068 return '<DIV CLASS="math">'.$tex.'</DIV>' ;
1069
1070
1071
1072
1073 }
1074}
1075
1076##### permission queries #####
1077
1078# this stuff should be abstracted out into the permissions system
1079# however, the permission system only knows about things in the
1080# course environment and the username. hmmm...
1081
1082# also, i should fix these so that they have a consistent calling
1083# format -- perhaps:
1084# canPERM($ce, $user, $set, $problem, $permissionLevel)
1085
1086sub canShowCorrectAnswers($$) {
1087 my ($permissionLevel, $answerDate) = @_;
1088 return $permissionLevel > 0 || time > $answerDate;
1089}
1090
1091sub canShowSolutions($$) {
1092 my ($permissionLevel, $answerDate) = @_;
1093 return canShowCorrectAnswers($permissionLevel, $answerDate);
1094}
1095
1096sub canRecordAnswers($$$$$) {
1097 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
1098 my $permHigh = $permissionLevel > 0;
1099 my $timeOK = time >= $openDate && time <= $dueDate;
1100 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
1101 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
1102 return $recordAnswers;
1103}
1104
1105sub canCheckAnswers($$) {
1106 my ($permissionLevel, $dueDate) = @_;
1107 my $permHigh = $permissionLevel > 0;
1108 my $timeOK = time >= $dueDate;
1109 my $recordAnswers = $permHigh || $timeOK;
1110 return $recordAnswers;
1111}
1112
1113sub mustRecordAnswers($) {
1114 my ($permissionLevel) = @_;
1115 return $permissionLevel == 0;
1116}
6661; 11171;

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9