[system] / trunk / webwork2 / lib / WeBWorK / PG / Local.pm Repository:
ViewVC logotype

Annotation of /trunk/webwork2/lib/WeBWorK/PG/Local.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1247 - (view) (download) (as text)

1 : gage 1247 ################################################################################
2 :     # WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
3 :     # $Id$
4 :     ################################################################################
5 :    
6 :     package WeBWorK::PG::Local;
7 :    
8 :     =head1 NAME
9 :    
10 :     WeBWorK::PG::Local - Use the WeBWorK::PG API to invoke a local
11 :     WeBWorK::PG::Translator object.
12 :    
13 :     =head1 DESCRIPTION
14 :    
15 :     WeBWorK::PG::Local encapsulates the PG translation process, making multiple
16 :     calls to WeBWorK::PG::Translator. Much of the flexibility of the Translator is
17 :     hidden, instead making choices that are appropriate for the webwork-modperl
18 :     system
19 :    
20 :     It implements the WeBWorK::PG interface and uses a local
21 :     WeBWorK::PG::Translator to perform problem rendering. See the documentation for
22 :     the WeBWorK::PG module for information about the API.
23 :    
24 :     =cut
25 :    
26 :     use strict;
27 :     use warnings;
28 :     use File::Path qw(rmtree);
29 :     use WeBWorK::PG::ImageGenerator;
30 :     use WeBWorK::PG::Translator;
31 :     use WeBWorK::Utils qw(readFile formatDateTime writeTimingLogEntry makeTempDirectory);
32 :    
33 :     sub new {
34 :     my $invocant = shift;
35 :     my $class = ref($invocant) || $invocant;
36 :     my (
37 :     $ce,
38 :     $user,
39 :     $key,
40 :     $set,
41 :     $problem,
42 :     $psvn,
43 :     $formFields, # in CGI::Vars format
44 :     $translationOptions, # hashref containing options for the
45 :     # translator, such as whether to show
46 :     # hints and the display mode to use
47 :     ) = @_;
48 :    
49 :     # write timing log entry
50 :     writeTimingLogEntry($ce, "WeBWorK::PG::new",
51 :     "user=".$user->user_id.",problem=".$ce->{courseName}."/".$set->set_id."/".$problem->problem_id.",mode=".$translationOptions->{displayMode},
52 :     "begin");
53 :    
54 :     # install a local warn handler to collect warnings
55 :     my $warnings = "";
56 :     local $SIG{__WARN__} = sub { $warnings .= shift }
57 :     if $ce->{pg}->{options}->{catchWarnings};
58 :    
59 :     # create a Translator
60 :     #warn "PG: creating a Translator\n";
61 :     my $translator = WeBWorK::PG::Translator->new;
62 :    
63 :     # set the directory hash
64 :     #warn "PG: setting the directory hash\n";
65 :     $translator->rh_directories({
66 :     courseScriptsDirectory => $ce->{pg}->{directories}->{macros},
67 :     macroDirectory => $ce->{courseDirs}->{macros},
68 :     templateDirectory => $ce->{courseDirs}->{templates},
69 :     tempDirectory => $ce->{courseDirs}->{html_temp},
70 :     });
71 :    
72 :     # evaluate modules and "extra packages"
73 :     #warn "PG: evaluating modules and \"extra packages\"\n";
74 :     my @modules = @{ $ce->{pg}->{modules} };
75 :     foreach my $module_packages_ref (@modules) {
76 :     my ($module, @extra_packages) = @$module_packages_ref;
77 :     # the first item is the main package
78 :     $translator->evaluate_modules($module);
79 :     # the remaining items are "extra" packages
80 :     $translator->load_extra_packages(@extra_packages);
81 :     }
82 :    
83 :     # set the environment (from defineProblemEnvir)
84 :     #warn "PG: setting the environment (from defineProblemEnvir)\n";
85 :     my $envir = defineProblemEnvir(
86 :     $ce,
87 :     $user,
88 :     $key,
89 :     $set,
90 :     $problem,
91 :     $psvn,
92 :     $formFields,
93 :     $translationOptions,
94 :     );
95 :     $translator->environment($envir);
96 :    
97 :     # initialize the Translator
98 :     #warn "PG: initializing the Translator\n";
99 :     $translator->initialize();
100 :    
101 :     # load IO.pl, PG.pl, and dangerousMacros.pl using unrestricted_load
102 :     # i'd like to change this at some point to have the same sort of interface to global.conf
103 :     # that the module loading does -- have a list of macros to load unrestrictedly.
104 :     #warn "PG: loading IO.pl, PG.pl, and dangerousMacros.pl using unrestricted_load\n";
105 :     foreach (qw(IO.pl PG.pl dangerousMacros.pl)) {
106 :     my $macroPath = $ce->{pg}->{directories}->{macros} . "/$_";
107 :     my $err = $translator->unrestricted_load($macroPath);
108 :     warn "Error while loading $macroPath: $err" if $err;
109 :     }
110 :    
111 :     # set the opcode mask (using default values)
112 :     #warn "PG: setting the opcode mask (using default values)\n";
113 :     $translator->set_mask();
114 :    
115 :     # store the problem source
116 :     #warn "PG: storing the problem source\n";
117 :     my $sourceFile = $problem->source_file;
118 :     $sourceFile = $ce->{courseDirs}->{templates}."/".$sourceFile
119 :     unless ($sourceFile =~ /^\//);
120 :     eval { $translator->source_string(readFile($sourceFile)) };
121 :     if ($@) {
122 :     # well, we couldn't get the problem source, for some reason.
123 :     return bless {
124 :     translator => $translator,
125 :     head_text => "",
126 :     body_text => <<EOF,
127 :     WeBWorK::Utils::readFile($sourceFile) says:
128 :     $@
129 :     EOF
130 :     answers => {},
131 :     result => {},
132 :     state => {},
133 :     errors => "Failed to read the problem source file.",
134 :     warnings => $warnings,
135 :     flags => {error_flag => 1},
136 :     }, $class;
137 :     }
138 :    
139 :     # install a safety filter (&safetyFilter)
140 :     #warn "PG: installing a safety filter\n";
141 :     $translator->rf_safety_filter(\&safetyFilter);
142 :    
143 :     # write timing log entry -- the translator is now all set up
144 :     writeTimingLogEntry($ce, "WeBWorK::PG::new",
145 :     "initialized",
146 :     "intermediate");
147 :    
148 :     # translate the PG source into text
149 :     #warn "PG: translating the PG source into text\n";
150 :     $translator->translate();
151 :    
152 :     # after we're done translating, we may have to clean up after the
153 :     # translator:
154 :    
155 :     # for example, HTML_img mode uses a tempdir for dvipng's temp files.\
156 :     # We have to remove it.
157 :     if ($envir->{dvipngTempDir}) {
158 :     rmtree($envir->{dvipngTempDir}, 0, 0);
159 :     }
160 :    
161 :     # HTML_dpng, on the other hand, uses an ImageGenerator. We have to
162 :     # render the queued equations.
163 :     if ($envir->{imagegen}) {
164 :     my $sourceFile = $ce->{courseDirs}->{templates} . "/" . $problem->source_file;
165 :     my %mtimeOption = -e $sourceFile
166 :     ? (mtime => (stat $sourceFile)[9])
167 :     : ();
168 :    
169 :     $envir->{imagegen}->render(
170 :     refresh => $translationOptions->{refreshMath2img},
171 :     %mtimeOption,
172 :     );
173 :     }
174 :    
175 :     my ($result, $state); # we'll need these on the other side of the if block!
176 :     if ($translationOptions->{processAnswers}) {
177 :    
178 :     # process student answers
179 :     #warn "PG: processing student answers\n";
180 :     $translator->process_answers($formFields);
181 :    
182 :     # retrieve the problem state and give it to the translator
183 :     #warn "PG: retrieving the problem state and giving it to the translator\n";
184 :     $translator->rh_problem_state({
185 :     recorded_score => $problem->status,
186 :     num_of_correct_ans => $problem->num_correct,
187 :     num_of_incorrect_ans => $problem->num_incorrect,
188 :     });
189 :    
190 :     # determine an entry order -- the ANSWER_ENTRY_ORDER flag is built by
191 :     # the PG macro package (PG.pl)
192 :     #warn "PG: determining an entry order\n";
193 :     my @answerOrder =
194 :     $translator->rh_flags->{ANSWER_ENTRY_ORDER}
195 :     ? @{ $translator->rh_flags->{ANSWER_ENTRY_ORDER} }
196 :     : keys %{ $translator->rh_evaluated_answers };
197 :    
198 :     # install a grader -- use the one specified in the problem,
199 :     # or fall back on the default from the course environment.
200 :     # (two magic strings are accepted, to avoid having to
201 :     # reference code when it would be difficult.)
202 :     #warn "PG: installing a grader\n";
203 :     my $grader = $translator->rh_flags->{PROBLEM_GRADER_TO_USE}
204 :     || $ce->{pg}->{options}->{grader};
205 :     $grader = $translator->rf_std_problem_grader
206 :     if $grader eq "std_problem_grader";
207 :     $grader = $translator->rf_avg_problem_grader
208 :     if $grader eq "avg_problem_grader";
209 :     die "Problem grader $grader is not a CODE reference."
210 :     unless ref $grader eq "CODE";
211 :     $translator->rf_problem_grader($grader);
212 :    
213 :     # grade the problem
214 :     #warn "PG: grading the problem\n";
215 :     ($result, $state) = $translator->grade_problem(
216 :     answers_submitted => $translationOptions->{processAnswers},
217 :     ANSWER_ENTRY_ORDER => \@answerOrder,
218 :     );
219 :    
220 :     }
221 :    
222 :     # write timing log entry
223 :     writeTimingLogEntry($ce, "WeBWorK::PG::new", "", "end");
224 :    
225 :     # return an object which contains the translator and the results of
226 :     # the translation process. this is DIFFERENT from the "format expected
227 :     # by Webwork.pm (and I believe processProblem8, but check.)"
228 :     return bless {
229 :     translator => $translator,
230 :     head_text => ${ $translator->r_header },
231 :     body_text => ${ $translator->r_text },
232 :     answers => $translator->rh_evaluated_answers,
233 :     result => $result,
234 :     state => $state,
235 :     errors => $translator->errors,
236 :     warnings => $warnings,
237 :     flags => $translator->rh_flags,
238 :     }, $class;
239 :     }
240 :    
241 :     # -----
242 :    
243 :     sub defineProblemEnvir {
244 :     my (
245 :     $ce,
246 :     $user,
247 :     $key,
248 :     $set,
249 :     $problem,
250 :     $psvn,
251 :     $formFields,
252 :     $options,
253 :     ) = @_;
254 :    
255 :     my %envir;
256 :    
257 :     # ----------------------------------------------------------------------
258 :    
259 :     # PG environment variables
260 :     # from docs/pglanguage/pgreference/environmentvariables as of 06/25/2002
261 :     # any changes are noted by "ADDED:" or "REMOVED:"
262 :    
263 :     # Vital state information
264 :     # ADDED: displayHintsQ, displaySolutionsQ, refreshMath2img,
265 :     # texDisposition
266 :    
267 :     $envir{psvn} = $set->psvn;
268 :     $envir{psvnNumber} = $envir{psvn};
269 :     $envir{probNum} = $problem->problem_id;
270 :     $envir{questionNumber} = $envir{probNum};
271 :     $envir{fileName} = $problem->source_file;
272 :     $envir{probFileName} = $envir{fileName};
273 :     $envir{problemSeed} = $problem->problem_seed;
274 :     $envir{displayMode} = translateDisplayModeNames($options->{displayMode});
275 :     $envir{languageMode} = $envir{displayMode};
276 :     $envir{outputMode} = $envir{displayMode};
277 :     $envir{displayHintsQ} = $options->{showHints};
278 :     $envir{displaySolutionsQ} = $options->{showSolutions};
279 :     # FIXME: this is HTML_img specific
280 :     #$envir{refreshMath2img} = $options->{refreshMath2img};
281 :     $envir{texDisposition} = "pdf"; # in webwork-modperl, we use pdflatex
282 :    
283 :     # Problem Information
284 :     # ADDED: courseName, formatedDueDate
285 :    
286 :     $envir{openDate} = $set->open_date;
287 :     $envir{formattedOpenDate} = formatDateTime($envir{openDate});
288 :     $envir{dueDate} = $set->due_date;
289 :     $envir{formattedDueDate} = formatDateTime($envir{dueDate});
290 :     $envir{formatedDueDate} = $envir{formattedDueDate}; # typo in many header files
291 :     $envir{answerDate} = $set->answer_date;
292 :     $envir{formattedAnswerDate} = formatDateTime($envir{answerDate});
293 :     $envir{numOfAttempts} = ($problem->num_correct || 0) + ($problem->num_incorrect || 0);
294 :     $envir{problemValue} = $problem->value;
295 :     $envir{sessionKey} = $key;
296 :     $envir{courseName} = $ce->{courseName};
297 :    
298 :     # Student Information
299 :     # ADDED: studentID
300 :    
301 :     $envir{sectionName} = $user->section;
302 :     $envir{sectionNumber} = $envir{sectionName};
303 :     $envir{recitationName} = $user->recitation;
304 :     $envir{recitationNumber} = $envir{recitationName};
305 :     $envir{setNumber} = $set->set_id;
306 :     $envir{studentLogin} = $user->user_id;
307 :     $envir{studentName} = $user->first_name . " " . $user->last_name;
308 :     $envir{studentID} = $user->student_id;
309 :    
310 :     # Answer Information
311 :     # REMOVED: refSubmittedAnswers
312 :    
313 :     $envir{inputs_ref} = $formFields;
314 :    
315 :     # External Programs
316 :     # ADDED: externalLaTeXPath, externalDvipngPath,
317 :     # externalGif2EpsPath, externalPng2EpsPath
318 :    
319 :     $envir{externalTTHPath} = $ce->{externalPrograms}->{tth};
320 :     $envir{externalLaTeXPath} = $ce->{externalPrograms}->{latex};
321 :     $envir{externalDvipngPath} = $ce->{externalPrograms}->{dvipng};
322 :     $envir{externalGif2EpsPath} = $ce->{externalPrograms}->{gif2eps};
323 :     $envir{externalPng2EpsPath} = $ce->{externalPrograms}->{png2eps};
324 :     $envir{externalGif2PngPath} = $ce->{externalPrograms}->{gif2png};
325 :    
326 :     # Directories and URLs
327 :     # REMOVED: courseName
328 :     # ADDED: dvipngTempDir
329 :    
330 :     $envir{cgiDirectory} = undef;
331 :     $envir{cgiURL} = undef;
332 :     $envir{classDirectory} = undef;
333 :     $envir{courseScriptsDirectory} = $ce->{pg}->{directories}->{macros}."/";
334 :     $envir{htmlDirectory} = $ce->{courseDirs}->{html}."/";
335 :     $envir{htmlURL} = $ce->{courseURLs}->{html}."/";
336 :     $envir{macroDirectory} = $ce->{courseDirs}->{macros}."/";
337 :     $envir{templateDirectory} = $ce->{courseDirs}->{templates}."/";
338 :     $envir{tempDirectory} = $ce->{courseDirs}->{html_temp}."/";
339 :     $envir{tempURL} = $ce->{courseURLs}->{html_temp}."/";
340 :     $envir{scriptDirectory} = undef;
341 :     $envir{webworkDocsURL} = $ce->{webworkURLs}->{docs}."/";
342 :     # FIXME: this is HTML_img mode-specific
343 :     #$envir{dvipngTempDir} = $options->{displayMode} eq 'images'
344 :     # ? makeTempDirectory($envir{tempDirectory}, "webwork-dvipng")
345 :     # : undef;
346 :    
347 :     # Information for sending mail
348 :    
349 :     $envir{mailSmtpServer} = $ce->{mail}->{smtpServer};
350 :     $envir{mailSmtpSender} = $ce->{mail}->{smtpSender};
351 :     $envir{ALLOW_MAIL_TO} = $ce->{mail}->{allowedRecipients};
352 :    
353 :     # Default values for evaluating answers
354 :    
355 :     my $ansEvalDefaults = $ce->{pg}->{ansEvalDefaults};
356 :     $envir{$_} = $ansEvalDefaults->{$_} foreach (keys %$ansEvalDefaults);
357 :    
358 :     # ----------------------------------------------------------------------
359 :    
360 :     my $basename = "equation-$envir{psvn}.$envir{probNum}";
361 :     $basename .= ".$envir{problemSeed}" if $envir{problemSeed};
362 :    
363 :     # Object for generating equation images
364 :     $envir{imagegen} = WeBWorK::PG::ImageGenerator->new(
365 :     tempDir => $ce->{webworkDirs}->{tmp}, # global temp dir
366 :     dir => $envir{tempDirectory},
367 :     url => $envir{tempURL},
368 :     basename => $basename,
369 :     latex => $envir{externalLaTeXPath},
370 :     dvipng => $envir{externalDvipngPath},
371 :     );
372 :    
373 :     # Other things...
374 :     $envir{QUIZ_PREFIX} = $options->{QUIZ_PREFIX}; # used by quizzes
375 :     $envir{PROBLEM_GRADER_TO_USE} = $ce->{pg}->{options}->{grader};
376 :     $envir{PRINT_FILE_NAMES_FOR} = $ce->{pg}->{specialPGEnvironmentVars}->{PRINT_FILE_NAMES_FOR};
377 :    
378 :     # variables for interpreting capa problems.
379 :     $envir{CAPA_Tools} = $ce->{pg}->{specialPGEnvironmentVars}->{CAPA_Tools};
380 :     $envir{CAPA_MCTools} = $ce->{pg}->{specialPGEnvironmentVars}->{CAPA_MCTools};
381 :     $envir{CAPA_Graphics_URL} = $ce->{pg}->{specialPGEnvironmentVars}->{CAPA_Graphics_URL};
382 :     $envir{CAPA_GraphicsDirectory} = $ce->{pg}->{specialPGEnvironmentVars}->{CAPA_GraphicsDirectory};
383 :    
384 :     return \%envir;
385 :     }
386 :    
387 :     sub translateDisplayModeNames($) {
388 :     my $name = shift;
389 :     return {
390 :     tex => "TeX",
391 :     plainText => "HTML",
392 :     formattedText => "HTML_tth",
393 :     images => "HTML_dpng", # "HTML_img",
394 :     }->{$name};
395 :     }
396 :    
397 :     sub safetyFilter {
398 :     my $answer = shift; # accepts one answer and checks it
399 :     my $submittedAnswer = $answer;
400 :     $answer = '' unless defined $answer;
401 :     my ($errorno);
402 :     $answer =~ tr/\000-\037/ /;
403 :     # Return if answer field is empty
404 :     unless ($answer =~ /\S/) {
405 :     #$errorno = "<BR>No answer was submitted.";
406 :     $errorno = 0; ## don't report blank answer as error
407 :     return ($answer,$errorno);
408 :     }
409 :     # replace ^ with ** (for exponentiation)
410 :     # $answer =~ s/\^/**/g;
411 :     # Return if forbidden characters are found
412 :     unless ($answer =~ /^[a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\[\]\(\)\,\|]+$/ ) {
413 :     $answer =~ tr/a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\(\)/#/c;
414 :     $errorno = "<BR>There are forbidden characters in your answer: $submittedAnswer<BR>";
415 :     return ($answer,$errorno);
416 :     }
417 :     $errorno = 0;
418 :     return($answer, $errorno);
419 :     }
420 :    
421 :     1;
422 :    
423 :     __END__
424 :    
425 :     =head1 OPERATION
426 :    
427 :     WeBWorK::PG goes through the following operations when constructed:
428 :    
429 :     =over
430 :    
431 :     =item Get database information
432 :    
433 :     Retrieve information about the current user, set, and problem from the
434 :     database.
435 :    
436 :     =item Create a translator
437 :    
438 :     Instantiate a WeBWorK::PG::Translator object.
439 :    
440 :     =item Set the directory hash
441 :    
442 :     Set the translator's directory hash (courseScripts, macros, templates, and temp
443 :     directories) from the course environment.
444 :    
445 :     =item Evaluate PG modules
446 :    
447 :     Using the module list from the course environment (pg->modules), perform a
448 :     "use"-like operation to evaluate modules at runtime.
449 :    
450 :     =item Set the problem environment
451 :    
452 :     Use data from the user, set, and problem, as well as the course environemnt and
453 :     translation options, to set the problem environment.
454 :    
455 :     =item Initialize the translator
456 :    
457 :     Call &WeBWorK::PG::Translator::initialize. What more do you want?
458 :    
459 :     =item Load PG.pl and dangerousMacros.pl
460 :    
461 :     These macros must be loaded without opcode masking, so they are loaded here.
462 :    
463 :     =item Set the opcode mask
464 :    
465 :     Set the opcode mask to the default specified by WeBWorK::PG::Translator.
466 :    
467 :     =item Load the problem source
468 :    
469 :     Give the problem source to the translator.
470 :    
471 :     =item Install a safety filter
472 :    
473 :     The safety filter is used to preprocess student input before evaluation. The
474 :     default safety filter, &WeBWorK::PG::safetyFilter, is used.
475 :    
476 :     =item Translate the problem source
477 :    
478 :     Call &WeBWorK::PG::Translator::translate to render the problem source into the
479 :     format given by the display mode.
480 :    
481 :     =item Process student answers
482 :    
483 :     Use form field inputs to evaluate student answers.
484 :    
485 :     =item Load the problem state
486 :    
487 :     Use values from the database to initialize the problem state, so that the
488 :     grader will have a point of reference.
489 :    
490 :     =item Determine an entry order
491 :    
492 :     Use the ANSWER_ENTRY_ORDER flag to determine the order of answers in the
493 :     problem. This is important for problems with dependancies among parts.
494 :    
495 :     =item Install a grader
496 :    
497 :     Use the PROBLEM_GRADER_TO_USE flag, or a default from the course environment,
498 :     to install a grader.
499 :    
500 :     =item Grade the problem
501 :    
502 :     Use the selected grader to grade the problem.
503 :    
504 :     =back
505 :    
506 :     =head1 AUTHOR
507 :    
508 :     Written by Sam Hathaway, sh002i (at) math.rochester.edu.
509 :    
510 :     =cut

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9