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

View of /branches/gage_dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 476 - (download) (as text) (annotate)
Tue Aug 20 01:07:18 2002 UTC (10 years, 10 months ago) by sh002i
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm
File size: 15440 byte(s)
fixed problem with deciding when to generate images in math2img mode
finished adding template escapes to ProblemSets, ProblemSet, and Problem

fixed a problem where modules were removed from the courseEnv while
being loaded (whups.)
-sam

    1 ################################################################################
    2 # WeBWorK mod_perl (c) 1995-2002 WeBWorK Team, Univeristy of Rochester
    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 # TODO:
   23 # 7. make warnings work
   24 
   25 ############################################################
   26 #
   27 # user
   28 # key
   29 #
   30 # displayMode
   31 # showOldAnswers
   32 # showCorrectAnswers
   33 # showHints
   34 # showSolutions
   35 #
   36 # AnSwEr# - answer blanks in problem
   37 #
   38 # redisplay - name of the "Redisplay Problem" button
   39 # submitAnswers - name of "Submit Answers" button
   40 #
   41 ############################################################
   42 
   43 sub pre_header_initialize {
   44   my ($self, $setName, $problemNumber) = @_;
   45   my $courseEnv = $self->{courseEnvironment};
   46   my $r = $self->{r};
   47   my $userName = $r->param('user');
   48 
   49   # fix format of setName and problem
   50   $setName =~ s/^set//;
   51   $problemNumber =~ s/^prob//;
   52 
   53   ##### database setup #####
   54 
   55   my $cldb   = WeBWorK::DB::Classlist->new($courseEnv);
   56   my $wwdb   = WeBWorK::DB::WW->new($courseEnv);
   57   my $authdb = WeBWorK::DB::Auth->new($courseEnv);
   58 
   59   my $user            = $cldb->getUser($userName);
   60   my $set             = $wwdb->getSet($userName, $setName);
   61   my $problem         = $wwdb->getProblem($userName, $setName, $problemNumber);
   62   my $permissionLevel = $authdb->getPermissions($userName);
   63 
   64   ##### form processing #####
   65 
   66   # set options from form fields (see comment at top of file for names)
   67   my $displayMode        = $r->param("displayMode")        || $courseEnv->{pg}->{options}->{displayMode};
   68   my $redisplay          = $r->param("redisplay");
   69   my $submitAnswers      = $r->param("submitAnswers");
   70 
   71   # coerce form fields into CGI::Vars format
   72   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
   73 
   74   ##### permissions #####
   75 
   76   # what does the user want to do?
   77   my %want = (
   78     showOldAnswers     => $r->param("showOldAnswers")     || $courseEnv->{pg}->{options}->{showOldAnswers},
   79     showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers},
   80     showHints          => $r->param("showHints")          || $courseEnv->{pg}->{options}->{showHints},
   81     showSolutions      => $r->param("showSolutions")      || $courseEnv->{pg}->{options}->{showSolutions},
   82     recordAnswers      => $r->param("recordAnswers")      || 1,
   83   );
   84 
   85   # are certain options enforced?
   86   my %must = (
   87     showOldAnswers     => 0,
   88     showCorrectAnswers => 0,
   89     showHints          => 0,
   90     showSolutions      => 0,
   91     recordAnswers      => mustRecordAnswers($permissionLevel),
   92   );
   93 
   94   # does the user have permission to use certain options?
   95   my %can = (
   96     showOldAnswers     => 1,
   97     showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
   98     showHints          => 1,
   99     showSolutions      => canShowSolutions($permissionLevel, $set->answer_date),
  100     recordAnswers      => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
  101       $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
  102       # num_correct+num_incorrect+1 -- as this happens before updating $problem
  103   );
  104 
  105   # final values for options
  106   my %will;
  107   foreach(keys %must) {
  108     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  109   }
  110 
  111   ##### sticky answers #####
  112 
  113   if (not $submitAnswers and $will{showOldAnswers}) {
  114     # do this only if new answers are NOT being submitted
  115     my %oldAnswers = decodeAnswers($problem->last_answer);
  116     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  117   }
  118 
  119   ##### translation #####
  120 
  121   my $pg = WeBWorK::PG->new(
  122     $courseEnv,
  123     $r->param('user'),
  124     $r->param('key'),
  125     $setName,
  126     $problemNumber,
  127     { # translation options
  128       displayMode     => $displayMode,
  129       showHints       => $will{showHints},
  130       showSolutions   => $will{showSolutions},
  131       refreshMath2img => $will{showHints} || $will{showSolutions},
  132       # try leaving processAnswers on all the time?
  133       processAnswers  => 1, #$submitAnswers ? 1 : 0,
  134     },
  135     $formFields
  136   );
  137 
  138   ##### store fields #####
  139 
  140   $self->{cldb}            = $cldb;
  141   $self->{wwdb}            = $wwdb;
  142   $self->{authdb}          = $authdb;
  143 
  144   $self->{user}            = $user;
  145   $self->{set}             = $set;
  146   $self->{problem}         = $problem;
  147   $self->{permissionLevel} = $permissionLevel;
  148 
  149   $self->{displayMode}   = $displayMode;
  150   $self->{redisplay}     = $redisplay;
  151   $self->{submitAnswers} = $submitAnswers;
  152   $self->{formFields}    = $formFields;
  153 
  154   $self->{want} = \%want;
  155   $self->{must} = \%must;
  156   $self->{can}  = \%can;
  157   $self->{will} = \%will;
  158 
  159   $self->{pg} = $pg;
  160 }
  161 
  162 #sub header {
  163 # # *** we need to print $pg->{header_text} here!
  164 #}
  165 
  166 sub path {
  167   my $self = shift;
  168   my $args = $_[-1];
  169   my $setName = $self->{set}->id;
  170   my $problemNumber = $self->{problem}->id;
  171 
  172   my $ce = $self->{courseEnvironment};
  173   my $root = $ce->{webworkURLs}->{root};
  174   my $courseName = $ce->{courseName};
  175   return $self->pathMacro($args,
  176     "Home" => "$root",
  177     $courseName => "$root/$courseName",
  178     $setName => "$root/$courseName/set$setName",
  179     "Problem $problemNumber" => "",
  180   );
  181 }
  182 
  183 sub siblings {
  184   my $self = shift;
  185   my $setName = $self->{set}->id;
  186   my $problemNumber = $self->{problem}->id;
  187 
  188   my $ce = $self->{courseEnvironment};
  189   my $root = $ce->{webworkURLs}->{root};
  190   my $courseName = $ce->{courseName};
  191 
  192   my $wwdb = $self->{wwdb};
  193   my $user = $self->{r}->param("user");
  194   my @problems;
  195   push @problems, $wwdb->getProblem($user, $setName, $_)
  196     foreach ($wwdb->getProblems($user, $setName));
  197   foreach my $problem (sort { $a->id <=> $b->id } @problems) {
  198     print CGI::a({-href=>"$root/$courseName/$setName/".$problem->id."/?"
  199       . $self->url_authen_args}, "Problem ".$problem->id), CGI::br();
  200   }
  201 }
  202 
  203 sub nav {
  204   my $self = shift;
  205   my $args = $_[-1];
  206   my $setName = $self->{set}->id;
  207   my $problemNumber = $self->{problem}->id;
  208 
  209   my $ce = $self->{courseEnvironment};
  210   my $root = $ce->{webworkURLs}->{root};
  211   my $courseName = $ce->{courseName};
  212 
  213   my $wwdb = $self->{wwdb};
  214   my $user = $self->{r}->param("user");
  215 
  216   my @links = ("Problem List" => "$root/$courseName/set$setName");
  217 
  218   my $prevProblem = $wwdb->getProblem($user, $setName, $problemNumber-1);
  219   my $nextProblem = $wwdb->getProblem($user, $setName, $problemNumber+1);
  220   unshift @links, "Previous Problem" => "$root/$courseName/set$setName/prob".$prevProblem->id
  221     if $prevProblem;
  222   push @links, "Next Problem" => "$root/$courseName/set$setName/prob".$nextProblem->id
  223     if $nextProblem;
  224 
  225   return $self->navMacro($args, @links);
  226 }
  227 
  228 sub title {
  229   my $self = shift;
  230   my $setName = $self->{set}->id;
  231   my $problemNumber = $self->{problem}->id;
  232 
  233   return "$setName : Problem $problemNumber";
  234 }
  235 
  236 sub body {
  237   my $self = shift;
  238 
  239   #$self->prepare(@_);
  240 
  241   # unpack some useful variables
  242   my $r               = $self->{r};
  243   my $wwdb            = $self->{wwdb};
  244   my $set             = $self->{set};
  245   my $problem         = $self->{problem};
  246   my $permissionLevel = $self->{permissionLevel};
  247   my $submitAnswers   = $self->{submitAnswers};
  248   my %will            = %{ $self->{will} };
  249   my $pg              = $self->{pg};
  250 
  251   ##### translation errors? #####
  252 
  253   if ($pg->{flags}->{error_flag}) {
  254     print translationError($pg->{errors}, $pg->{body_text});
  255     return "";
  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     CGI::p(CGI::i($pg->{result}->{msg})),
  336     CGI::p($pg->{body_text}),
  337     CGI::p(CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers")),
  338     $self->viewOptions,
  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 sub translationError($$) {
  362   my ($error, $details) = @_;
  363   return
  364     CGI::h2("Software Error"),
  365     CGI::p(<<EOF),
  366 WeBWorK has encountered a software error while attempting to process this problem.
  367 It is likely that there is an error in the problem itself.
  368 If you are a student, contact your professor to have the error corrected.
  369 If you are a professor, please consut the error output below for more informaiton.
  370 EOF
  371     CGI::h3("Error messages"), CGI::blockquote(CGI::pre($error)),
  372     CGI::h3("Error context"), CGI::blockquote(CGI::pre($details));
  373 }
  374 
  375 sub attemptResults($$$) {
  376   my $pg = shift;
  377   my $showAttemptAnswers = shift;
  378   my $showCorrectAnswers = shift;
  379   my $showAttemptResults = $showAttemptAnswers && shift;
  380   my $problemResult = $pg->{result}; # the overall result of the problem
  381   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  382 
  383   my $header = CGI::th("answer");
  384   $header .= $showAttemptAnswers ? CGI::th("attempt")  : "";
  385   $header .= $showCorrectAnswers ? CGI::th("correct")  : "";
  386   $header .= $showAttemptResults ? CGI::th("result")   : "";
  387   $header .= $showAttemptAnswers ? CGI::th("messages") : "";
  388   my @tableRows = ( $header );
  389   my $numCorrect;
  390   foreach my $name (@answerNames) {
  391     my $answerResult  = $pg->{answers}->{$name};
  392     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  393     my $correctAnswer = $answerResult->{correct_ans};
  394     my $answerScore   = $answerResult->{score};
  395     my $answerMessage = $showAttemptAnswers ? $answerResult->{ans_message} : "";
  396 
  397     $numCorrect += $answerScore > 0;
  398     my $resultString = $answerScore ? "correct :^)" : "incorrect >:(";
  399 
  400     my $row = CGI::td($name);
  401     $row .= $showAttemptAnswers ? CGI::td($studentAnswer) : "";
  402     $row .= $showCorrectAnswers ? CGI::td($correctAnswer) : "";
  403     $row .= $showAttemptResults ? CGI::td($resultString)  : "";
  404     $row .= $answerMessage      ? CGI::td($answerMessage) : "";
  405     push @tableRows, $row;
  406   }
  407 
  408   my $numCorrectNoun = $numCorrect == 1 ? "question" : "questions";
  409   my $scorePercent = int ($problemResult->{score} * 100) . "\%";
  410   my $summary = "On this attempt, you answered $numCorrect $numCorrectNoun out of "
  411     . scalar @answerNames . " correct, for a score of $scorePercent.";
  412   return CGI::table({-border=>1}, CGI::Tr(\@tableRows)) . CGI::p($summary);
  413 }
  414 
  415 sub viewOptions($) {
  416   my $self = shift;
  417   my $displayMode = $self->{displayMode};
  418   my %must = %{ $self->{must} };
  419   my %can  = %{ $self->{can}  };
  420   my %will = %{ $self->{will} };
  421 
  422   my $optionLine;
  423   $can{showOldAnswers} and $optionLine .= join "",
  424     "Show: &nbsp;",
  425     CGI::checkbox(
  426       -name    => "showOldAnswers",
  427       -checked => $will{showOldAnswers},
  428       -label   => "Saved answers",
  429     ), "&nbsp;&nbsp;";
  430   $can{showCorrectAnswers} and $optionLine .= join "",
  431     CGI::checkbox(
  432       -name    => "showCorrectAnswers",
  433       -checked => $will{showCorrectAnswers},
  434       -label   => "Correct answers",
  435     ), "&nbsp;&nbsp;";
  436   $can{showHints} and $optionLine .= join "",
  437     CGI::checkbox(
  438       -name    => "showHints",
  439       -checked => $will{showHints},
  440       -label   => "Hints",
  441     ), "&nbsp;&nbsp;";
  442   $can{showSolutions} and $optionLine .= join "",
  443     CGI::checkbox(
  444       -name    => "showSolutions",
  445       -checked => $will{showSolutions},
  446       -label   => "Solutions",
  447     ), "&nbsp;&nbsp;";
  448   $optionLine and $optionLine .= join "", CGI::br();
  449 
  450   return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex"},
  451       "View equations as: &nbsp;",
  452     CGI::radio_group(
  453       -name    => "displayMode",
  454       -values  => ['plainText', 'formattedText', 'images'],
  455       -default => $displayMode,
  456       -labels  => {
  457         plainText     => "plain text",
  458         formattedText => "formatted text",
  459         images        => "images",
  460       }
  461     ), CGI::br(),
  462     $optionLine,
  463     CGI::submit(-name=>"redisplay", -label=>"Redisplay Problem"),
  464   );
  465 }
  466 
  467 ##### permission queries #####
  468 
  469 # this stuff should be abstracted out into the permissions system
  470 # however, the permission system only knows about things in the
  471 # course environment and the username. hmmm...
  472 
  473 # also, i should fix these so that they have a consistent calling
  474 # format -- perhaps:
  475 #   canPERM($courseEnv, $user, $set, $problem, $permissionLevel)
  476 
  477 sub canShowCorrectAnswers($$) {
  478   my ($permissionLevel, $answerDate) = @_;
  479   return $permissionLevel > 0 || time > $answerDate;
  480 }
  481 
  482 sub canShowSolutions($$) {
  483   my ($permissionLevel, $answerDate) = @_;
  484   return canShowCorrectAnswers($permissionLevel, $answerDate);
  485 }
  486 
  487 sub canRecordAnswers($$$$$) {
  488   my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
  489   my $permHigh = $permissionLevel > 0;
  490   my $timeOK = time >= $openDate && time <= $dueDate;
  491   my $attemptsOK = $attempts <= $maxAttempts;
  492   return $permHigh || ($timeOK && $attemptsOK);
  493 }
  494 
  495 sub mustRecordAnswers($) {
  496   my ($permissionLevel) = @_;
  497   return $permissionLevel == 0;
  498 }
  499 
  500 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9