[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 562 - (download) (as text) (annotate)
Fri Sep 27 23:53:42 2002 UTC (10 years, 7 months ago) by sh002i
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm
File size: 16891 byte(s)
- created macros/IO.pl, which is loaded with no opmask by PG.pm. It is a copy
  of WeBWorK::PG::IO.pm, with some changes to make it work as a macro package.
  The translator no longer shares IO.pm's functions with the safe compartment.
  This is a BAD THING, and should be reconsidered when the Translator is
  revised.
- Changed many (but not all) checks for HTML or HTML_tth modes to match /^HTML/
  in the macros.
- changed &header to &head in Problem.pm
- Added problem environment variables for gif2eps and png2eps and modified
  &dangerousMacros::alias to use them
- fixed MOST of the harmless warnings in the system. there's still the "Use
  of uninitialized value in null operation" warning in template(), tho.

Still to come:

- make images in PDFs work
- fix TTH mode character encodings on mac (maybe)
- have logout button invalidate key
- Pretty die messages (from outside of the translator)
- Feedback - need nice modular way of sending email
- Options - email address and password

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9