[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 555 - (download) (as text) (annotate)
Wed Sep 18 19:25:42 2002 UTC (10 years, 8 months ago) by sh002i
File size: 15604 byte(s)
fixed image centering, added head escape.
-sam

    1 ################################################################################
    2 # WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
    3 # $Id$
    4 ################################################################################
    5 
    6 package WeBWorK::ContentGenerator::Problem;
    7 
    8 =head1 NAME
    9 
   10 WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
   11 
   12 =cut
   13 
   14 use strict;
   15 use warnings;
   16 use base qw(WeBWorK::ContentGenerator);
   17 use CGI qw();
   18 use WeBWorK::Form;
   19 use WeBWorK::PG;
   20 use WeBWorK::Utils qw(ref2string encodeAnswers decodeAnswers);
   21 
   22 ############################################################
   23 #
   24 # user
   25 # key
   26 #
   27 # displayMode
   28 # showOldAnswers
   29 # showCorrectAnswers
   30 # showHints
   31 # showSolutions
   32 #
   33 # AnSwEr# - answer blanks in problem
   34 #
   35 # redisplay - name of the "Redisplay Problem" button
   36 # submitAnswers - name of "Submit Answers" button
   37 #
   38 ############################################################
   39 
   40 sub pre_header_initialize {
   41   my ($self, $setName, $problemNumber) = @_;
   42   my $courseEnv = $self->{courseEnvironment};
   43   my $r = $self->{r};
   44   my $userName = $r->param('user');
   45 
   46   ##### database setup #####
   47 
   48   my $cldb   = WeBWorK::DB::Classlist->new($courseEnv);
   49   my $wwdb   = WeBWorK::DB::WW->new($courseEnv);
   50   my $authdb = WeBWorK::DB::Auth->new($courseEnv);
   51 
   52   my $user            = $cldb->getUser($userName);
   53   my $set             = $wwdb->getSet($userName, $setName);
   54   my $problem         = $wwdb->getProblem($userName, $setName, $problemNumber);
   55   my $psvn            = $wwdb->getPSVN($userName, $setName);
   56   my $permissionLevel = $authdb->getPermissions($userName);
   57 
   58   ##### form processing #####
   59 
   60   # set options from form fields (see comment at top of file for names)
   61   my $displayMode        = $r->param("displayMode")        || $courseEnv->{pg}->{options}->{displayMode};
   62   my $redisplay          = $r->param("redisplay");
   63   my $submitAnswers      = $r->param("submitAnswers");
   64 
   65   # coerce form fields into CGI::Vars format
   66   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
   67 
   68   ##### permissions #####
   69 
   70   # what does the user want to do?
   71   my %want = (
   72     showOldAnswers     => $r->param("showOldAnswers")     || $courseEnv->{pg}->{options}->{showOldAnswers},
   73     showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers},
   74     showHints          => $r->param("showHints")          || $courseEnv->{pg}->{options}->{showHints},
   75     showSolutions      => $r->param("showSolutions")      || $courseEnv->{pg}->{options}->{showSolutions},
   76     recordAnswers      => $r->param("recordAnswers")      || 1,
   77   );
   78 
   79   # are certain options enforced?
   80   my %must = (
   81     showOldAnswers     => 0,
   82     showCorrectAnswers => 0,
   83     showHints          => 0,
   84     showSolutions      => 0,
   85     recordAnswers      => mustRecordAnswers($permissionLevel),
   86   );
   87 
   88   # does the user have permission to use certain options?
   89   my %can = (
   90     showOldAnswers     => 1,
   91     showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
   92     showHints          => 1,
   93     showSolutions      => canShowSolutions($permissionLevel, $set->answer_date),
   94     recordAnswers      => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
   95       $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
   96       # num_correct+num_incorrect+1 -- as this happens before updating $problem
   97   );
   98 
   99   # final values for options
  100   my %will;
  101   foreach(keys %must) {
  102     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  103   }
  104 
  105   ##### sticky answers #####
  106 
  107   if (not $submitAnswers and $will{showOldAnswers}) {
  108     # do this only if new answers are NOT being submitted
  109     my %oldAnswers = decodeAnswers($problem->last_answer);
  110     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  111   }
  112 
  113   ##### translation #####
  114 
  115   my $pg = WeBWorK::PG->new(
  116     $courseEnv,
  117     $user,
  118     $r->param('key'),
  119     $set,
  120     $problem,
  121     $psvn,
  122     $formFields,
  123     { # translation options
  124       displayMode     => $displayMode,
  125       showHints       => $will{showHints},
  126       showSolutions   => $will{showSolutions},
  127       refreshMath2img => $will{showHints} || $will{showSolutions},
  128       # try leaving processAnswers on all the time?
  129       processAnswers  => 1, #$submitAnswers ? 1 : 0,
  130     },
  131   );
  132 
  133   ##### store fields #####
  134 
  135   $self->{cldb}            = $cldb;
  136   $self->{wwdb}            = $wwdb;
  137   $self->{authdb}          = $authdb;
  138 
  139   $self->{user}            = $user;
  140   $self->{set}             = $set;
  141   $self->{problem}         = $problem;
  142   $self->{permissionLevel} = $permissionLevel;
  143 
  144   $self->{displayMode}   = $displayMode;
  145   $self->{redisplay}     = $redisplay;
  146   $self->{submitAnswers} = $submitAnswers;
  147   $self->{formFields}    = $formFields;
  148 
  149   $self->{want} = \%want;
  150   $self->{must} = \%must;
  151   $self->{can}  = \%can;
  152   $self->{will} = \%will;
  153 
  154   $self->{pg} = $pg;
  155 }
  156 
  157 sub header {
  158   my $self = shift;
  159 
  160   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  161 }
  162 
  163 sub path {
  164   my $self = shift;
  165   my $args = $_[-1];
  166   my $setName = $self->{set}->id;
  167   my $problemNumber = $self->{problem}->id;
  168 
  169   my $ce = $self->{courseEnvironment};
  170   my $root = $ce->{webworkURLs}->{root};
  171   my $courseName = $ce->{courseName};
  172   return $self->pathMacro($args,
  173     "Home" => "$root",
  174     $courseName => "$root/$courseName",
  175     $setName => "$root/$courseName/$setName",
  176     "Problem $problemNumber" => "",
  177   );
  178 }
  179 
  180 sub siblings {
  181   my $self = shift;
  182   my $setName = $self->{set}->id;
  183   my $problemNumber = $self->{problem}->id;
  184 
  185   my $ce = $self->{courseEnvironment};
  186   my $root = $ce->{webworkURLs}->{root};
  187   my $courseName = $ce->{courseName};
  188 
  189   print CGI::strong("Problems"), CGI::br();
  190 
  191   my $wwdb = $self->{wwdb};
  192   my $user = $self->{r}->param("user");
  193   my @problems;
  194   push @problems, $wwdb->getProblem($user, $setName, $_)
  195     foreach ($wwdb->getProblems($user, $setName));
  196   foreach my $problem (sort { $a->id <=> $b->id } @problems) {
  197     print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?"
  198       . $self->url_authen_args}, "Problem ".$problem->id), CGI::br();
  199   }
  200 }
  201 
  202 sub nav {
  203   my $self = shift;
  204   my $args = $_[-1];
  205   my $setName = $self->{set}->id;
  206   my $problemNumber = $self->{problem}->id;
  207 
  208   my $ce = $self->{courseEnvironment};
  209   my $root = $ce->{webworkURLs}->{root};
  210   my $courseName = $ce->{courseName};
  211 
  212   my $wwdb = $self->{wwdb};
  213   my $user = $self->{r}->param("user");
  214 
  215   my @links = ("Problem List" => "$root/$courseName/$setName");
  216 
  217   my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1);
  218   my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1);
  219   unshift @links, "Previous Problem" => $prevProblem
  220     ? "$root/$courseName/$setName/".$prevProblem->id
  221     : "";
  222   push @links, "Next Problem" => $nextProblem
  223     ? "$root/$courseName/$setName/".$nextProblem->id
  224     : "";
  225 
  226   return $self->navMacro($args, @links);
  227 }
  228 
  229 sub title {
  230   my $self = shift;
  231   my $setName = $self->{set}->id;
  232   my $problemNumber = $self->{problem}->id;
  233 
  234   return "$setName : Problem $problemNumber";
  235 }
  236 
  237 sub body {
  238   my $self = shift;
  239 
  240   #$self->prepare(@_);
  241 
  242   # unpack some useful variables
  243   my $r               = $self->{r};
  244   my $wwdb            = $self->{wwdb};
  245   my $set             = $self->{set};
  246   my $problem         = $self->{problem};
  247   my $permissionLevel = $self->{permissionLevel};
  248   my $submitAnswers   = $self->{submitAnswers};
  249   my %will            = %{ $self->{will} };
  250   my $pg              = $self->{pg};
  251 
  252   ##### translation errors? #####
  253 
  254   if ($pg->{flags}->{error_flag}) {
  255     return translationError($pg->{errors}, $pg->{body_text});
  256   }
  257 
  258   ##### answer processing #####
  259 
  260   # if answers were submitted:
  261   if ($submitAnswers) {
  262     # store answers in DB for sticky answers
  263     my %answersToStore;
  264     my %answerHash = %{ $pg->{answers} };
  265     $answersToStore{$_} = $answerHash{$_}->{original_student_ans}
  266       foreach (keys %answerHash);
  267     my $answerString = encodeAnswers(%answersToStore,
  268       @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} });
  269     $problem->last_answer($answerString);
  270     $wwdb->setProblem($problem);
  271 
  272     # store state in DB if it makes sense
  273     if ($will{recordAnswers}) {
  274       $problem->attempted(1);
  275       $problem->status($pg->{state}->{recorded_score});
  276       $problem->num_correct($pg->{state}->{num_of_correct_ans});
  277       $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  278       $wwdb->setProblem($problem);
  279     }
  280   }
  281 
  282   ##### output #####
  283 
  284   # attempt summary
  285   if ($submitAnswers or $will{showCorrectAnswers}) {
  286     # print this if user submitted answers OR requested correct answers
  287     print attemptResults($pg, $submitAnswers, $will{showCorrectAnswers},
  288       $pg->{flags}->{showPartialCorrectAnswers});
  289   }
  290 
  291   # score summary
  292   my $attempts = $problem->num_correct + $problem->num_incorrect;
  293   my $attemptsNoun = $attempts != 1 ? "times" : "time";
  294   my $lastScore = int ($problem->status * 100) . "%";
  295   my ($attemptsLeft, $attemptsLeftNoun);
  296   if ($problem->max_attempts == -1) {
  297     # unlimited attempts
  298     $attemptsLeft = "unlimited";
  299     $attemptsLeftNoun = "attempts";
  300   } else {
  301     $attemptsLeft = $problem->max_attempts - $attempts;
  302     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
  303   }
  304   my $setClosedMessage;
  305   if (time < $set->open_date or time > $set->due_date) {
  306     $setClosedMessage = "This problem set is closed.";
  307     if ($permissionLevel > 0) {
  308       $setClosedMessage .= " Since you are a privileged user, additional attempts will be recorded.";
  309     } else {
  310       $setClosedMessage .= " Additional attempts will not be recorded.";
  311     }
  312   }
  313   print CGI::p(
  314     "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
  315     $problem->attempted
  316       ? "Your recorded score is $lastScore." . CGI::br()
  317       : "",
  318     "You have $attemptsLeft $attemptsLeftNoun remaining.", CGI::br(),
  319     $setClosedMessage,
  320   );
  321 
  322   # BY THE WAY..........
  323   # we have to figure out some way to tell the student if their NEW answer,
  324   # on THIS attempt, has been recorded. however, this is decided in part by
  325   # the grader, so is there any way for us to know? we can rule out several
  326   # cases where the answer is NOT being recorded, because of things decided
  327   # in &canRecordAnswers...
  328 
  329   print CGI::hr();
  330 
  331   # main form
  332   print
  333     CGI::startform("POST", $r->uri),
  334     $self->hidden_authen_fields,
  335     $self->viewOptions,
  336     CGI::p(CGI::i($pg->{result}->{msg})),
  337     CGI::p($pg->{body_text}),
  338     CGI::p(CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers")),
  339     CGI::endform();
  340 
  341   # debugging stuff
  342   #print
  343   # hr(),
  344   # h2("debugging information"),
  345   # h3("form fields"),
  346   # ref2string($formFields),
  347   # h3("user object"),
  348   # ref2string($user),
  349   # h3("set object"),
  350   # ref2string($set),
  351   # h3("problem object"),
  352   # ref2string($problem),
  353   # h3("PG object"),
  354   # ref2string($pg, {'WeBWorK::PG::Translator' => 1});
  355 
  356   return "";
  357 }
  358 
  359 ##### output utilities #####
  360 
  361 # this is used by ProblemSet.pm too, so don't fuck it up
  362 sub translationError($$) {
  363   my ($error, $details) = @_;
  364   return
  365     CGI::h2("Software Error"),
  366     CGI::p(<<EOF),
  367 WeBWorK has encountered a software error while attempting to process this problem.
  368 It is likely that there is an error in the problem itself.
  369 If you are a student, contact your professor to have the error corrected.
  370 If you are a professor, please consut the error output below for more informaiton.
  371 EOF
  372     CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
  373     CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
  374 }
  375 
  376 sub attemptResults($$$) {
  377   my $pg = shift;
  378   my $showAttemptAnswers = shift;
  379   my $showCorrectAnswers = shift;
  380   my $showAttemptResults = $showAttemptAnswers && shift;
  381   my $problemResult = $pg->{result}; # the overall result of the problem
  382   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  383 
  384   my $header = CGI::th("answer");
  385   $header .= $showAttemptAnswers ? CGI::th("attempt")  : "";
  386   $header .= $showCorrectAnswers ? CGI::th("correct")  : "";
  387   $header .= $showAttemptResults ? CGI::th("result")   : "";
  388   $header .= $showAttemptAnswers ? CGI::th("messages") : "";
  389   my @tableRows = ( $header );
  390   my $numCorrect;
  391   foreach my $name (@answerNames) {
  392     my $answerResult  = $pg->{answers}->{$name};
  393     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  394     my $correctAnswer = $answerResult->{correct_ans};
  395     my $answerScore   = $answerResult->{score};
  396     my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : "";
  397 
  398     $numCorrect += $answerScore > 0;
  399     my $resultString = $answerScore ? "correct" : "incorrect";
  400 
  401     # get rid of the goofy prefix on the answer names (supposedly, the format
  402     # of the answer names is changeable. this only fixes
  403     $name =~ s/^AnSwEr//;
  404 
  405     my $row = CGI::td($name);
  406     $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : "";
  407     $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : "";
  408     $row .= $showAttemptResults ? CGI::td($resultString)  : "";
  409     $row .= $answerMessage      ? CGI::td($answerMessage) : "";
  410     push @tableRows, $row;
  411   }
  412 
  413   my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions";
  414   my $scorePercent = int ($problemResult->{score} * 100) . "\%";
  415   my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of "
  416     . scalar @answerNames . " correct, for a score of $scorePercent.";
  417   return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary);
  418 }
  419 
  420 sub viewOptions($) {
  421   my $self = shift;
  422   my $displayMode = $self->{displayMode};
  423   my %must = %{ $self->{must} };
  424   my %can  = %{ $self->{can}  };
  425   my %will = %{ $self->{will} };
  426 
  427   my $optionLine;
  428   $can{showOldAnswers} and $optionLine .= join "",
  429     "Show: &nbsp;",
  430     CGI::checkbox(
  431       -name    => "showOldAnswers",
  432       -checked => $will{showOldAnswers},
  433       -label   => "Saved answers",
  434     ), "&nbsp;&nbsp;";
  435   $can{showCorrectAnswers} and $optionLine .= join "",
  436     CGI::checkbox(
  437       -name    => "showCorrectAnswers",
  438       -checked => $will{showCorrectAnswers},
  439       -label   => "Correct answers",
  440     ), "&nbsp;&nbsp;";
  441   $can{showHints} and $optionLine .= join "",
  442     CGI::checkbox(
  443       -name    => "showHints",
  444       -checked => $will{showHints},
  445       -label   => "Hints",
  446     ), "&nbsp;&nbsp;";
  447   $can{showSolutions} and $optionLine .= join "",
  448     CGI::checkbox(
  449       -name    => "showSolutions",
  450       -checked => $will{showSolutions},
  451       -label   => "Solutions",
  452     ), "&nbsp;&nbsp;";
  453   $optionLine and $optionLine .= join "", CGI::br();
  454 
  455   return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"},
  456       "View equations as: &nbsp;",
  457     CGI::radio_group(
  458       -name    => "displayMode",
  459       -values  => ['plainText', 'formattedText', 'images'],
  460       -default => $displayMode,
  461       -labels  => {
  462         plainText     => "plain text",
  463         formattedText => "formatted text",
  464         images        => "images",
  465       }
  466     ), CGI::br(),
  467     $optionLine,
  468     CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"),
  469   );
  470 }
  471 
  472 ##### permission queries #####
  473 
  474 # this stuff should be abstracted out into the permissions system
  475 # however, the permission system only knows about things in the
  476 # course environment and the username. hmmm...
  477 
  478 # also, i should fix these so that they have a consistent calling
  479 # format -- perhaps:
  480 #   canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
  481 
  482 sub canShowCorrectAnswers($$) {
  483   my ($permissionLevel, $answerDate) = @_;
  484   return $permissionLevel > 0 || time > $answerDate;
  485 }
  486 
  487 sub canShowSolutions($$) {
  488   my ($permissionLevel, $answerDate) = @_;
  489   return canShowCorrectAnswers($permissionLevel, $answerDate);
  490 }
  491 
  492 sub canRecordAnswers($$$$$) {
  493   my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
  494   my $permHigh = $permissionLevel > 0;
  495   my $timeOK = time >= $openDate && time <= $dueDate;
  496   my $attemptsOK = $attempts <= $maxAttempts;
  497   return $permHigh || ($timeOK && $attemptsOK);
  498 }
  499 
  500 sub mustRecordAnswers($) {
  501   my ($permissionLevel) = @_;
  502   return $permissionLevel == 0;
  503 }
  504 
  505 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9