[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 2415 - (download) (as text) (annotate)
Sat Jun 26 16:12:16 2004 UTC (8 years, 10 months ago) by jj
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm
File size: 39236 byte(s)
Altered course in how to set vertical alignment of images, so this
undoes calls for javascript, and passes more arguments to imagegenerator
(which can be used someday soon).

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9