[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 2440 - (download) (as text) (annotate)
Sat Jul 3 17:29:32 2004 UTC (8 years, 10 months ago) by sh002i
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm
File size: 39497 byte(s)
get dvipng settings from new place in CE

    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.150 2004/07/02 20:39:12 dpvc Exp $
    5 #
    6 # This program is free software; you can redistribute it and/or modify it under
    7 # the terms of either: (a) the GNU General Public License as published by the
    8 # Free Software Foundation; either version 2, or (at your option) any later
    9 # version, or (b) the "Artistic License" which comes with this package.
   10 #
   11 # This program is distributed in the hope that it will be useful, but WITHOUT
   12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
   13 # FOR A PARTICULAR PURPOSE.  See either the GNU General Public License or the
   14 # Artistic License for more details.
   15 ################################################################################
   16 
   17 package WeBWorK::ContentGenerator::Problem;
   18 use base qw(WeBWorK::ContentGenerator);
   19 
   20 =head1 NAME
   21 
   22 WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
   23 
   24 =cut
   25 
   26 use strict;
   27 use warnings;
   28 use CGI qw();
   29 use File::Path qw(rmtree);
   30 use WeBWorK::Form;
   31 use WeBWorK::PG;
   32 use WeBWorK::PG::ImageGenerator;
   33 use WeBWorK::PG::IO;
   34 use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory);
   35 use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
   36 use WeBWorK::Timing;
   37 
   38 use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
   39 
   40 ############################################################
   41 #
   42 # user
   43 # effectiveUser
   44 # key
   45 #
   46 # editMode
   47 # sourceFilePath - path to file to be editted
   48 # problemSeed - problem seed for editted problem
   49 #
   50 # displayMode - type of display (ie formatted, images, asciimath, etc)
   51 #
   52 # showOldAnswers
   53 # showCorrectAnswers
   54 # showHints
   55 # showSolutions
   56 #
   57 # AnSwEr# - answer blanks in problem
   58 #
   59 # redisplay - name of the "Redisplay Problem" button
   60 # submitAnswers - name of "Submit Answers" button
   61 # checkAnswers - name of the "Check Answers" button
   62 # previewAnswers - name of the "Preview Answers" button
   63 #
   64 # success - success message (from PGProblemEditor)
   65 # failure - failure message (from PGProblemEditor)
   66 #
   67 ############################################################
   68 
   69 
   70 sub pre_header_initialize {
   71   my ($self) = @_;
   72   my $r = $self->r;
   73   my $ce = $r->ce;
   74   my $db = $r->db;
   75   my $authz = $r->authz;
   76   my $urlpath = $r->urlpath;
   77 
   78   my $setName = $urlpath->arg("setID");
   79   my $problemNumber = $r->urlpath->arg("problemID");
   80   my $userName = $r->param('user');
   81   my $effectiveUserName = $r->param('effectiveUser');
   82   my $key = $r->param('key');
   83 
   84   my $user = $db->getUser($userName); # checked
   85   die "record for user $userName (real user) does not exist."
   86     unless defined $user;
   87 
   88   my $effectiveUser = $db->getUser($effectiveUserName); # checked
   89   die "record for user $effectiveUserName (effective user) does not exist."
   90     unless defined $effectiveUser;
   91 
   92   my $PermissionLevel = $db->getPermissionLevel($userName); # checked
   93   die "permission level record for user $userName does not exist (but the user does? odd...)"
   94     unless defined $PermissionLevel;
   95   my $permissionLevel = $PermissionLevel->permission;
   96 
   97   # obtain the merged set for $effectiveUser
   98   my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
   99 
  100   # obtain the merged problem for $effectiveUser
  101   my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
  102 
  103   my $editMode = $r->param("editMode");
  104 
  105   if ($authz->hasPermissions($userName, "modify_problem_sets")) {
  106     # professors are allowed to fabricate sets and problems not
  107     # assigned to them (or anyone). this allows them to use the
  108     # editor to
  109 
  110     # if that is not yet defined obtain the global set, convert
  111     # it to a user set, and add fake user data
  112     unless (defined $set) {
  113       my $userSetClass = $db->{set_user}->{record};
  114       my $globalSet = $db->getGlobalSet($setName); # checked
  115       # if the global set doesn't exist either, bail!
  116       if(not defined $globalSet) {
  117         $set = fake_set($db);
  118       } else {
  119         $set = global2user($userSetClass, $globalSet);
  120         $set->psvn(0);
  121 
  122         # FIXME: This is a temporary fix to fill in the database
  123         #  We want the published field to contain either 1 or 0 so if it has not been set to 0, default to 1
  124         # this will fill in all the empty fields but not change anything that has been specifically set to 1 or 0
  125         $globalSet->published("1") unless $globalSet->published eq "0";
  126         $db->putGlobalSet($globalSet);
  127       }
  128     }
  129 
  130     # if that is not yet defined obtain the global problem,
  131     # convert it to a user problem, and add fake user data
  132     unless (defined $problem) {
  133       my $userProblemClass = $db->{problem_user}->{record};
  134       my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
  135       # if the global problem doesn't exist either, bail!
  136       if(not defined $globalProblem) {
  137         my $sourceFilePath = $r->param("sourceFilePath");
  138         # These are problems from setmaker.  If declared invalid, they won't come up
  139         $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
  140 #       die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
  141         $problem = fake_problem($db);
  142         $problem->problem_id(1);
  143         $problem->source_file($sourceFilePath);
  144         $problem->user_id($effectiveUserName);
  145       } else {
  146         $problem = global2user($userProblemClass, $globalProblem);
  147         $problem->user_id($effectiveUserName);
  148         $problem->problem_seed(0);
  149         $problem->status(0);
  150         $problem->attempted(0);
  151         $problem->last_answer("");
  152         $problem->num_correct(0);
  153         $problem->num_incorrect(0);
  154       }
  155     }
  156 
  157     # now we're sure we have valid UserSet and UserProblem objects
  158     # yay!
  159 
  160     # now deal with possible editor overrides:
  161 
  162     # if the caller is asking to override the source file, and
  163     # editMode calls for a temporary file, do so
  164     my $sourceFilePath = $r->param("sourceFilePath");
  165     if (defined $sourceFilePath and
  166         (not defined $editMode or $editMode eq "temporaryFile")) {
  167       $problem->source_file($sourceFilePath);
  168     }
  169 
  170     # if the problem does not have a source file or no source file has been passed in
  171     # then this is really an invalid problem (probably from a bad URL)
  172     $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file);
  173 
  174     # if the caller is asking to override the problem seed, do so
  175     my $problemSeed = $r->param("problemSeed");
  176     if (defined $problemSeed) {
  177       $problem->problem_seed($problemSeed);
  178     }
  179 
  180     my $publishedClass = ($set->published) ? "Published" : "Unpublished";
  181     my $publishedText = ($set->published) ? "visible to students." : "hidden from students.";
  182     $self->addmessage(CGI::p("This set is " . CGI::font({class=>$publishedClass}, $publishedText)));
  183   } else {
  184 
  185     # students can't view problems not assigned to them
  186 
  187     # A set is valid if it exists and if it is either published or the user is privileged.
  188     $self->{invalidSet} = ((grep /^$setName/, $db->listUserSets($effectiveUserName)) == 0)
  189           || not defined $set
  190           || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"));
  191     $self->{invalidProblem} = ((grep /^$problemNumber/, $db->listUserProblems($effectiveUserName, $setName)) == 0)
  192           || not defined $problem
  193           || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"));
  194 
  195     $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem};
  196   }
  197 
  198   $self->{userName}          = $userName;
  199   $self->{effectiveUserName} = $effectiveUserName;
  200   $self->{user}              = $user;
  201   $self->{effectiveUser}     = $effectiveUser;
  202   $self->{permissionLevel}   = $permissionLevel;
  203   $self->{set}               = $set;
  204   $self->{problem}           = $problem;
  205   $self->{editMode}          = $editMode;
  206 
  207   ##### form processing #####
  208 
  209   # set options from form fields (see comment at top of file for names)
  210   my $displayMode        = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
  211   my $redisplay          = $r->param("redisplay");
  212   my $submitAnswers      = $r->param("submitAnswers");
  213   my $checkAnswers       = $r->param("checkAnswers");
  214   my $previewAnswers     = $r->param("previewAnswers");
  215 
  216   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
  217 
  218   $self->{displayMode}    = $displayMode;
  219   $self->{redisplay}      = $redisplay;
  220   $self->{submitAnswers}  = $submitAnswers;
  221   $self->{checkAnswers}   = $checkAnswers;
  222   $self->{previewAnswers} = $previewAnswers;
  223   $self->{formFields}     = $formFields;
  224 
  225   # get result and send to message
  226   my $success        = $r->param("sucess");
  227   my $failure        = $r->param("failure");
  228   $self->addbadmessage(CGI::p($failure)) if $failure;
  229   $self->addgoodmessage(CGI::p($success)) if $success;
  230 
  231   # now that we've set all the necessary variables quit out if the set or problem is invalid
  232   return if $self->{invalidSet} || $self->{invalidProblem};
  233 
  234   ##### permissions #####
  235 
  236   # are we allowed to view this problem?
  237   $self->{isOpen} = time >= $set->open_date || $authz->hasPermissions($user, "view_unopened_sets");
  238   return unless $self->{isOpen};
  239 
  240   # what does the user want to do?
  241   my %want = (
  242     showOldAnswers     => $r->param("showOldAnswers")     || $ce->{pg}->{options}->{showOldAnswers},
  243     showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
  244     showHints          => $r->param("showHints")          || $ce->{pg}->{options}->{showHints},
  245     showSolutions      => $r->param("showSolutions")      || $ce->{pg}->{options}->{showSolutions},
  246     recordAnswers      => $submitAnswers,
  247     checkAnswers       => $checkAnswers,
  248   );
  249 
  250   # are certain options enforced?
  251   my %must = (
  252     showOldAnswers     => 0,
  253     showCorrectAnswers => 0,
  254     showHints          => 0,
  255     showSolutions      => 0,
  256     recordAnswers      => mustRecordAnswers($permissionLevel),
  257     checkAnswers       => 0,
  258   );
  259 
  260   # does the user have permission to use certain options?
  261   my %can = (
  262     showOldAnswers     => 1,
  263     showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date),
  264     showHints          => 1,
  265     showSolutions      => canShowSolutions($permissionLevel, $set->answer_date),
  266     recordAnswers      => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date,
  267       $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1),
  268       # attempts=num_correct+num_incorrect+1, as this happens before updating $problem
  269     checkAnswers       => canCheckAnswers($permissionLevel, $set->due_date),
  270   );
  271 
  272   # more complicated logic for showing check answer button:
  273   # checkAnswers button shows up after due date -- once a student can't record anymore
  274   # checkAnswers button always shows up when an instructor or TA is acting
  275   # as someone else (the $user and $effectiveUserName aren't the same).
  276   $can{checkAnswers} = (
  277     # $can{recordAnswers} will be false if the due date has passed OR the
  278     # student has used up all of her attempts
  279     ($can{checkAnswers} and not $can{recordAnswers})
  280       or
  281     (
  282       # FIXME: this is not the right way to check for this.
  283       # also, canCheckAnswers() will show this button if the permission
  284       # level is positive,  which is always true when an instructor is
  285       # acting as a student
  286       defined($userName)
  287         and
  288       defined($effectiveUserName)
  289         and
  290       ($userName ne $effectiveUserName)
  291     )
  292   );
  293 
  294   # more complicated logic for showing "submit answer" button:
  295   # We hide the submit answer button if someone is acting as a student
  296   # This prevents errors where you accidently submit the answer for a student
  297   # Not sure whether this a feature or a bug
  298   $can{recordAnswers} = (
  299     $can{recordAnswers}
  300       and not
  301     (
  302       # FIXME: this is not the right way to check for this.
  303       defined($userName)
  304         and
  305       defined($effectiveUserName)
  306         and
  307       ($userName ne $effectiveUserName)
  308     )
  309   );
  310 
  311   # final values for options
  312   my %will;
  313   foreach (keys %must) {
  314     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  315   }
  316 
  317   ##### sticky answers #####
  318 
  319   if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
  320     # do this only if new answers are NOT being submitted
  321     my %oldAnswers = decodeAnswers($problem->last_answer);
  322     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  323   }
  324 
  325   ##### translation #####
  326 
  327   $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer);
  328   my $pg = WeBWorK::PG->new(
  329     $ce,
  330     $effectiveUser,
  331     $key,
  332     $set,
  333     $problem,
  334     $set->psvn, # FIXME: this field should be removed
  335     $formFields,
  336     { # translation options
  337       displayMode     => $displayMode,
  338       showHints       => $will{showHints},
  339       showSolutions   => $will{showSolutions},
  340       refreshMath2img => $will{showHints} || $will{showSolutions},
  341       processAnswers  => 1,
  342     },
  343   );
  344 
  345   $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer);
  346   ##### fix hint/solution options #####
  347 
  348   $can{showHints}     &&= $pg->{flags}->{hintExists}
  349                       &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
  350   $can{showSolutions} &&= $pg->{flags}->{solutionExists};
  351 
  352   ##### store fields #####
  353 
  354   $self->{want} = \%want;
  355   $self->{must} = \%must;
  356   $self->{can}  = \%can;
  357   $self->{will} = \%will;
  358   $self->{pg} = $pg;
  359 }
  360 
  361 sub if_errors($$) {
  362   my ($self, $arg) = @_;
  363 
  364   if ($self->{isOpen}) {
  365     return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
  366   } else {
  367     return !$arg;
  368   }
  369 }
  370 
  371 sub head {
  372   my ($self) = @_;
  373 
  374   return "" unless $self->{isOpen};
  375   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  376 }
  377 
  378 sub options {
  379   my ($self) = @_;
  380 
  381   return "" if $self->{invalidProblem};
  382   my $sourceFilePathfield = '';
  383         if($self->r->param("sourceFilePath")) {
  384     $sourceFilePathfield = CGI::hidden(-name => "sourceFilePath",
  385                                                    -value => $self->r->param("sourceFilePath"));
  386   }
  387 
  388   return join("",
  389     CGI::start_form("POST", $self->{r}->uri),
  390     $self->hidden_authen_fields,
  391     $sourceFilePathfield,
  392     CGI::hr(),
  393     CGI::start_div({class=>"viewOptions"}),
  394     $self->viewOptions(),
  395     CGI::end_div(),
  396     CGI::end_form()
  397   );
  398 }
  399 
  400 sub siblings {
  401   my ($self) = @_;
  402   my $r = $self->r;
  403   my $db = $r->db;
  404   my $urlpath = $r->urlpath;
  405 
  406   # can't show sibling problems if the set is invalid
  407   return "" if $self->{invalidSet};
  408 
  409   my $courseID = $urlpath->arg("courseID");
  410   my $setID = $self->{set}->set_id;
  411   my $eUserID = $r->param("effectiveUser");
  412   my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
  413 
  414   print CGI::start_ul({class=>"LinksMenu"});
  415   print CGI::start_li();
  416   print CGI::span({style=>"font-size:larger"}, "Problems");
  417   print CGI::start_ul();
  418 
  419   foreach my $problemID (@problemIDs) {
  420     my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
  421       courseID => $courseID, setID => $setID, problemID => $problemID);
  422     print CGI::li(CGI::a({href=>$self->systemLink($problemPage, params=>{displayMode => $self->{displayMode}})}, "Problem $problemID"));
  423   }
  424 
  425   print CGI::end_ul();
  426   print CGI::end_li();
  427   print CGI::end_ul();
  428 
  429   return "";
  430 }
  431 
  432 sub nav {
  433   my ($self, $args) = @_;
  434   my $r = $self->r;
  435   my $db = $r->db;
  436   my $urlpath = $r->urlpath;
  437 
  438   my $courseID = $urlpath->arg("courseID");
  439   my $setID = $self->{set}->set_id if !($self->{invalidSet});
  440   my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
  441   my $eUserID = $r->param("effectiveUser");
  442 
  443   my ($prevID, $nextID);
  444 
  445   if (!$self->{invalidProblem}) {
  446     my @problemIDs = $db->listUserProblems($eUserID, $setID);
  447     foreach my $id (@problemIDs) {
  448       $prevID = $id if $id < $problemID
  449         and (not defined $prevID or $id > $prevID);
  450       $nextID = $id if $id > $problemID
  451         and (not defined $nextID or $id < $nextID);
  452     }
  453   }
  454 
  455   my @links;
  456 
  457   if ($prevID) {
  458     my $prevPage = $urlpath->newFromModule(__PACKAGE__,
  459       courseID => $courseID, setID => $setID, problemID => $prevID);
  460     push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
  461   } else {
  462     push @links, "Previous Problem", "", "navPrev";
  463   }
  464 
  465   push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList";
  466 
  467   if ($nextID) {
  468     my $nextPage = $urlpath->newFromModule(__PACKAGE__,
  469       courseID => $courseID, setID => $setID, problemID => $nextID);
  470     push @links, "Next Problem", $r->location . $nextPage->path, "navNext";
  471   } else {
  472     push @links, "Next Problem", "", "navNext";
  473   }
  474 
  475   my $tail = "&displayMode=".$self->{displayMode};
  476   return $self->navMacro($args, $tail, @links);
  477 }
  478 
  479 sub title {
  480   my ($self) = @_;
  481 
  482   # using the url arguments won't break if the set/problem are invalid
  483   my $setID = $self->r->urlpath->arg("setID");
  484   my $problemID = $self->r->urlpath->arg("problemID");
  485 
  486   return "$setID : $problemID";
  487 }
  488 
  489 sub body {
  490   my $self = shift;
  491   my $r = $self->r;
  492   my $ce = $r->ce;
  493   my $db = $r->db;
  494   my $authz = $r->authz;
  495   my $urlpath = $r->urlpath;
  496   my $user = $r->param('user');
  497 
  498   if ($self->{invalidSet}) {
  499     return CGI::div({class=>"ResultsWithError"},
  500       CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . "."));
  501   }
  502 
  503   if ($self->{invalidProblem}) {
  504     return CGI::div({class=>"ResultsWithError"},
  505       CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . "."));
  506   }
  507 
  508   unless ($self->{isOpen}) {
  509     return CGI::div({class=>"ResultsWithError"},
  510       CGI::p("This problem is not available because the problem set that contains it is not yet open."));
  511   }
  512   # unpack some useful variables
  513   my $set             = $self->{set};
  514   my $problem         = $self->{problem};
  515   my $editMode        = $self->{editMode};
  516   my $permissionLevel = $self->{permissionLevel};
  517   my $submitAnswers   = $self->{submitAnswers};
  518   my $checkAnswers    = $self->{checkAnswers};
  519   my $previewAnswers  = $self->{previewAnswers};
  520   my %want            = %{ $self->{want} };
  521   my %can             = %{ $self->{can}  };
  522   my %must            = %{ $self->{must} };
  523   my %will            = %{ $self->{will} };
  524   my $pg              = $self->{pg};
  525 
  526   my $courseName = $urlpath->arg("courseID");
  527 
  528   my $editorLink = "";
  529   # if we are here without a real problem set, carry that through
  530   my $forced_field = [];
  531   $forced_field = ['sourceFilePath' =>  $r->param("sourceFilePath")] if
  532     ($set->set_id eq 'Undefined_Set');
  533   if ($authz->hasPermissions($user, "modify_problem_sets")) {
  534     my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
  535       courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id);
  536     my $editorURL = $self->systemLink($editorPage, params=>$forced_field);
  537     $editorLink = CGI::a({href=>$editorURL}, "Edit this problem");
  538   }
  539 
  540   ##### translation errors? #####
  541 
  542   if ($pg->{flags}->{error_flag}) {
  543     print $self->errorOutput($pg->{errors}, $pg->{body_text});
  544     print $editorLink;
  545     return "";
  546   }
  547 
  548   ##### answer processing #####
  549   $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer);
  550   # if answers were submitted:
  551   my $scoreRecordedMessage;
  552   my $pureProblem;
  553   if ($submitAnswers) {
  554     # get a "pure" (unmerged) UserProblem to modify
  555     # this will be undefined if the problem has not been assigned to this user
  556     $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
  557     if (defined $pureProblem) {
  558       # store answers in DB for sticky answers
  559       my %answersToStore;
  560       my %answerHash = %{ $pg->{answers} };
  561       $answersToStore{$_} = $self->{formFields}->{$_}  #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values.  Don't use it!!
  562         foreach (keys %answerHash);
  563 
  564       # There may be some more answers to store -- one which are auxiliary entries to a primary answer.  Evaluating
  565       # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
  566       # however we need to store them.  Fortunately they are still in the input form.
  567       my @extra_answer_names  = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
  568       $answersToStore{$_} = $self->{formFields}->{$_} foreach  (@extra_answer_names);
  569 
  570       # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
  571       my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
  572       my $answerString = encodeAnswers(%answersToStore,
  573          @answer_order);
  574 
  575       # store last answer to database
  576       $problem->last_answer($answerString);
  577       $pureProblem->last_answer($answerString);
  578       $db->putUserProblem($pureProblem);
  579 
  580       # store state in DB if it makes sense
  581       if ($will{recordAnswers}) {
  582         $problem->status($pg->{state}->{recorded_score});
  583         $problem->attempted(1);
  584         $problem->num_correct($pg->{state}->{num_of_correct_ans});
  585         $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  586         $pureProblem->status($pg->{state}->{recorded_score});
  587         $pureProblem->attempted(1);
  588         $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
  589         $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  590         if ($db->putUserProblem($pureProblem)) {
  591           $scoreRecordedMessage = "Your score was recorded.";
  592         } else {
  593           $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
  594         }
  595         # write to the transaction log, just to make sure
  596         writeLog($self->{ce}, "transaction",
  597           $problem->problem_id."\t".
  598           $problem->set_id."\t".
  599           $problem->user_id."\t".
  600           $problem->source_file."\t".
  601           $problem->value."\t".
  602           $problem->max_attempts."\t".
  603           $problem->problem_seed."\t".
  604           $pureProblem->status."\t".
  605           $pureProblem->attempted."\t".
  606           $pureProblem->last_answer."\t".
  607           $pureProblem->num_correct."\t".
  608           $pureProblem->num_incorrect
  609         );
  610       } else {
  611         if (time < $set->open_date or time > $set->due_date) {
  612           $scoreRecordedMessage = "Your score was not recorded because this problem set is closed.";
  613         } else {
  614           $scoreRecordedMessage = "Your score was not recorded.";
  615         }
  616       }
  617     } else {
  618       $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you.";
  619     }
  620   }
  621 
  622   # logging student answers
  623 
  624   my $answer_log    = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
  625   if ( defined($answer_log ) and defined($pureProblem)) {
  626     if ($submitAnswers ) {
  627       my $answerString = "";
  628       my %answerHash = %{ $pg->{answers} };
  629       # FIXME  this is the line 552 error.  make sure original student ans is defined.
  630       # The fact that it is not defined is probably due to an error in some answer evaluator.
  631       # But I think it is useful to suppress this error message in the log.
  632       foreach (sort keys %answerHash) {
  633         my $student_ans = $answerHash{$_}->{original_student_ans} ||'';
  634         $answerString  .= $student_ans."\t"
  635       }
  636       $answerString = '' unless defined($answerString); # insure string is defined.
  637       writeCourseLog($self->{ce}, "answer_log",
  638               join("",
  639             '|', $problem->user_id,
  640             '|', $problem->set_id,
  641             '|', $problem->problem_id,
  642             '|',"\t",
  643             time(),"\t",
  644             $answerString,
  645           ),
  646       );
  647 
  648     }
  649   }
  650 
  651   $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer);
  652 
  653   ##### output #####
  654 
  655   print CGI::start_div({class=>"problemHeader"});
  656 
  657   # custom message for editor
  658   if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) {
  659     if ($editMode eq "temporaryFile") {
  660       print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file));
  661     } elsif ($editMode eq "savedFile") {
  662       # taken care of in the initialization phase
  663     }
  664   }
  665 
  666   # attempt summary
  667   #FIXME -- the following is a kludge:  if showPartialCorrectAnswers is negative don't show anything.
  668   # until after the due date
  669   # do I need to check $will{showCorrectAnswers} to make preflight work??
  670   if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) {
  671     # print this if user submitted answers OR requested correct answers
  672 
  673     print $self->attemptResults($pg, 1,
  674       $will{showCorrectAnswers},
  675       $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
  676   } elsif ($checkAnswers) {
  677     # print this if user previewed answers
  678     print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED  -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br() );
  679     print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
  680       # show attempt answers
  681       # show correct answers if asked
  682       # show attempt results (correctness)
  683       # show attempt previews
  684   } elsif ($previewAnswers) {
  685     # print this if user previewed answers
  686     print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
  687       # show attempt answers
  688       # don't show correct answers
  689       # don't show attempt results (correctness)
  690       # show attempt previews
  691   }
  692 
  693   print CGI::end_div();
  694 
  695   print CGI::start_div({class=>"problem"});
  696 
  697   # main form
  698   print
  699     CGI::startform("POST", $r->uri),
  700     $self->hidden_authen_fields,
  701     CGI::p($pg->{body_text}),
  702     CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})),
  703     CGI::p(
  704       ($can{showCorrectAnswers}
  705         ? CGI::checkbox(
  706             -name    => "showCorrectAnswers",
  707             -checked => $will{showCorrectAnswers},
  708             -label   => "Show correct answers",
  709           ) ." "
  710         : "" ),
  711       ($can{showHints}
  712         ? '<div style="color:red">'. CGI::checkbox(
  713           -name    => "showHints",
  714           -checked => $will{showHints},
  715           -label   => "Show Hints",
  716           ) . "</div> "
  717         : " " ),
  718       ($can{showSolutions}
  719         ? CGI::checkbox(
  720           -name    => "showSolutions",
  721           -checked => $will{showSolutions},
  722           -label   => "Show Solutions",
  723           ) . " "
  724         : " " ),CGI::br(),
  725       CGI::submit(-name=>"previewAnswers",
  726         -label=>"Preview Answers"),
  727       ($can{recordAnswers}
  728         ? CGI::submit(-name=>"submitAnswers",
  729           -label=>"Submit Answers")
  730         : ""),
  731       ( $can{checkAnswers}
  732         ? CGI::submit(-name=>"checkAnswers",
  733           -label=>"Check Answers")
  734         : ""),
  735     );
  736   print CGI::end_div();
  737 
  738   print CGI::start_div({class=>"scoreSummary"});
  739 
  740   # score summary
  741   my $attempts = $problem->num_correct + $problem->num_incorrect;
  742   my $attemptsNoun = $attempts != 1 ? "times" : "time";
  743   my $lastScore = sprintf("%.0f%%", $problem->status * 100); # Round to whole number
  744   my ($attemptsLeft, $attemptsLeftNoun);
  745   if ($problem->max_attempts == -1) {
  746     # unlimited attempts
  747     $attemptsLeft = "unlimited";
  748     $attemptsLeftNoun = "attempts";
  749   } else {
  750     $attemptsLeft = $problem->max_attempts - $attempts;
  751     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
  752   }
  753 
  754   my $setClosed = 0;
  755   my $setClosedMessage;
  756   if (time < $set->open_date or time > $set->due_date) {
  757     $setClosed = 1;
  758     $setClosedMessage = "This problem set is closed.";
  759     if ($authz->hasPermissions($user, "view_answers")) {
  760       $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
  761     } else {
  762       $setClosedMessage .= " Additional attempts will not be recorded.";
  763     }
  764   }
  765 
  766   my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)";
  767   print CGI::p(
  768     $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
  769     "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
  770     $problem->attempted
  771       ? "Your recorded score is $lastScore.  $notCountedMessage" . CGI::br()
  772       : "",
  773     $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
  774   );
  775   print CGI::end_div();
  776 
  777   # save state for viewOptions
  778   print  CGI::hidden(
  779          -name  => "showOldAnswers",
  780          -value => $will{showOldAnswers}
  781        ),
  782 
  783        CGI::hidden(
  784          -name  => "displayMode",
  785          -value => $self->{displayMode}
  786        );
  787   print( CGI::hidden(
  788          -name    => 'editMode',
  789          -value   => $self->{editMode},
  790        )
  791   ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
  792   print( CGI::hidden(
  793           -name   => 'sourceFilePath',
  794           -value  =>  $self->{problem}->{source_file}
  795   ))  if defined($self->{problem}->{source_file});
  796 
  797   print( CGI::hidden(
  798           -name   => 'problemSeed',
  799           -value  =>  $r->param("problemSeed")
  800   ))  if defined($r->param("problemSeed"));
  801 
  802   # end of main form
  803   print CGI::endform();
  804 
  805   print  CGI::start_div({class=>"problemFooter"});
  806 
  807   ## arguments for answer inspection button
  808   #my $prof_url = $ce->{webworkURLs}->{oldProf};
  809   #my $webworkURL = $ce->{webworkURLs}->{root};
  810   #my $cgi_url = $prof_url;
  811   #$cgi_url=~ s|/[^/]*$||;  # clip profLogin.pl
  812   #my $authen_args = $self->url_authen_args();
  813   #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
  814 
  815   my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
  816     courseID => $courseName);
  817   my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
  818 
  819   # print answer inspection button
  820   if ($authz->hasPermissions($user, "view_answers")) {
  821     print "\n",
  822       CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
  823       $self->hidden_authen_fields,"\n",
  824       CGI::hidden(-name => 'courseID',  -value=>$courseName), "\n",
  825       CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
  826       CGI::hidden(-name => 'setID',  -value=>$problem->set_id), "\n",
  827       CGI::hidden(-name => 'studentUser',    -value=>$problem->user_id), "\n",
  828       CGI::p( {-align=>"left"},
  829         CGI::submit(-name => 'action',  -value=>'Show Past Answers')
  830       ), "\n",
  831       CGI::endform();
  832   }
  833 
  834   # feedback form url
  835   my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback",
  836     courseID => $courseName);
  837   my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action
  838 
  839   #print feedback form
  840   print
  841     CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
  842     $self->hidden_authen_fields,"\n",
  843     CGI::hidden("module",             __PACKAGE__),"\n",
  844     CGI::hidden("set",                $set->set_id),"\n",
  845     CGI::hidden("problem",            $problem->problem_id),"\n",
  846     CGI::hidden("displayMode",        $self->{displayMode}),"\n",
  847     CGI::hidden("showOldAnswers",     $will{showOldAnswers}),"\n",
  848     CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
  849     CGI::hidden("showHints",          $will{showHints}),"\n",
  850     CGI::hidden("showSolutions",      $will{showSolutions}),"\n",
  851     CGI::p({-align=>"left"},
  852       CGI::submit(-name=>"feedbackForm", -label=>"Email instructor")
  853     ),
  854     CGI::endform(),"\n";
  855 
  856   # FIXME print editor link
  857   print $editorLink;   #empty unless it is appropriate to have an editor link.
  858 
  859   print CGI::end_div();
  860 
  861   # debugging stuff
  862   if (0) {
  863     print
  864       CGI::hr(),
  865       CGI::h2("debugging information"),
  866       CGI::h3("form fields"),
  867       ref2string($self->{formFields}),
  868       CGI::h3("user object"),
  869       ref2string($self->{user}),
  870       CGI::h3("set object"),
  871       ref2string($set),
  872       CGI::h3("problem object"),
  873       ref2string($problem),
  874       CGI::h3("PG object"),
  875       ref2string($pg, {'WeBWorK::PG::Translator' => 1});
  876   }
  877 
  878   return "";
  879 }
  880 
  881 ##### output utilities #####
  882 
  883 sub attemptResults {
  884   my $self = shift;
  885   my $pg = shift;
  886   my $showAttemptAnswers = shift;
  887   my $showCorrectAnswers = shift;
  888   my $showAttemptResults = $showAttemptAnswers && shift;
  889   my $showSummary = shift;
  890   my $showAttemptPreview = shift || 0;
  891 
  892   my $ce = $self->r->ce;
  893 
  894   my $problemResult = $pg->{result}; # the overall result of the problem
  895   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  896 
  897   my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
  898 
  899   my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
  900 
  901   # to make grabbing these options easier, we'll pull them out now...
  902   my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
  903 
  904   my $imgGen = WeBWorK::PG::ImageGenerator->new(
  905     tempDir         => $ce->{webworkDirs}->{tmp},
  906     latex         => $ce->{externalPrograms}->{latex},
  907     dvipng          => $ce->{externalPrograms}->{dvipng},
  908     useCache        => 1,
  909     cacheDir        => $ce->{webworkDirs}->{equationCache},
  910     cacheURL        => $ce->{webworkURLs}->{equationCache},
  911     cacheDB         => $ce->{webworkFiles}->{equationCacheDB},
  912     dvipng_align    => $imagesModeOptions{dvipng_align},
  913     dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
  914   );
  915 
  916   my $header;
  917   #$header .= CGI::th("Part");
  918   $header .= $showAttemptAnswers ? CGI::th("Entered")  : "";
  919   $header .= $showAttemptPreview ? CGI::th("Answer Preview")  : "";
  920   $header .= $showCorrectAnswers ? CGI::th("Correct")  : "";
  921   $header .= $showAttemptResults ? CGI::th("Result")   : "";
  922   $header .= $showMessages       ? CGI::th("Messages") : "";
  923   my @tableRows = ( $header );
  924   my $numCorrect = 0;
  925   foreach my $name (@answerNames) {
  926     my $answerResult  = $pg->{answers}->{$name};
  927     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  928     my $preview       = ($showAttemptPreview
  929                           ? $self->previewAnswer($answerResult, $imgGen)
  930                           : "");
  931     my $correctAnswer = $answerResult->{correct_ans};
  932     my $answerScore   = $answerResult->{score};
  933     my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
  934     #FIXME  --Can we be sure that $answerScore is an integer-- could the problem give partial credit?
  935     $numCorrect += $answerScore > 0;
  936     my $resultString = $answerScore == 1 ? "correct" : "incorrect";
  937 
  938     # get rid of the goofy prefix on the answer names (supposedly, the format
  939     # of the answer names is changeable. this only fixes it for "AnSwEr"
  940     #$name =~ s/^AnSwEr//;
  941 
  942     my $row;
  943     #$row .= CGI::td($name);
  944     $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
  945     $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview))       : "";
  946     $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
  947     $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString))  : "";
  948     $row .= $showMessages       ? CGI::td($self->nbsp($answerMessage)) : "";
  949     push @tableRows, $row;
  950   }
  951 
  952   # render equation images
  953   $imgGen->render(refresh => 1);
  954 
  955 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
  956   my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
  957 #   FIXME  -- I left the old code in in case we have to back out.
  958 # my $summary = "On this attempt, you answered $numCorrect out of "
  959 #   . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
  960   my $summary = "";
  961   if (scalar @answerNames == 1) {
  962       if ($numCorrect == scalar @answerNames) {
  963         $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct.");
  964        } else {
  965          $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct.");
  966        }
  967   } else {
  968       if ($numCorrect == scalar @answerNames) {
  969         $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
  970        } else {
  971          $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT correct.");
  972        }
  973   }
  974 
  975   return
  976     CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
  977     . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : "");
  978 }
  979 
  980 #sub nbsp {
  981 # my $str = shift;
  982 # ($str =~/\S/) ? $str : '&nbsp;'  ;  # returns non-breaking space for empty strings
  983 #                                     # tricky cases:   $str =0;
  984 #                                     #  $str is a complex number
  985 #}
  986 
  987 sub viewOptions {
  988   my ($self) = @_;
  989   my $ce = $self->r->ce;
  990 
  991   # don't show options if we don't have anything to show
  992   return if $self->{invalidSet} or $self->{invalidProblem};
  993   return unless $self->{isOpen};
  994 
  995   my $displayMode = $self->{displayMode};
  996   my %must = %{ $self->{must} };
  997   my %can  = %{ $self->{can}  };
  998   my %will = %{ $self->{will} };
  999 
 1000   my $optionLine;
 1001   $can{showOldAnswers} and $optionLine .= join "",
 1002     "Show: &nbsp;".CGI::br(),
 1003     CGI::checkbox(
 1004       -name    => "showOldAnswers",
 1005       -checked => $will{showOldAnswers},
 1006       -label   => "Saved answers",
 1007     ), "&nbsp;&nbsp;".CGI::br();
 1008 
 1009   $optionLine and $optionLine .= join "", CGI::br();
 1010 
 1011   my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
 1012   my @active_modes = grep { exists $display_modes{$_} }
 1013       @{$ce->{pg}->{displayModes}};
 1014   my $modeLine = (scalar(@active_modes)>1) ?
 1015     "View&nbsp;equations&nbsp;as:&nbsp;&nbsp;&nbsp;&nbsp;".CGI::br().
 1016     CGI::radio_group(
 1017       -name    => "displayMode",
 1018       -values  => \@active_modes,
 1019       -default => $displayMode,
 1020       -linebreak=>'true',
 1021       -labels  => {
 1022         plainText     => "plain",
 1023         formattedText => "formatted",
 1024         images        => "images",
 1025         jsMath        => "jsMath",
 1026         asciimath     => "asciimath",
 1027       },
 1028     ). CGI::br().CGI::hr() : '';
 1029 
 1030   return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"},
 1031     $modeLine,
 1032     $optionLine,
 1033     CGI::submit(-name=>"redisplay", -label=>"Save Options"),
 1034   );
 1035 }
 1036 
 1037 sub previewAnswer {
 1038   my ($self, $answerResult, $imgGen) = @_;
 1039   my $ce            = $self->r->ce;
 1040   my $effectiveUser = $self->{effectiveUser};
 1041   my $set           = $self->{set};
 1042   my $problem       = $self->{problem};
 1043   my $displayMode   = $self->{displayMode};
 1044 
 1045   # note: right now, we have to do things completely differently when we are
 1046   # rendering math from INSIDE the translator and from OUTSIDE the translator.
 1047   # so we'll just deal with each case explicitly here. there's some code
 1048   # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
 1049 
 1050   my $tex = $answerResult->{preview_latex_string};
 1051 
 1052   return "" unless defined $tex and $tex ne "";
 1053 
 1054   if ($displayMode eq "plainText") {
 1055     return $tex;
 1056   } elsif ($displayMode eq "formattedText") {
 1057     my $tthCommand = $ce->{externalPrograms}->{tth}
 1058       . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
 1059       . "\\(".$tex."\\)\n"
 1060       . "END_OF_INPUT\n";
 1061 
 1062     # call tth
 1063     my $result = `$tthCommand`;
 1064     if ($?) {
 1065       return "<b>[tth failed: $? $@]</b>";
 1066     }
 1067     return $result;
 1068   } elsif ($displayMode eq "images") {
 1069     $imgGen->add($tex);
 1070   } elsif ($displayMode eq "jsMath") {
 1071 
 1072     return '<DIV CLASS="math">'.$tex.'</DIV>' ;
 1073 
 1074 
 1075 
 1076 
 1077   }
 1078 }
 1079 
 1080 ##### permission queries #####
 1081 
 1082 # this stuff should be abstracted out into the permissions system
 1083 # however, the permission system only knows about things in the
 1084 # course environment and the username. hmmm...
 1085 
 1086 # also, i should fix these so that they have a consistent calling
 1087 # format -- perhaps:
 1088 #   canPERM($ce, $user, $set, $problem, $permissionLevel)
 1089 
 1090 sub canShowCorrectAnswers($$) {
 1091   my ($permissionLevel, $answerDate) = @_;
 1092   return $permissionLevel > 0 || time > $answerDate;
 1093 }
 1094 
 1095 sub canShowSolutions($$) {
 1096   my ($permissionLevel, $answerDate) = @_;
 1097   return canShowCorrectAnswers($permissionLevel, $answerDate);
 1098 }
 1099 
 1100 sub canRecordAnswers($$$$$) {
 1101   my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_;
 1102   my $permHigh = $permissionLevel > 0;
 1103   my $timeOK = time >= $openDate && time <= $dueDate;
 1104   my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts;
 1105   my $recordAnswers = $permHigh || ($timeOK && $attemptsOK);
 1106   return $recordAnswers;
 1107 }
 1108 
 1109 sub canCheckAnswers($$) {
 1110   my ($permissionLevel, $dueDate) = @_;
 1111   my $permHigh = $permissionLevel > 0;
 1112   my $timeOK = time >= $dueDate;
 1113   my $recordAnswers = $permHigh || $timeOK;
 1114   return $recordAnswers;
 1115 }
 1116 
 1117 sub mustRecordAnswers($) {
 1118   my ($permissionLevel) = @_;
 1119   return $permissionLevel == 0;
 1120 }
 1121 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9