[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 558 - (download) (as text) (annotate)
Fri Sep 20 22:47:22 2002 UTC (10 years, 8 months ago) by sh002i
File size: 16442 byte(s)
* fixed multiple-calls-to-&handler problem
* fixed if-else-endif code in &template
* added code to catch warnings in PG evaluation
* added "pink screen" and warning reporting
* started work on logging code (see Utils.pm, commented out)
-sam & dennis

    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 if_warnings($$) {
  158   my ($self, $arg) = @_;
  159   return $self->{pg}->{warnings} ne "";
  160 }
  161 
  162 sub if_errors($$) {
  163   my ($self, $arg) = @_;
  164   return $self->{pg}->{flags}->{error_flag};
  165 }
  166 
  167 sub header {
  168   my $self = shift;
  169 
  170   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  171 }
  172 
  173 sub path {
  174   my $self = shift;
  175   my $args = $_[-1];
  176   my $setName = $self->{set}->id;
  177   my $problemNumber = $self->{problem}->id;
  178 
  179   my $ce = $self->{courseEnvironment};
  180   my $root = $ce->{webworkURLs}->{root};
  181   my $courseName = $ce->{courseName};
  182   return $self->pathMacro($args,
  183     "Home" => "$root",
  184     $courseName => "$root/$courseName",
  185     $setName => "$root/$courseName/$setName",
  186     "Problem $problemNumber" => "",
  187   );
  188 }
  189 
  190 sub siblings {
  191   my $self = shift;
  192   my $setName = $self->{set}->id;
  193   my $problemNumber = $self->{problem}->id;
  194 
  195   my $ce = $self->{courseEnvironment};
  196   my $root = $ce->{webworkURLs}->{root};
  197   my $courseName = $ce->{courseName};
  198 
  199   print CGI::strong("Problems"), CGI::br();
  200 
  201   my $wwdb = $self->{wwdb};
  202   my $user = $self->{r}->param("user");
  203   my @problems;
  204   push @problems, $wwdb->getProblem($user, $setName, $_)
  205     foreach ($wwdb->getProblems($user, $setName));
  206   foreach my $problem (sort { $a->id <=> $b->id } @problems) {
  207     print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?"
  208       . $self->url_authen_args}, "Problem ".$problem->id), CGI::br();
  209   }
  210 }
  211 
  212 sub nav {
  213   my $self = shift;
  214   my $args = $_[-1];
  215   my $setName = $self->{set}->id;
  216   my $problemNumber = $self->{problem}->id;
  217 
  218   my $ce = $self->{courseEnvironment};
  219   my $root = $ce->{webworkURLs}->{root};
  220   my $courseName = $ce->{courseName};
  221 
  222   my $wwdb = $self->{wwdb};
  223   my $user = $self->{r}->param("user");
  224 
  225   my @links = ("Problem List" => "$root/$courseName/$setName");
  226 
  227   my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1);
  228   my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1);
  229   unshift @links, "Previous Problem" => $prevProblem
  230     ? "$root/$courseName/$setName/".$prevProblem->id
  231     : "";
  232   push @links, "Next Problem" => $nextProblem
  233     ? "$root/$courseName/$setName/".$nextProblem->id
  234     : "";
  235 
  236   return $self->navMacro($args, @links);
  237 }
  238 
  239 sub title {
  240   my $self = shift;
  241   my $setName = $self->{set}->id;
  242   my $problemNumber = $self->{problem}->id;
  243 
  244   return "$setName : Problem $problemNumber";
  245 }
  246 
  247 sub body {
  248   my $self = shift;
  249 
  250   #$self->prepare(@_);
  251 
  252   # unpack some useful variables
  253   my $r               = $self->{r};
  254   my $wwdb            = $self->{wwdb};
  255   my $set             = $self->{set};
  256   my $problem         = $self->{problem};
  257   my $permissionLevel = $self->{permissionLevel};
  258   my $submitAnswers   = $self->{submitAnswers};
  259   my %will            = %{ $self->{will} };
  260   my $pg              = $self->{pg};
  261 
  262   ##### translation errors? #####
  263 
  264   if ($pg->{flags}->{error_flag}) {
  265     return translationError($pg->{errors}, $pg->{body_text});
  266   }
  267 
  268   ##### answer processing #####
  269 
  270   # if answers were submitted:
  271   if ($submitAnswers) {
  272     # store answers in DB for sticky answers
  273     my %answersToStore;
  274     my %answerHash = %{ $pg->{answers} };
  275     $answersToStore{$_} = $answerHash{$_}->{original_student_ans}
  276       foreach (keys %answerHash);
  277     my $answerString = encodeAnswers(%answersToStore,
  278       @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} });
  279     $problem->last_answer($answerString);
  280     $wwdb->setProblem($problem);
  281 
  282     # store state in DB if it makes sense
  283     if ($will{recordAnswers}) {
  284       $problem->attempted(1);
  285       $problem->status($pg->{state}->{recorded_score});
  286       $problem->num_correct($pg->{state}->{num_of_correct_ans});
  287       $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  288       $wwdb->setProblem($problem);
  289     }
  290   }
  291 
  292   ##### output #####
  293 
  294   # attempt summary
  295   if ($submitAnswers or $will{showCorrectAnswers}) {
  296     # print this if user submitted answers OR requested correct answers
  297     print attemptResults($pg, $submitAnswers, $will{showCorrectAnswers},
  298       $pg->{flags}->{showPartialCorrectAnswers});
  299   }
  300 
  301   # score summary
  302   my $attempts = $problem->num_correct + $problem->num_incorrect;
  303   my $attemptsNoun = $attempts != 1 ? "times" : "time";
  304   my $lastScore = int ($problem->status * 100) . "%";
  305   my ($attemptsLeft, $attemptsLeftNoun);
  306   if ($problem->max_attempts == -1) {
  307     # unlimited attempts
  308     $attemptsLeft = "unlimited";
  309     $attemptsLeftNoun = "attempts";
  310   } else {
  311     $attemptsLeft = $problem->max_attempts - $attempts;
  312     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
  313   }
  314   my $setClosedMessage;
  315   if (time < $set->open_date or time > $set->due_date) {
  316     $setClosedMessage = "This problem set is closed.";
  317     if ($permissionLevel > 0) {
  318       $setClosedMessage .= " Since you are a privileged user, additional attempts will be recorded.";
  319     } else {
  320       $setClosedMessage .= " Additional attempts will not be recorded.";
  321     }
  322   }
  323   print CGI::p(
  324     "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
  325     $problem->attempted
  326       ? "Your recorded score is $lastScore." . CGI::br()
  327       : "",
  328     "You have $attemptsLeft $attemptsLeftNoun remaining.", CGI::br(),
  329     $setClosedMessage,
  330   );
  331 
  332   # BY THE WAY..........
  333   # we have to figure out some way to tell the student if their NEW answer,
  334   # on THIS attempt, has been recorded. however, this is decided in part by
  335   # the grader, so is there any way for us to know? we can rule out several
  336   # cases where the answer is NOT being recorded, because of things decided
  337   # in &canRecordAnswers...
  338 
  339   print CGI::hr();
  340 
  341   # main form
  342   print
  343     CGI::startform("POST", $r->uri),
  344     $self->hidden_authen_fields,
  345     $self->viewOptions,
  346     CGI::p(CGI::i($pg->{result}->{msg})),
  347     CGI::p($pg->{body_text}),
  348     CGI::p(CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers")),
  349     CGI::endform();
  350 
  351   # warning output
  352   if ($pg->{warnings} ne "") {
  353     print CGI::hr(), warningOutput($pg->{warnings});
  354   }
  355 
  356   # debugging stuff
  357   #print
  358   # hr(),
  359   # h2("debugging information"),
  360   # h3("form fields"),
  361   # ref2string($formFields),
  362   # h3("user object"),
  363   # ref2string($user),
  364   # h3("set object"),
  365   # ref2string($set),
  366   # h3("problem object"),
  367   # ref2string($problem),
  368   # h3("PG object"),
  369   # ref2string($pg, {'WeBWorK::PG::Translator' => 1});
  370 
  371   return "";
  372 }
  373 
  374 ##### output utilities #####
  375 
  376 # this is used by ProblemSet.pm too, so don't fuck it up
  377 sub translationError($$) {
  378   my ($error, $details) = @_;
  379   return
  380     CGI::h2("Software Error"),
  381     CGI::p(<<EOF),
  382 WeBWorK has encountered a software error while attempting to process this problem.
  383 It is likely that there is an error in the problem itself.
  384 If you are a student, contact your professor to have the error corrected.
  385 If you are a professor, please consut the error output below for more informaiton.
  386 EOF
  387     CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
  388     CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
  389 }
  390 
  391 # this is used by ProblemSet.pm too, so don't fuck it up
  392 sub warningOutput($) {
  393   my $warnings = shift;
  394 
  395   return
  396     CGI::h2("Software Warnings"),
  397     CGI::p(<<EOF),
  398 WeBWorK has encountered warnings while attempting to process this problem.
  399 It is likely that this indicates an error or ambiguity in the problem itself.
  400 If you are a student, contact your professor to have the problem corrected.
  401 If you are a professor, please consut the error output below for more informaiton.
  402 EOF
  403     CGI::h3("Warning messages"),
  404     CGI::blockquote(CGI::pre($warnings)),
  405   ;
  406 }
  407 
  408 sub attemptResults($$$) {
  409   my $pg = shift;
  410   my $showAttemptAnswers = shift;
  411   my $showCorrectAnswers = shift;
  412   my $showAttemptResults = $showAttemptAnswers && shift;
  413   my $problemResult = $pg->{result}; # the overall result of the problem
  414   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  415 
  416   my $header = CGI::th("answer");
  417   $header .= $showAttemptAnswers ? CGI::th("attempt")  : "";
  418   $header .= $showCorrectAnswers ? CGI::th("correct")  : "";
  419   $header .= $showAttemptResults ? CGI::th("result")   : "";
  420   $header .= $showAttemptAnswers ? CGI::th("messages") : "";
  421   my @tableRows = ( $header );
  422   my $numCorrect;
  423   foreach my $name (@answerNames) {
  424     my $answerResult  = $pg->{answers}->{$name};
  425     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  426     my $correctAnswer = $answerResult->{correct_ans};
  427     my $answerScore   = $answerResult->{score};
  428     my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : "";
  429 
  430     $numCorrect += $answerScore > 0;
  431     my $resultString = $answerScore ? "correct" : "incorrect";
  432 
  433     # get rid of the goofy prefix on the answer names (supposedly, the format
  434     # of the answer names is changeable. this only fixes
  435     $name =~ s/^AnSwEr//;
  436 
  437     my $row = CGI::td($name);
  438     $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : "";
  439     $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : "";
  440     $row .= $showAttemptResults ? CGI::td($resultString)  : "";
  441     $row .= $answerMessage      ? CGI::td($answerMessage) : "";
  442     push @tableRows, $row;
  443   }
  444 
  445   my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions";
  446   my $scorePercent = int ($problemResult->{score} * 100) . "\%";
  447   my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of "
  448     . scalar @answerNames . " correct, for a score of $scorePercent.";
  449   return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary);
  450 }
  451 
  452 sub viewOptions($) {
  453   my $self = shift;
  454   my $displayMode = $self->{displayMode};
  455   my %must = %{ $self->{must} };
  456   my %can  = %{ $self->{can}  };
  457   my %will = %{ $self->{will} };
  458 
  459   my $optionLine;
  460   $can{showOldAnswers} and $optionLine .= join "",
  461     "Show: &nbsp;",
  462     CGI::checkbox(
  463       -name    => "showOldAnswers",
  464       -checked => $will{showOldAnswers},
  465       -label   => "Saved answers",
  466     ), "&nbsp;&nbsp;";
  467   $can{showCorrectAnswers} and $optionLine .= join "",
  468     CGI::checkbox(
  469       -name    => "showCorrectAnswers",
  470       -checked => $will{showCorrectAnswers},
  471       -label   => "Correct answers",
  472     ), "&nbsp;&nbsp;";
  473   $can{showHints} and $optionLine .= join "",
  474     CGI::checkbox(
  475       -name    => "showHints",
  476       -checked => $will{showHints},
  477       -label   => "Hints",
  478     ), "&nbsp;&nbsp;";
  479   $can{showSolutions} and $optionLine .= join "",
  480     CGI::checkbox(
  481       -name    => "showSolutions",
  482       -checked => $will{showSolutions},
  483       -label   => "Solutions",
  484     ), "&nbsp;&nbsp;";
  485   $optionLine and $optionLine .= join "", CGI::br();
  486 
  487   return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"},
  488       "View equations as: &nbsp;",
  489     CGI::radio_group(
  490       -name    => "displayMode",
  491       -values  => ['plainText', 'formattedText', 'images'],
  492       -default => $displayMode,
  493       -labels  => {
  494         plainText     => "plain text",
  495         formattedText => "formatted text",
  496         images        => "images",
  497       }
  498     ), CGI::br(),
  499     $optionLine,
  500     CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"),
  501   );
  502 }
  503 
  504 ##### permission queries #####
  505 
  506 # this stuff should be abstracted out into the permissions system
  507 # however, the permission system only knows about things in the
  508 # course environment and the username. hmmm...
  509 
  510 # also, i should fix these so that they have a consistent calling
  511 # format -- perhaps:
  512 #   canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
  513 
  514 sub canShowCorrectAnswers($$) {
  515   my ($permissionLevel, $answerDate) = @_;
  516   return $permissionLevel > 0 || time > $answerDate;
  517 }
  518 
  519 sub canShowSolutions($$) {
  520   my ($permissionLevel, $answerDate) = @_;
  521   return canShowCorrectAnswers($permissionLevel, $answerDate);
  522 }
  523 
  524 sub canRecordAnswers($$$$$) {
  525   my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
  526   my $permHigh = $permissionLevel > 0;
  527   my $timeOK = time >= $openDate && time <= $dueDate;
  528   my $attemptsOK = $attempts <= $maxAttempts;
  529   return $permHigh || ($timeOK && $attemptsOK);
  530 }
  531 
  532 sub mustRecordAnswers($) {
  533   my ($permissionLevel) = @_;
  534   return $permissionLevel == 0;
  535 }
  536 
  537 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9