[system] / trunk / webwork-modperl / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

View of /trunk/webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9