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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2231 - (download) (as text) (annotate)
Mon May 31 04:17:59 2004 UTC (9 years ago) by jj
File size: 40818 byte(s)
When viewing a problem which isn't really part of a set (e.g., out of SetMaker), make the display mode option buttons work.

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9