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

View of /branches/gage_dev/webwork2/lib/WeBWorK/PG.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6435 - (download) (as text) (annotate)
Thu Sep 16 15:38:35 2010 UTC (2 years, 8 months ago) by gage
File size: 14287 byte(s)
Cleaning things up by replacing references to psvnNumber by psvn (which is less redundant)



    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2007 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork2/lib/WeBWorK/PG.pm,v 1.76 2009/07/18 02:52:51 gage Exp $
    5 #
    6 # This program is free software; you can redistribute it and/or modify it under
    7 # the terms of either: (a) the GNU General Public License as published by the
    8 # Free Software Foundation; either version 2, or (at your option) any later
    9 # version, or (b) the "Artistic License" which comes with this package.
   10 #
   11 # This program is distributed in the hope that it will be useful, but WITHOUT
   12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
   13 # FOR A PARTICULAR PURPOSE.  See either the GNU General Public License or the
   14 # Artistic License for more details.
   15 ################################################################################
   16 
   17 package WeBWorK::PG;
   18 
   19 =head1 NAME
   20 
   21 WeBWorK::PG - Invoke one of several PG rendering methods using an easy-to-use
   22 API.
   23 
   24 =cut
   25 
   26 use strict;
   27 use warnings;
   28 use WeBWorK::PG::ImageGenerator;
   29 use WeBWorK::Utils qw(runtime_use formatDateTime makeTempDirectory);
   30 use WeBWorK::Utils::RestrictedClosureClass;
   31 
   32 use constant DISPLAY_MODES => {
   33   # display name   # mode name
   34   tex           => "TeX",
   35   plainText     => "HTML",
   36   formattedText => "HTML_tth",
   37   images        => "HTML_dpng",
   38   jsMath        => "HTML_jsMath",
   39   MathJax       => "HTML_MathJax",
   40   asciimath     => "HTML_asciimath",
   41   LaTeXMathML   => "HTML_LaTeXMathML",
   42 };
   43 
   44 sub new {
   45   shift; # throw away invocant -- we don't need it
   46   my ($ce, $user, $key, $set, $problem, $psvn, $formFields,
   47     $translationOptions) = @_;
   48 
   49   my $renderer = $ce->{pg}->{renderer};
   50 
   51   runtime_use $renderer;
   52 
   53   return $renderer->new(@_);
   54 }
   55 
   56 sub defineProblemEnvir {
   57   my (
   58     $self,
   59     $ce,
   60     $user,
   61     $key,
   62     $set,
   63     $problem,
   64     $psvn,  #FIXME  -- not used
   65     $formFields,
   66     $options,
   67     $extras,
   68   ) = @_;
   69 
   70   my %envir;
   71 
   72   # ----------------------------------------------------------------------
   73 
   74   # PG environment variables
   75   # from docs/pglanguage/pgreference/environmentvariables as of 06/25/2002
   76   # any changes are noted by "ADDED:" or "REMOVED:"
   77 
   78   # Vital state information
   79   # ADDED: displayModeFailover, displayHintsQ, displaySolutionsQ,
   80   #        refreshMath2img, texDisposition
   81 
   82   $envir{psvn}                = $set->psvn;
   83   $envir{psvnNumber}          = "psvnNumber-is-deprecated-Please-use-psvn-Instead"; #FIXME
   84   $envir{probNum}             = $problem->problem_id;
   85   $envir{questionNumber}      = $envir{probNum};
   86   $envir{fileName}            = $problem->source_file;
   87   $envir{probFileName}        = $envir{fileName};
   88   $envir{problemSeed}         = $problem->problem_seed;
   89   $envir{displayMode}         = translateDisplayModeNames($options->{displayMode});
   90   $envir{languageMode}        = $envir{displayMode};
   91   $envir{outputMode}          = $envir{displayMode};
   92   $envir{displayHintsQ}       = $options->{showHints};
   93   $envir{displaySolutionsQ}   = $options->{showSolutions};
   94   $envir{texDisposition}      = "pdf"; # in webwork2, we use pdflatex
   95 
   96   # Problem Information
   97   # ADDED: courseName, formatedDueDate, enable_reduced_scoring
   98 
   99   $envir{openDate}            = $set->open_date;
  100   $envir{formattedOpenDate}   = formatDateTime($envir{openDate}, $ce->{siteDefaults}{timezone});
  101   $envir{dueDate}             = $set->due_date;
  102   $envir{formattedDueDate}    = formatDateTime($envir{dueDate}, $ce->{siteDefaults}{timezone});
  103   $envir{formatedDueDate}     = $envir{formattedDueDate}; # typo in many header files
  104   $envir{answerDate}          = $set->answer_date;
  105   $envir{formattedAnswerDate} = formatDateTime($envir{answerDate}, $ce->{siteDefaults}{timezone});
  106   $envir{numOfAttempts}       = ($problem->num_correct || 0) + ($problem->num_incorrect || 0);
  107   $envir{problemValue}        = $problem->value;
  108   $envir{sessionKey}          = $key;
  109   $envir{courseName}          = $ce->{courseName};
  110   $envir{enable_reduced_scoring} = $set->enable_reduced_scoring;
  111 
  112   # Student Information
  113   # ADDED: studentID
  114 
  115   $envir{sectionName}      = $user->section;
  116   $envir{sectionNumber}    = $envir{sectionName};
  117   $envir{recitationName}   = $user->recitation;
  118   $envir{recitationNumber} = $envir{recitationName};
  119   $envir{setNumber}        = $set->set_id;
  120   $envir{studentLogin}     = $user->user_id;
  121   $envir{studentName}      = $user->first_name . " " . $user->last_name;
  122   $envir{studentID}        = $user->student_id;
  123   $envir{permissionLevel}  = $options->{permissionLevel};  # permission level of actual user
  124   $envir{effectivePermissionLevel}  = $options->{effectivePermissionLevel}; # permission level of user assigned to this question
  125 
  126 
  127   # Answer Information
  128   # REMOVED: refSubmittedAnswers
  129 
  130   $envir{inputs_ref} = $formFields;
  131 
  132   # External Programs
  133   # ADDED: externalLaTeXPath, externalDvipngPath,
  134   #        externalGif2EpsPath, externalPng2EpsPath
  135 
  136   $envir{externalTTHPath}      = $ce->{externalPrograms}->{tth};
  137   $envir{externalLaTeXPath}    = $ce->{externalPrograms}->{latex};
  138   $envir{externalDvipngPath}   = $ce->{externalPrograms}->{dvipng};
  139   $envir{externalGif2EpsPath}  = $ce->{externalPrograms}->{gif2eps};
  140   $envir{externalPng2EpsPath}  = $ce->{externalPrograms}->{png2eps};
  141   $envir{externalGif2PngPath}  = $ce->{externalPrograms}->{gif2png};
  142   $envir{externalCheckUrl}     = $ce->{externalPrograms}->{checkurl};
  143   # Directories and URLs
  144   # REMOVED: courseName
  145   # ADDED: dvipngTempDir
  146   # ADDED: jsMathURL
  147   # ADDED: MathJaxURL
  148   # ADDED: asciimathURL
  149   # ADDED: macrosPath
  150   # REMOVED: macrosDirectory, courseScriptsDirectory
  151   # ADDED: LaTeXMathML
  152 
  153   $envir{cgiDirectory}           = undef;
  154   $envir{cgiURL}                 = undef;
  155   $envir{classDirectory}         = undef;
  156     $envir{macrosPath}             = $ce->{pg}->{directories}{macrosPath};
  157     $envir{appletPath}             = $ce->{pg}->{directories}{appletPath};
  158     $envir{pgDirectories}          = $ce->{pg}->{directories};
  159   $envir{webworkHtmlDirectory}   = $ce->{webworkDirs}->{htdocs}."/";
  160   $envir{webworkHtmlURL}         = $ce->{webworkURLs}->{htdocs}."/";
  161   $envir{htmlDirectory}          = $ce->{courseDirs}->{html}."/";
  162   $envir{htmlURL}                = $ce->{courseURLs}->{html}."/";
  163   $envir{templateDirectory}      = $ce->{courseDirs}->{templates}."/";
  164   $envir{tempDirectory}          = $ce->{courseDirs}->{html_temp}."/";
  165   $envir{tempURL}                = $ce->{courseURLs}->{html_temp}."/";
  166   $envir{scriptDirectory}        = undef;
  167   $envir{webworkDocsURL}         = $ce->{webworkURLs}->{docs}."/";
  168   $envir{localHelpURL}           = $ce->{webworkURLs}->{local_help}."/";
  169   $envir{jsMathURL}              = $ce->{webworkURLs}->{jsMath};
  170   $envir{MathJaxURL}             = $ce->{webworkURLs}->{MathJax};
  171   $envir{asciimathURL}           = $ce->{webworkURLs}->{asciimath};
  172   $envir{LaTeXMathMLURL}         = $ce->{webworkURLs}->{LaTeXMathML};
  173   $envir{server_root_url}        = $ce->{apache_root_url}|| '';
  174 
  175   # Information for sending mail
  176 
  177   $envir{mailSmtpServer} = $ce->{mail}->{smtpServer};
  178   $envir{mailSmtpSender} = $ce->{mail}->{smtpSender};
  179   $envir{ALLOW_MAIL_TO}  = $ce->{mail}->{allowedRecipients};
  180 
  181   # Default values for evaluating answers
  182 
  183   my $ansEvalDefaults = $ce->{pg}->{ansEvalDefaults};
  184   $envir{$_} = $ansEvalDefaults->{$_} foreach (keys %$ansEvalDefaults);
  185 
  186   # ----------------------------------------------------------------------
  187 
  188   # ADDED: ImageGenerator for images mode
  189   if (defined $extras->{image_generator}) {
  190     #$envir{imagegen} = $extras->{image_generator};
  191     # only allow access to the add() method
  192     $envir{imagegen} = new WeBWorK::Utils::RestrictedClosureClass($extras->{image_generator}, "add");
  193   }
  194 
  195   if (defined $extras->{mailer}) {
  196     #my $rmailer = new WeBWorK::Utils::RestrictedClosureClass($extras->{mailer},
  197     # qw/Open SendEnc Close Cancel skipped_recipients error error_msg/);
  198     #my $safe_hole = new Safe::Hole {};
  199     #$envir{mailer} = $safe_hole->wrap($rmailer);
  200     $envir{mailer} = new WeBWorK::Utils::RestrictedClosureClass($extras->{mailer}, "add_message");
  201   }
  202 
  203   #  ADDED: jsMath options
  204   $envir{jsMath} = {%{$ce->{pg}{displayModeOptions}{jsMath}}};
  205 
  206   # Other things...
  207   $envir{QUIZ_PREFIX}              = $options->{QUIZ_PREFIX}; # used by quizzes
  208   $envir{PROBLEM_GRADER_TO_USE}    = $ce->{pg}->{options}->{grader};
  209   $envir{PRINT_FILE_NAMES_FOR}     = $ce->{pg}->{specialPGEnvironmentVars}->{PRINT_FILE_NAMES_FOR};
  210 
  211         #  ADDED: __files__
  212         #    an array for mapping (eval nnn) to filenames in error messages
  213   $envir{__files__} = {
  214     root => $ce->{webworkDirs}{root},     # used to shorten filenames
  215     pg   => $ce->{pg}{directories}{root}, # ditto
  216     tmpl => $ce->{courseDirs}{templates}, # ditto
  217   };
  218 
  219   # variables for interpreting capa problems and other things to be
  220         # seen in a pg file
  221   my $specialPGEnvironmentVarHash = $ce->{pg}->{specialPGEnvironmentVars};
  222   for my $SPGEV (keys %{$specialPGEnvironmentVarHash}) {
  223     $envir{$SPGEV} = $specialPGEnvironmentVarHash->{$SPGEV};
  224   }
  225 
  226   return \%envir;
  227 }
  228 
  229 sub translateDisplayModeNames($) {
  230   my $name = shift;
  231   return DISPLAY_MODES()->{$name};
  232 }
  233 
  234 sub oldSafetyFilter {
  235   my $answer = shift; # accepts one answer and checks it
  236   my $submittedAnswer = $answer;
  237   $answer = '' unless defined $answer;
  238   my ($errorno);
  239   $answer =~ tr/\000-\037/ /;
  240   # Return if answer field is empty
  241   unless ($answer =~ /\S/) {
  242     #$errorno = "<BR>No answer was submitted.";
  243     $errorno = 0;  ## don't report blank answer as error
  244     return ($answer,$errorno);
  245   }
  246   # replace ^ with **    (for exponentiation)
  247   # $answer =~ s/\^/**/g;
  248   # Return if forbidden characters are found
  249   unless ($answer =~ /^[a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\[\]\(\)\,\|]+$/ )  {
  250     $answer =~ tr/a-zA-Z0-9_\-\+ \t\/@%\*\.\n^\(\)/#/c;
  251     $errorno = "<BR>There are forbidden characters in your answer: $submittedAnswer<BR>";
  252     return ($answer,$errorno);
  253   }
  254   $errorno = 0;
  255   return($answer, $errorno);
  256 }
  257 
  258 sub nullSafetyFilter {
  259   return shift, 0; # no errors
  260 }
  261 
  262 1;
  263 
  264 __END__
  265 
  266 =head1 SYNOPSIS
  267 
  268  $pg = WeBWorK::PG->new(
  269    $ce,         # a WeBWorK::CourseEnvironment object
  270    $user,       # a WeBWorK::DB::Record::User object
  271    $sessionKey,
  272    $set,        # a WeBWorK::DB::Record::UserSet object
  273    $problem,    # a WeBWorK::DB::Record::UserProblem object
  274    $psvn,
  275    $formFields  # in &WeBWorK::Form::Vars format
  276    { # translation options
  277      displayMode     => "images", # (plainText|formattedText|images)
  278      showHints       => 1,        # (0|1)
  279      showSolutions   => 0,        # (0|1)
  280      refreshMath2img => 0,        # (0|1)
  281      processAnswers  => 1,        # (0|1)
  282    },
  283  );
  284 
  285  $translator = $pg->{translator}; # WeBWorK::PG::Translator
  286  $body       = $pg->{body_text};  # text string
  287  $header     = $pg->{head_text};  # text string
  288  $answerHash = $pg->{answers};    # WeBWorK::PG::AnswerHash
  289  $result     = $pg->{result};     # hash reference
  290  $state      = $pg->{state};      # hash reference
  291  $errors     = $pg->{errors};     # text string
  292  $warnings   = $pg->{warnings};   # text string
  293  $flags      = $pg->{flags};      # hash reference
  294 
  295 =head1 DESCRIPTION
  296 
  297 WeBWorK::PG is a factory for modules which use the WeBWorK::PG API. Notable
  298 modules which use this API (and exist) are WeBWorK::PG::Local and
  299 WeBWorK::PG::Remote. The course environment key $pg{renderer} is consulted to
  300 determine which render to use.
  301 
  302 =head1 THE WEBWORK::PG API
  303 
  304 Modules which support this API must implement the following method:
  305 
  306 =over
  307 
  308 =item new ENVIRONMENT, USER, KEY, SET, PROBLEM, PSVN, FIELDS, OPTIONS
  309 
  310 The C<new> method creates a translator, initializes it using the parameters
  311 specified, translates a PG file, and processes answers. It returns a reference
  312 to a blessed hash containing the results of the translation process.
  313 
  314 =back
  315 
  316 =head2 Parameters
  317 
  318 =over
  319 
  320 =item ENVIRONMENT
  321 
  322 a WeBWorK::CourseEnvironment object
  323 
  324 =item USER
  325 
  326 a WeBWorK::User object
  327 
  328 =item KEY
  329 
  330 the session key of the current session
  331 
  332 =item SET
  333 
  334 a WeBWorK::Set object
  335 
  336 =item PROBLEM
  337 
  338 a WeBWorK::DB::Record::UserProblem object. The contents of the source_file
  339 field can specify a PG file either by absolute path or path relative to the
  340 "templates" directory. I<The caller should remove taint from this value before
  341 passing!>
  342 
  343 =item PSVN
  344 
  345 the problem set version number: use variable $psvn
  346 
  347 =item FIELDS
  348 
  349 a reference to a hash (as returned by &WeBWorK::Form::Vars) containing form
  350 fields submitted by a problem processor. The translator will look for fields
  351 like "AnSwEr[0-9]" containing submitted student answers.
  352 
  353 =item OPTIONS
  354 
  355 a reference to a hash containing the following data:
  356 
  357 =over
  358 
  359 =item displayMode
  360 
  361 one of "plainText", "formattedText", or "images"
  362 
  363 =item showHints
  364 
  365 boolean, render hints
  366 
  367 =item showSolutions
  368 
  369 boolean, render solutions
  370 
  371 =item refreshMath2img
  372 
  373 boolean, force images created by math2img (in "images" mode) to be recreated,
  374 even if the PG source has not been updated. FIXME: remove this option.
  375 
  376 =item processAnswers
  377 
  378 boolean, call answer evaluators and graders
  379 
  380 =back
  381 
  382 =back
  383 
  384 =head2 RETURN VALUE
  385 
  386 The C<new> method returns a blessed hash reference containing the following
  387 fields. More information can be found in the documentation for
  388 WeBWorK::PG::Translator.
  389 
  390 =over
  391 
  392 =item translator
  393 
  394 The WeBWorK::PG::Translator object used to render the problem.
  395 
  396 =item head_text
  397 
  398 HTML code for the E<lt>headE<gt> block of an resulting web page. Used for
  399 JavaScript features.
  400 
  401 =item body_text
  402 
  403 HTML code for the E<lt>bodyE<gt> block of an resulting web page.
  404 
  405 =item answers
  406 
  407 An C<AnswerHash> object containing submitted answers, and results of answer
  408 evaluation.
  409 
  410 =item result
  411 
  412 A hash containing the results of grading the problem.
  413 
  414 =item state
  415 
  416 A hash containing the new problem state.
  417 
  418 =item errors
  419 
  420 A string containing any errors encountered while rendering the problem.
  421 
  422 =item warnings
  423 
  424 A string containing any warnings encountered while rendering the problem.
  425 
  426 =item flags
  427 
  428 A hash containing PG_flags (see the Translator docs).
  429 
  430 =back
  431 
  432 =head1 METHODS PROVIDED BY THE BASE CLASS
  433 
  434 The following methods are provided for use by subclasses of WeBWorK::PG.
  435 
  436 =over
  437 
  438 =item defineProblemEnvir ENVIRONMENT, USER, KEY, SET, PROBLEM, PSVN, FIELDS, OPTIONS
  439 
  440 Generate a problem environment hash to pass to the renderer.
  441 
  442 =item translateDisplayModeNames NAME
  443 
  444 NAME contains
  445 
  446 =back
  447 
  448 =head1 AUTHOR
  449 
  450 Written by Sam Hathaway, sh002i (at) math.rochester.edu.
  451 
  452 =cut

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9