[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 1776 - (download) (as text) (annotate)
Wed Feb 4 13:22:56 2004 UTC (9 years, 3 months ago) by gage
File size: 36844 byte(s)
Fixed flaw in the previous correction meant to protect against
undefined student answers.

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9