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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6285 - (download) (as text) (annotate)
Sat May 29 12:43:20 2010 UTC (2 years, 11 months ago) by gage
File size: 48112 byte(s)
check that a tex output actually exists before typesetting the correct answer.
This effort is still a hack.  Problem.pm needs to be written from the ground up.

    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2007 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.225 2010/05/28 21:29:48 gage 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(-nosticky );
   29 use WeBWorK::CGI;
   30 use File::Path qw(rmtree);
   31 use WeBWorK::Debug;
   32 use WeBWorK::Form;
   33 use WeBWorK::PG;
   34 use WeBWorK::PG::ImageGenerator;
   35 use WeBWorK::PG::IO;
   36 use WeBWorK::Utils qw(readFile writeLog writeCourseLog encodeAnswers decodeAnswers
   37   ref2string makeTempDirectory path_is_subdir sortByName before after between);
   38 use WeBWorK::DB::Utils qw(global2user user2global);
   39 use URI::Escape;
   40 
   41 use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
   42 
   43 ################################################################################
   44 # CGI param interface to this module (up-to-date as of v1.153)
   45 ################################################################################
   46 
   47 # Standard params:
   48 #
   49 #     user - user ID of real user
   50 #     key - session key
   51 #     effectiveUser - user ID of effective user
   52 #
   53 # Integration with PGProblemEditor:
   54 #
   55 #     editMode - if set, indicates alternate problem source location.
   56 #                can be "temporaryFile" or "savedFile".
   57 #
   58 #     sourceFilePath - path to file to be edited
   59 #     problemSeed - force problem seed to value
   60 #     success - success message to display
   61 #     failure - failure message to display
   62 #
   63 # Rendering options:
   64 #
   65 #     displayMode - name of display mode to use
   66 #
   67 #     showOldAnswers - request that last entered answer be shown (if allowed)
   68 #     showCorrectAnswers - request that correct answers be shown (if allowed)
   69 #     showHints - request that hints be shown (if allowed)
   70 #     showSolutions - request that solutions be shown (if allowed)
   71 #
   72 # Problem interaction:
   73 #
   74 #     AnSwEr# - answer blanks in problem
   75 #
   76 #     redisplay - name of the "Redisplay Problem" button
   77 #     submitAnswers - name of "Submit Answers" button
   78 #     checkAnswers - name of the "Check Answers" button
   79 #     previewAnswers - name of the "Preview Answers" button
   80 
   81 ################################################################################
   82 # "can" methods
   83 ################################################################################
   84 
   85 # Subroutines to determine if a user "can" perform an action. Each subroutine is
   86 # called with the following arguments:
   87 #
   88 #     ($self, $User, $EffectiveUser, $Set, $Problem)
   89 
   90 # Note that significant parts of the "can" methods are lifted into the
   91 # GatewayQuiz module.  It isn't direct, however, because of the necessity
   92 # of dealing with versioning there.
   93 
   94 sub can_showOldAnswers {
   95   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
   96 
   97   return 1;
   98 }
   99 
  100 sub can_showCorrectAnswers {
  101   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  102   my $authz = $self->r->authz;
  103 
  104   return
  105     after($Set->answer_date)
  106       ||
  107     $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")
  108     ;
  109 }
  110 
  111 sub can_showHints {
  112   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  113 
  114   return 1;
  115 }
  116 
  117 sub can_showSolutions {
  118   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  119   my $authz = $self->r->authz;
  120 
  121   return
  122     after($Set->answer_date)
  123       ||
  124     $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date")
  125     ;
  126 }
  127 
  128 sub can_recordAnswers {
  129   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  130   my $authz = $self->r->authz;
  131   my $thisAttempt = $submitAnswers ? 1 : 0;
  132   if ($User->user_id ne $EffectiveUser->user_id) {
  133     return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
  134   }
  135   if (before($Set->open_date)) {
  136     return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
  137   } elsif (between($Set->open_date, $Set->due_date)) {
  138     my $max_attempts = $Problem->max_attempts;
  139     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  140     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  141       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts");
  142     } else {
  143       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts");
  144     }
  145   } elsif (between($Set->due_date, $Set->answer_date)) {
  146     return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
  147   } elsif (after($Set->answer_date)) {
  148     return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
  149   }
  150 }
  151 
  152 sub can_checkAnswers {
  153   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  154   my $authz = $self->r->authz;
  155   my $thisAttempt = $submitAnswers ? 1 : 0;
  156 
  157   if (before($Set->open_date)) {
  158     return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
  159   } elsif (between($Set->open_date, $Set->due_date)) {
  160     my $max_attempts = $Problem->max_attempts;
  161     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  162     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  163       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts");
  164     } else {
  165       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts");
  166     }
  167   } elsif (between($Set->due_date, $Set->answer_date)) {
  168     return $authz->hasPermissions($User->user_id, "check_answers_after_due_date");
  169   } elsif (after($Set->answer_date)) {
  170     return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date");
  171   }
  172 }
  173 
  174 # Reset the default in some cases
  175 sub set_showOldAnswers_default {
  176   my ($self, $ce, $userName, $authz, $set) = @_;
  177   # these people always use the system/course default, so don't
  178   # override the value of ...->{showOldAnswers}
  179   return if $authz->hasPermissions($userName, "can_always_use_show_old_answers_default");
  180   # this person should always default to 0
  181   $ce->{pg}->{options}->{showOldAnswers} = 0
  182     unless ($authz->hasPermissions($userName, "can_show_old_answers_by_default"));
  183   # we are after the due date, so default to not showing it
  184   $ce->{pg}->{options}->{showOldAnswers} = 0 if $set->{due_date} && after($set->{due_date});
  185 }
  186 
  187 ################################################################################
  188 # output utilities
  189 ################################################################################
  190 
  191 # Note: the substance of attemptResults is lifted into GatewayQuiz.pm,
  192 # with some changes to the output format
  193 
  194 sub attemptResults {
  195   my $self = shift;
  196   my $pg = shift;
  197   my $showAttemptAnswers = shift;
  198   my $showCorrectAnswers = shift;
  199   my $showAttemptResults = $showAttemptAnswers && shift;
  200   my $showSummary = shift;
  201   my $showAttemptPreview = shift || 0;
  202 
  203   my $ce = $self->r->ce;
  204 
  205   my $problemResult = $pg->{result}; # the overall result of the problem
  206   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  207 
  208   my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
  209 
  210   my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
  211 
  212   # to make grabbing these options easier, we'll pull them out now...
  213   my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
  214 
  215   my $imgGen = WeBWorK::PG::ImageGenerator->new(
  216     tempDir         => $ce->{webworkDirs}->{tmp},
  217     latex         => $ce->{externalPrograms}->{latex},
  218     dvipng          => $ce->{externalPrograms}->{dvipng},
  219     useCache        => 1,
  220     cacheDir        => $ce->{webworkDirs}->{equationCache},
  221     cacheURL        => $ce->{webworkURLs}->{equationCache},
  222     cacheDB         => $ce->{webworkFiles}->{equationCacheDB},
  223     dvipng_align    => $imagesModeOptions{dvipng_align},
  224     dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
  225   );
  226 
  227   my $header;
  228   #$header .= CGI::th("Part");
  229   $header .= $showAttemptAnswers ? CGI::th("Entered")  : "";
  230   $header .= $showAttemptPreview ? CGI::th("Answer Preview")  : "";
  231   $header .= $showCorrectAnswers ? CGI::th("Correct")  : "";
  232   $header .= $showAttemptResults ? CGI::th("Result")   : "";
  233   $header .= $showMessages       ? CGI::th("Messages") : "";
  234   my $fully = '';
  235   my @tableRows = ( $header );
  236   my $numCorrect = 0;
  237   my $numBlanks  =0;
  238   my $tthPreambleCache;
  239   foreach my $name (@answerNames) {
  240     my $answerResult  = $pg->{answers}->{$name};
  241     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  242     my $preview       = ($showAttemptPreview
  243                           ? $self->previewAnswer($answerResult, $imgGen, \$tthPreambleCache)
  244                           : "");
  245     my $correctAnswerPreview = $self->previewCorrectAnswer($answerResult, $imgGen, \$tthPreambleCache);
  246     my $correctAnswer = $answerResult->{correct_ans};
  247     my $answerScore   = $answerResult->{score};
  248     my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
  249     $answerMessage =~ s/\n/<BR>/g;
  250     $numCorrect += $answerScore >= 1;
  251     $numBlanks++ unless $studentAnswer =~/\S/ || $answerScore >= 1;   # unless student answer contains entry
  252     my $resultString = $answerScore >= 1 ? "correct" :
  253                        $answerScore > 0  ? int($answerScore*100)."% correct" :
  254                                                        "incorrect";
  255     $fully = 'completely ' if $answerScore >0 and $answerScore < 1;
  256 
  257     # get rid of the goofy prefix on the answer names (supposedly, the format
  258     # of the answer names is changeable. this only fixes it for "AnSwEr"
  259     #$name =~ s/^AnSwEr//;
  260 
  261     my $row;
  262     #$row .= CGI::td($name);
  263     $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
  264     $row .= $showAttemptPreview ? CGI::td({title=>"$studentAnswer"}, $self->nbsp($preview))       : "";
  265     $row .= $showCorrectAnswers ? CGI::td({title=> "$correctAnswerPreview"}, $self->nbsp($correctAnswer)) : "";
  266     $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString))  : "";
  267     $row .= $showMessages       ? CGI::td({-class=>"Message"},$self->nbsp($answerMessage)) : "";
  268     push @tableRows, $row;
  269   }
  270 
  271   # render equation images
  272   $imgGen->render(refresh => 1);
  273 
  274 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
  275   my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
  276 #   FIXME  -- I left the old code in in case we have to back out.
  277 # my $summary = "On this attempt, you answered $numCorrect out of "
  278 #   . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
  279   my $summary = "";
  280   unless (defined($problemResult->{summary}) and $problemResult->{summary} =~ /\S/) {
  281     if (scalar @answerNames == 1) {  #default messages
  282         if ($numCorrect == scalar @answerNames) {
  283           $summary .= CGI::div({class=>"ResultsWithoutError"},"The answer above is correct.");
  284          } else {
  285            $summary .= CGI::div({class=>"ResultsWithError"},"The answer above is NOT ${fully}correct.");
  286          }
  287     } else {
  288         if ($numCorrect == scalar @answerNames) {
  289           $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the answers above are correct.");
  290          }
  291          unless ($numCorrect + $numBlanks == scalar( @answerNames)) {
  292           $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the answers above is NOT ${fully}correct.");
  293          }
  294          if ($numBlanks) {
  295           my $s = ($numBlanks>1)?'':'s';
  296           $summary .= CGI::div({class=>"ResultsAlert"},"$numBlanks of the questions remain$s unanswered.");
  297          }
  298     }
  299   } else {
  300     $summary = $problemResult->{summary};   # summary has been defined by grader
  301   }
  302   return
  303     CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
  304     . ($showSummary ? CGI::p({class=>'attemptResultsSummary'},$summary) : "");
  305 }
  306 
  307 
  308 # Note: previewAnswer is lifted into GatewayQuiz.pm
  309 
  310 sub previewAnswer {
  311   my ($self, $answerResult, $imgGen, $tthPreambleCache) = @_;
  312   my $ce            = $self->r->ce;
  313   my $effectiveUser = $self->{effectiveUser};
  314   my $set           = $self->{set};
  315   my $problem       = $self->{problem};
  316   my $displayMode   = $self->{displayMode};
  317 
  318   # note: right now, we have to do things completely differently when we are
  319   # rendering math from INSIDE the translator and from OUTSIDE the translator.
  320   # so we'll just deal with each case explicitly here. there's some code
  321   # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
  322 
  323   my $tex = $answerResult->{preview_latex_string};
  324 
  325   return "" unless defined $tex and $tex ne "";
  326 
  327   if ($displayMode eq "plainText") {
  328     return $tex;
  329   } elsif ($displayMode eq "formattedText") {
  330 
  331     # read the TTH preamble, or use the cached copy passed in from the caller
  332     my $tthPreamble='';
  333     if (defined $$tthPreambleCache) {
  334       $tthPreamble = $$tthPreambleCache;
  335     } else {
  336       my $tthPreambleFile = $ce->{courseDirs}->{templates} . "/tthPreamble.tex";
  337       if (-r $tthPreambleFile) {
  338         $tthPreamble = readFile($tthPreambleFile);
  339         # thanks to Jim Martino. each line in the definition file should end with
  340         #a % to prevent adding supurious paragraphs to output:
  341         $tthPreamble =~ s/(.)\n/$1%\n/g;
  342         # solves the problem if the file doesn't end with a return:
  343         $tthPreamble .="%\n";
  344         # store preamble in cache:
  345         $$tthPreambleCache = $tthPreamble;
  346       } else {
  347       }
  348     }
  349 
  350     # construct TTH command line
  351     my $tthCommand = $ce->{externalPrograms}->{tth}
  352       . " -L -f5 -u -r  2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
  353       . $tthPreamble . "\\[" . $tex . "\\]\n"
  354       . "END_OF_INPUT\n";
  355 
  356     # call tth
  357     my $result = `$tthCommand`;
  358     if ($?) {
  359       return "<b>[tth failed: $? $@]</b>";
  360     } else {
  361       #  avoid border problems in tables and remove unneeded initial <br>
  362       $result =~ s/(<table [^>]*)>/$1 CLASS="ArrayLayout">/gi;
  363       $result =~ s!\s*<br clear="all" />!!;
  364       return $result;
  365     }
  366 
  367   } elsif ($displayMode eq "images") {
  368     $imgGen->add($tex);
  369   } elsif ($displayMode eq "jsMath") {
  370     $tex =~ s/</&lt;/g; $tex =~ s/>/&gt;/g;
  371     return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>';
  372   }
  373 }
  374 sub previewCorrectAnswer {
  375   my ($self, $answerResult, $imgGen, $tthPreambleCache) = @_;
  376   my $ce            = $self->r->ce;
  377   my $effectiveUser = $self->{effectiveUser};
  378   my $set           = $self->{set};
  379   my $problem       = $self->{problem};
  380   my $displayMode   = $self->{displayMode};
  381 
  382   # note: right now, we have to do things completely differently when we are
  383   # rendering math from INSIDE the translator and from OUTSIDE the translator.
  384   # so we'll just deal with each case explicitly here. there's some code
  385   # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
  386 
  387   return "" unless defined(  $answerResult->{correct_value} ) and ref( $answerResult->{correct_value} );
  388 
  389   my $tex = $answerResult->{correct_value}->TeX;
  390 
  391   return "" unless defined $tex and $tex ne "";
  392 
  393   if ($displayMode eq "plainText") {
  394     return $tex;
  395   } elsif ($displayMode eq "formattedText") {
  396 
  397     # read the TTH preamble, or use the cached copy passed in from the caller
  398     my $tthPreamble='';
  399     if (defined $$tthPreambleCache) {
  400       $tthPreamble = $$tthPreambleCache;
  401     } else {
  402       my $tthPreambleFile = $ce->{courseDirs}->{templates} . "/tthPreamble.tex";
  403       if (-r $tthPreambleFile) {
  404         $tthPreamble = readFile($tthPreambleFile);
  405         # thanks to Jim Martino. each line in the definition file should end with
  406         #a % to prevent adding supurious paragraphs to output:
  407         $tthPreamble =~ s/(.)\n/$1%\n/g;
  408         # solves the problem if the file doesn't end with a return:
  409         $tthPreamble .="%\n";
  410         # store preamble in cache:
  411         $$tthPreambleCache = $tthPreamble;
  412       } else {
  413       }
  414     }
  415 
  416     # construct TTH command line
  417     my $tthCommand = $ce->{externalPrograms}->{tth}
  418       . " -L -f5 -u -r  2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
  419       . $tthPreamble . "\\[" . $tex . "\\]\n"
  420       . "END_OF_INPUT\n";
  421 
  422     # call tth
  423     my $result = `$tthCommand`;
  424     if ($?) {
  425       return "<b>[tth failed: $? $@]</b>";
  426     } else {
  427       #  avoid border problems in tables and remove unneeded initial <br>
  428       $result =~ s/(<table [^>]*)>/$1 CLASS="ArrayLayout">/gi;
  429       $result =~ s!\s*<br clear="all" />!!;
  430       return $result;
  431     }
  432 
  433   } elsif ($displayMode eq "images") {
  434     $imgGen->add($tex);
  435   } elsif ($displayMode eq "jsMath") {
  436     $tex =~ s/</&lt;/g; $tex =~ s/>/&gt;/g;
  437     return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>';
  438   }
  439 }
  440 
  441 ################################################################################
  442 # Template escape implementations
  443 ################################################################################
  444 
  445 sub pre_header_initialize {
  446   my ($self) = @_;
  447   my $r = $self->r;
  448   my $ce = $r->ce;
  449   my $db = $r->db;
  450   my $authz = $r->authz;
  451   my $urlpath = $r->urlpath;
  452 
  453   my $setName = $urlpath->arg("setID");
  454   my $problemNumber = $r->urlpath->arg("problemID");
  455   my $userName = $r->param('user');
  456   my $effectiveUserName = $r->param('effectiveUser');
  457   my $key = $r->param('key');
  458   my $editMode = $r->param("editMode");
  459 
  460   my $user = $db->getUser($userName); # checked
  461   die "record for user $userName (real user) does not exist."
  462     unless defined $user;
  463 
  464   my $effectiveUser = $db->getUser($effectiveUserName); # checked
  465   die "record for user $effectiveUserName (effective user) does not exist."
  466     unless defined $effectiveUser;
  467 
  468   # obtain the merged set for $effectiveUser
  469   my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
  470 
  471   $self->set_showOldAnswers_default($ce, $userName, $authz, $set);
  472 
  473   # Database fix (in case of undefined published values)
  474   # this is only necessary because some people keep holding to ww1.9 which did not have a published field
  475   # make sure published is set to 0 or 1
  476   if ( $set and $set->published ne "0" and $set->published ne "1") {
  477     my $globalSet = $db->getGlobalSet($set->set_id);
  478     $globalSet->published("1"); # defaults to published
  479     $db->putGlobalSet($globalSet);
  480     $set = $db->getMergedSet($effectiveUserName, $setName);
  481   } else {
  482     # don't do anything just yet, maybe we're a professor and we're
  483     # fabricating a set or haven't assigned it to ourselves just yet
  484   }
  485     # When a set is created enable_reduced_scoring is null, so we have to set it
  486   if ( $set and $set->enable_reduced_scoring ne "0" and $set->enable_reduced_scoring ne "1") {
  487     my $globalSet = $db->getGlobalSet($set->set_id);
  488     $globalSet->enable_reduced_scoring("0");  # defaults to disabled
  489     $db->putGlobalSet($globalSet);
  490     $set = $db->getMergedSet($effectiveUserName, $setName);
  491   }
  492 
  493 
  494   # obtain the merged problem for $effectiveUser
  495   my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
  496 
  497   if ($authz->hasPermissions($userName, "modify_problem_sets")) {
  498     # professors are allowed to fabricate sets and problems not
  499     # assigned to them (or anyone). this allows them to use the
  500     # editor to
  501 
  502     # if a User Set does not exist for this user and this set
  503     # then we check the Global Set
  504     # if that does not exist we create a fake set
  505     # if it does, we add fake user data
  506     unless (defined $set) {
  507       my $userSetClass = $db->{set_user}->{record};
  508       my $globalSet = $db->getGlobalSet($setName); # checked
  509 
  510       if (not defined $globalSet) {
  511         $set = fake_set($db);
  512       } else {
  513         $set = global2user($userSetClass, $globalSet);
  514         $set->psvn(0);
  515       }
  516     }
  517 
  518     # if that is not yet defined obtain the global problem,
  519     # convert it to a user problem, and add fake user data
  520     unless (defined $problem) {
  521       my $userProblemClass = $db->{problem_user}->{record};
  522       my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
  523       # if the global problem doesn't exist either, bail!
  524       if(not defined $globalProblem) {
  525         my $sourceFilePath = $r->param("sourceFilePath");
  526         die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir
  527         # These are problems from setmaker.  If declared invalid, they won't come up
  528         $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
  529 #       die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
  530         $problem = fake_problem($db);
  531         $problem->problem_id(1);
  532         $problem->source_file($sourceFilePath);
  533         $problem->user_id($effectiveUserName);
  534       } else {
  535         $problem = global2user($userProblemClass, $globalProblem);
  536         $problem->user_id($effectiveUserName);
  537         $problem->problem_seed(0);
  538         $problem->status(0);
  539         $problem->attempted(0);
  540         $problem->last_answer("");
  541         $problem->num_correct(0);
  542         $problem->num_incorrect(0);
  543       }
  544     }
  545 
  546     # now we're sure we have valid UserSet and UserProblem objects
  547     # yay!
  548 
  549     # now deal with possible editor overrides:
  550 
  551     # if the caller is asking to override the source file, and
  552     # editMode calls for a temporary file, do so
  553     my $sourceFilePath = $r->param("sourceFilePath");
  554     if (defined $editMode and $editMode eq "temporaryFile" and defined $sourceFilePath) {
  555       die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir
  556       $problem->source_file($sourceFilePath);
  557     }
  558 
  559     # if the problem does not have a source file or no source file has been passed in
  560     # then this is really an invalid problem (probably from a bad URL)
  561     $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file);
  562 
  563     # if the caller is asking to override the problem seed, do so
  564     my $problemSeed = $r->param("problemSeed");
  565     if (defined $problemSeed) {
  566       $problem->problem_seed($problemSeed);
  567     }
  568 
  569     my $publishedClass = ($set->published) ? "Published" : "Unpublished";
  570     my $publishedText = ($set->published) ? "visible to students." : "hidden from students.";
  571     $self->addmessage(CGI::span("This set is " . CGI::font({class=>$publishedClass}, $publishedText)));
  572 
  573   # test for additional problem validity if it's not already invalid
  574         } else {
  575     $self->{invalidProblem} = !(defined $problem and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")));
  576 
  577     $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem};
  578   }
  579 
  580   $self->{userName}          = $userName;
  581   $self->{effectiveUserName} = $effectiveUserName;
  582   $self->{user}              = $user;
  583   $self->{effectiveUser}     = $effectiveUser;
  584   $self->{set}               = $set;
  585   $self->{problem}           = $problem;
  586   $self->{editMode}          = $editMode;
  587 
  588   ##### form processing #####
  589 
  590   # set options from form fields (see comment at top of file for names)
  591   my $displayMode        = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
  592   my $redisplay          = $r->param("redisplay");
  593   my $submitAnswers      = $r->param("submitAnswers");
  594   my $checkAnswers       = $r->param("checkAnswers");
  595   my $previewAnswers     = $r->param("previewAnswers");
  596 
  597   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
  598 
  599   $self->{displayMode}    = $displayMode;
  600   $self->{redisplay}      = $redisplay;
  601   $self->{submitAnswers}  = $submitAnswers;
  602   $self->{checkAnswers}   = $checkAnswers;
  603   $self->{previewAnswers} = $previewAnswers;
  604   $self->{formFields}     = $formFields;
  605 
  606   # get result and send to message
  607   my $status_message = $r->param("status_message");
  608   $self->addmessage(CGI::p("$status_message")) if $status_message;
  609 
  610   # now that we've set all the necessary variables quit out if the set or problem is invalid
  611   return if $self->{invalidSet} || $self->{invalidProblem};
  612 
  613   ##### permissions #####
  614 
  615   # what does the user want to do?
  616   #FIXME  There is a problem with checkboxes -- if they are not checked they are invisible.  Hence if the default mode in $ce is 1
  617   # there is no way to override this.  Probably this is ok for the last three options, but it was definitely not ok for showing
  618   # saved answers which is normally on, but you want to be able to turn it off!  This section should be moved to ContentGenerator
  619   # so that you can set these options anywhere.  We also need mechanisms for making them sticky.
  620   # Note: ProblemSet and ProblemSets might set showOldAnswers to '', which
  621   #       needs to be treated as if it is not set.
  622   my %want = (
  623     showOldAnswers     => (defined($r->param("showOldAnswers")) and $r->param("showOldAnswers") ne '') ? $r->param("showOldAnswers")  : $ce->{pg}->{options}->{showOldAnswers},
  624     showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
  625     showHints          => $r->param("showHints")          || $ce->{pg}->{options}->{showHints},
  626     showSolutions      => $r->param("showSolutions")      || $ce->{pg}->{options}->{showSolutions},
  627     recordAnswers      => $submitAnswers,
  628     checkAnswers       => $checkAnswers,
  629     getSubmitButton    => 1,
  630   );
  631 
  632   # are certain options enforced?
  633   my %must = (
  634     showOldAnswers     => 0,
  635     showCorrectAnswers => 0,
  636     showHints          => 0,
  637     showSolutions      => 0,
  638     recordAnswers      => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
  639     checkAnswers       => 0,
  640     getSubmitButton    => 0,
  641   );
  642 
  643   # does the user have permission to use certain options?
  644   my @args = ($user, $effectiveUser, $set, $problem);
  645   my %can = (
  646     showOldAnswers     => $self->can_showOldAnswers(@args),
  647     showCorrectAnswers => $self->can_showCorrectAnswers(@args),
  648     showHints          => $self->can_showHints(@args),
  649     showSolutions      => $self->can_showSolutions(@args),
  650     recordAnswers      => $self->can_recordAnswers(@args, 0),
  651     checkAnswers       => $self->can_checkAnswers(@args, $submitAnswers),
  652     getSubmitButton    => $self->can_recordAnswers(@args, $submitAnswers),
  653   );
  654 
  655   # final values for options
  656   my %will;
  657   foreach (keys %must) {
  658     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  659     #warn "final values for options $_ is can $can{$_}, want $want{$_}, must $must{$_}, will $will{$_}";
  660   }
  661 
  662   ##### sticky answers #####
  663 
  664   if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
  665     # do this only if new answers are NOT being submitted
  666     my %oldAnswers = decodeAnswers($problem->last_answer);
  667     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  668   }
  669 
  670   ##### translation #####
  671 
  672   debug("begin pg processing");
  673   my $pg = WeBWorK::PG->new(
  674     $ce,
  675     $effectiveUser,
  676     $key,
  677     $set,
  678     $problem,
  679     $set->psvn, # FIXME: this field should be removed
  680     $formFields,
  681     { # translation options
  682       displayMode     => $displayMode,
  683       showHints       => $will{showHints},
  684       showSolutions   => $will{showSolutions},
  685       refreshMath2img => $will{showHints} || $will{showSolutions},
  686       processAnswers  => 1,
  687       permissionLevel => $db->getPermissionLevel($userName)->permission,
  688       effectivePermissionLevel => $db->getPermissionLevel($effectiveUserName)->permission,
  689     },
  690   );
  691 
  692   debug("end pg processing");
  693 
  694   ##### fix hint/solution options #####
  695 
  696   $can{showHints}     &&= $pg->{flags}->{hintExists}
  697                       &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
  698   $can{showSolutions} &&= $pg->{flags}->{solutionExists};
  699 
  700   ##### store fields #####
  701 
  702   $self->{want} = \%want;
  703   $self->{must} = \%must;
  704   $self->{can}  = \%can;
  705   $self->{will} = \%will;
  706   $self->{pg} = $pg;
  707 }
  708 
  709 sub if_errors($$) {
  710   my ($self, $arg) = @_;
  711 
  712   if ($self->{isOpen}) {
  713     return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
  714   } else {
  715     return !$arg;
  716   }
  717 }
  718 
  719 sub head {
  720   my ($self) = @_;
  721 
  722   return "" if ( $self->{invalidSet} );
  723   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  724 }
  725 
  726 sub options {
  727   my ($self) = @_;
  728   #warn "doing options in Problem";
  729 
  730   # don't show options if we don't have anything to show
  731   return "" if $self->{invalidSet} or $self->{invalidProblem};
  732 
  733   my $displayMode = $self->{displayMode};
  734   my %can = %{ $self->{can} };
  735 
  736   my @options_to_show = "displayMode";
  737   push @options_to_show, "showOldAnswers" if $can{showOldAnswers};
  738   push @options_to_show, "showHints" if $can{showHints};
  739   push @options_to_show, "showSolutions" if $can{showSolutions};
  740 
  741   return $self->optionsMacro(
  742     options_to_show => \@options_to_show,
  743     extra_params => ["editMode", "sourceFilePath"],
  744   );
  745 }
  746 
  747 sub siblings {
  748   my ($self) = @_;
  749   my $r = $self->r;
  750   my $db = $r->db;
  751   my $urlpath = $r->urlpath;
  752 
  753   # can't show sibling problems if the set is invalid
  754   return "" if $self->{invalidSet};
  755 
  756   my $courseID = $urlpath->arg("courseID");
  757   my $setID = $self->{set}->set_id;
  758   my $eUserID = $r->param("effectiveUser");
  759   my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
  760 
  761   print CGI::start_div({class=>"info-box", id=>"fisheye"});
  762   print CGI::h2("Problems");
  763   #print CGI::start_ul({class=>"LinksMenu"});
  764   #print CGI::start_li();
  765   #print CGI::span({style=>"font-size:larger"}, "Problems");
  766   print CGI::start_ul();
  767 
  768   foreach my $problemID (@problemIDs) {
  769     my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
  770       courseID => $courseID, setID => $setID, problemID => $problemID);
  771     print CGI::li(CGI::a( {href=>$self->systemLink($problemPage,
  772                           params=>{  displayMode => $self->{displayMode},
  773                                  showOldAnswers => $self->{will}->{showOldAnswers}
  774                               })},  "Problem $problemID")
  775      );
  776   }
  777 
  778   print CGI::end_ul();
  779   #print CGI::end_li();
  780   #print CGI::end_ul();
  781   print CGI::end_div();
  782 
  783   return "";
  784 }
  785 
  786 sub nav {
  787   my ($self, $args) = @_;
  788   my $r = $self->r;
  789   my $db = $r->db;
  790   my $urlpath = $r->urlpath;
  791 
  792   return "" if ( $self->{invalidSet} );
  793 
  794   my $courseID = $urlpath->arg("courseID");
  795   my $setID = $self->{set}->set_id if !($self->{invalidSet});
  796   my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
  797   my $eUserID = $r->param("effectiveUser");
  798 
  799   my ($prevID, $nextID);
  800 
  801   if (!$self->{invalidProblem}) {
  802     my @problemIDs = $db->listUserProblems($eUserID, $setID);
  803     foreach my $id (@problemIDs) {
  804       $prevID = $id if $id < $problemID
  805         and (not defined $prevID or $id > $prevID);
  806       $nextID = $id if $id > $problemID
  807         and (not defined $nextID or $id < $nextID);
  808     }
  809   }
  810 
  811   my @links;
  812 
  813   if ($prevID) {
  814     my $prevPage = $urlpath->newFromModule(__PACKAGE__,
  815       courseID => $courseID, setID => $setID, problemID => $prevID);
  816     push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
  817   } else {
  818     push @links, "Previous Problem", "", "navPrevGrey";
  819   }
  820 
  821   if (defined($setID) && $setID ne 'Undefined_Set') {
  822     push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList";
  823   } else {
  824     push @links, "Problem List", "", "navProbListGrey";
  825   }
  826 
  827   if ($nextID) {
  828     my $nextPage = $urlpath->newFromModule(__PACKAGE__,
  829       courseID => $courseID, setID => $setID, problemID => $nextID);
  830     push @links, "Next Problem", $r->location . $nextPage->path, "navNext";
  831   } else {
  832     push @links, "Next Problem", "", "navNextGrey";
  833   }
  834 
  835   my $tail = "";
  836 
  837   $tail .= "&displayMode=".$self->{displayMode} if defined $self->{displayMode};
  838   $tail .= "&showOldAnswers=".$self->{will}->{showOldAnswers}
  839     if defined $self->{will}->{showOldAnswers};
  840   return $self->navMacro($args, $tail, @links);
  841 }
  842 
  843 sub title {
  844   my ($self) = @_;
  845 
  846   # using the url arguments won't break if the set/problem are invalid
  847   my $setID = WeBWorK::ContentGenerator::underscore2nbsp($self->r->urlpath->arg("setID"));
  848   my $problemID = $self->r->urlpath->arg("problemID");
  849 
  850   return "$setID: Problem $problemID";
  851 }
  852 
  853 sub body {
  854   my $self = shift;
  855   my $r = $self->r;
  856   my $ce = $r->ce;
  857   my $db = $r->db;
  858   my $authz = $r->authz;
  859   my $urlpath = $r->urlpath;
  860   my $user = $r->param('user');
  861   my $effectiveUser = $r->param('effectiveUser');
  862 
  863   if ( $self->{invalidSet} ) {
  864     return CGI::div({class=>"ResultsWithError"},
  865         CGI::p("The selected problem set (" .
  866                $urlpath->arg("setID") . ") is not " .
  867                "a valid set for $effectiveUser:"),
  868         CGI::p($self->{invalidSet}));
  869   }
  870 
  871   if ($self->{invalidProblem}) {
  872     return CGI::div({class=>"ResultsWithError"},
  873       CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . "."));
  874   }
  875 
  876   # unpack some useful variables
  877   my $set             = $self->{set};
  878   my $problem         = $self->{problem};
  879   my $editMode        = $self->{editMode};
  880   my $submitAnswers   = $self->{submitAnswers};
  881   my $checkAnswers    = $self->{checkAnswers};
  882   my $previewAnswers  = $self->{previewAnswers};
  883   my %want            = %{ $self->{want} };
  884   my %can             = %{ $self->{can}  };
  885   my %must            = %{ $self->{must} };
  886   my %will            = %{ $self->{will} };
  887   my $pg              = $self->{pg};
  888 
  889   my $courseName = $urlpath->arg("courseID");
  890 
  891   # FIXME: move editor link to top, next to problem number.
  892   # format as "[edit]" like we're doing with course info file, etc.
  893   # add edit link for set as well.
  894   my $editorLink = "";
  895   # if we are here without a real homework set, carry that through
  896   my $forced_field = [];
  897   $forced_field = ['sourceFilePath' =>  $r->param("sourceFilePath")] if
  898     ($set->set_id eq 'Undefined_Set');
  899   if ($authz->hasPermissions($user, "modify_problem_sets")) {
  900     my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
  901       courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id);
  902     my $editorURL = $self->systemLink($editorPage, params=>$forced_field);
  903     $editorLink = CGI::p(CGI::a({href=>$editorURL,target =>'WW_Editor'}, "Edit this problem"));
  904   }
  905 
  906   ##### translation errors? #####
  907 
  908   if ($pg->{flags}->{error_flag}) {
  909     if ($authz->hasPermissions($user, "view_problem_debugging_info")) {
  910       print $self->errorOutput($pg->{errors}, $pg->{body_text});
  911     } else {
  912       print $self->errorOutput($pg->{errors}, "You do not have permission to view the details of this error.");
  913     }
  914     print $editorLink;
  915     return "";
  916   }
  917 
  918   ##### answer processing #####
  919   debug("begin answer processing");
  920   # if answers were submitted:
  921   my $scoreRecordedMessage;
  922   my $pureProblem;
  923   if ($submitAnswers) {
  924     # get a "pure" (unmerged) UserProblem to modify
  925     # this will be undefined if the problem has not been assigned to this user
  926     $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
  927     if (defined $pureProblem) {
  928       # store answers in DB for sticky answers
  929       my %answersToStore;
  930       my %answerHash = %{ $pg->{answers} };
  931       $answersToStore{$_} = $self->{formFields}->{$_}  #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values.  Don't use it!!
  932         foreach (keys %answerHash);
  933 
  934       # There may be some more answers to store -- one which are auxiliary entries to a primary answer.  Evaluating
  935       # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
  936       # however we need to store them.  Fortunately they are still in the input form.
  937       my @extra_answer_names  = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
  938       $answersToStore{$_} = $self->{formFields}->{$_} foreach  (@extra_answer_names);
  939 
  940       # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
  941       my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
  942       my $answerString = encodeAnswers(%answersToStore,
  943          @answer_order);
  944 
  945       # store last answer to database
  946       $problem->last_answer($answerString);
  947       $pureProblem->last_answer($answerString);
  948       $db->putUserProblem($pureProblem);
  949 
  950       # store state in DB if it makes sense
  951       if ($will{recordAnswers}) {
  952         $problem->status($pg->{state}->{recorded_score});
  953         $problem->sub_status($pg->{state}->{sub_recorded_score});
  954         $problem->attempted(1);
  955         $problem->num_correct($pg->{state}->{num_of_correct_ans});
  956         $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  957         $pureProblem->status($pg->{state}->{recorded_score});
  958         $pureProblem->sub_status($pg->{state}->{sub_recorded_score});
  959         $pureProblem->attempted(1);
  960         $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
  961         $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  962         if ($db->putUserProblem($pureProblem)) {
  963           $scoreRecordedMessage = "Your score was recorded.";
  964         } else {
  965           $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
  966         }
  967         # write to the transaction log, just to make sure
  968         writeLog($self->{ce}, "transaction",
  969           $problem->problem_id."\t".
  970           $problem->set_id."\t".
  971           $problem->user_id."\t".
  972           $problem->source_file."\t".
  973           $problem->value."\t".
  974           $problem->max_attempts."\t".
  975           $problem->problem_seed."\t".
  976           $pureProblem->status."\t".
  977           $pureProblem->attempted."\t".
  978           $pureProblem->last_answer."\t".
  979           $pureProblem->num_correct."\t".
  980           $pureProblem->num_incorrect
  981         );
  982       } else {
  983         if (before($set->open_date) or after($set->due_date)) {
  984           $scoreRecordedMessage = "Your score was not recorded because this homework set is closed.";
  985         } else {
  986           $scoreRecordedMessage = "Your score was not recorded.";
  987         }
  988       }
  989     } else {
  990       $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
  991     }
  992   }
  993 
  994   # logging student answers
  995 
  996   my $answer_log    = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
  997   if ( defined($answer_log ) and defined($pureProblem)) {
  998     if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) {
  999             my $answerString = ""; my $scores = "";
 1000       my %answerHash = %{ $pg->{answers} };
 1001       # FIXME  this is the line 552 error.  make sure original student ans is defined.
 1002       # The fact that it is not defined is probably due to an error in some answer evaluator.
 1003       # But I think it is useful to suppress this error message in the log.
 1004       foreach (sortByName(undef, keys %answerHash)) {
 1005         my $orig_ans = $answerHash{$_}->{original_student_ans};
 1006         my $student_ans = defined $orig_ans ? $orig_ans : '';
 1007         $answerString  .= $student_ans."\t";
 1008         $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0";
 1009       }
 1010       $answerString = '' unless defined($answerString); # insure string is defined.
 1011       writeCourseLog($self->{ce}, "answer_log",
 1012               join("",
 1013             '|', $problem->user_id,
 1014             '|', $problem->set_id,
 1015             '|', $problem->problem_id,
 1016             '|', $scores, "\t",
 1017             time(),"\t",
 1018             $answerString,
 1019           ),
 1020       );
 1021 
 1022     }
 1023   }
 1024 
 1025   debug("end answer processing");
 1026 
 1027   ##### output #####
 1028   # custom message for editor
 1029   if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) {
 1030     if ($editMode eq "temporaryFile") {
 1031       print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file));
 1032     } elsif ($editMode eq "savedFile") {
 1033       # taken care of in the initialization phase
 1034     }
 1035   }
 1036   print CGI::start_div({class=>"problemHeader"});
 1037 
 1038 
 1039 
 1040   # attempt summary
 1041   #FIXME -- the following is a kludge:  if showPartialCorrectAnswers is negative don't show anything.
 1042   # until after the due date
 1043   # do I need to check $will{showCorrectAnswers} to make preflight work??
 1044   if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) {
 1045     # print this if user submitted answers OR requested correct answers
 1046 
 1047     print $self->attemptResults($pg, 1,
 1048       $will{showCorrectAnswers},
 1049       $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
 1050   } elsif ($checkAnswers) {
 1051     # print this if user previewed answers
 1052     print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br();
 1053     print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
 1054       # show attempt answers
 1055       # show correct answers if asked
 1056       # show attempt results (correctness)
 1057       # show attempt previews
 1058   } elsif ($previewAnswers) {
 1059     # print this if user previewed answers
 1060     print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
 1061       # show attempt answers
 1062       # don't show correct answers
 1063       # don't show attempt results (correctness)
 1064       # show attempt previews
 1065   }
 1066 
 1067   print CGI::end_div();
 1068 
 1069   # main form
 1070   print "\n";
 1071   print CGI::start_form(-method=>"POST", -action=> $r->uri,-name=>"problemMainForm", onsubmit=>"submitAction()");
 1072   print $self->hidden_authen_fields;
 1073   print "\n";
 1074   print CGI::start_div({class=>"problem"});
 1075   print CGI::p($pg->{body_text});
 1076   print CGI::p(CGI::b("Note: "). CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
 1077   print $editorLink; # this is empty unless it is appropriate to have an editor link.
 1078   print CGI::end_div();
 1079 
 1080   print CGI::start_p();
 1081 
 1082   if ($can{showCorrectAnswers}) {
 1083     print CGI::checkbox(
 1084       -name    => "showCorrectAnswers",
 1085       -checked => $will{showCorrectAnswers},
 1086       -label   => "Show correct answers",
 1087       -value   => 1,
 1088     );
 1089   }
 1090   if ($can{showHints}) {
 1091     print CGI::div({style=>"color:red"},
 1092       CGI::checkbox(
 1093         -name    => "showHints",
 1094         -checked => $will{showHints},
 1095         -label   => "Show Hints",
 1096         -value   =>1,
 1097       )
 1098     );
 1099   }
 1100   if ($can{showSolutions}) {
 1101     print CGI::checkbox(
 1102       -name    => "showSolutions",
 1103       -checked => $will{showSolutions},
 1104       -label   => "Show Solutions",
 1105       -value   => 1,
 1106     );
 1107   }
 1108 
 1109   if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) {
 1110     print CGI::br();
 1111   }
 1112 
 1113   print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers");
 1114   if ($can{checkAnswers}) {
 1115     print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers");
 1116   }
 1117   if ($can{getSubmitButton}) {
 1118     if ($user ne $effectiveUser) {
 1119       # if acting as a student, make it clear that answer submissions will
 1120       # apply to the student's records, not the professor's.
 1121       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser");
 1122     } else {
 1123       #print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>"alert('submit button clicked')");
 1124       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>"");
 1125       # FIXME  for unknown reasons the -onclick label seems to have to be there in order to allow the forms onsubmit to trigger
 1126       # WFT???
 1127     }
 1128   }
 1129 
 1130   print CGI::end_p();
 1131 
 1132   print CGI::start_div({class=>"scoreSummary"});
 1133 
 1134   # score summary
 1135   my $attempts = $problem->num_correct + $problem->num_incorrect;
 1136   my $attemptsNoun = $attempts != 1 ? "times" : "time";
 1137   my $problem_status    = $problem->status || 0;
 1138   my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number
 1139   my ($attemptsLeft, $attemptsLeftNoun);
 1140   if ($problem->max_attempts == -1) {
 1141     # unlimited attempts
 1142     $attemptsLeft = "unlimited";
 1143     $attemptsLeftNoun = "attempts";
 1144   } else {
 1145     $attemptsLeft = $problem->max_attempts - $attempts;
 1146     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
 1147   }
 1148 
 1149   my $setClosed = 0;
 1150   my $setClosedMessage;
 1151   if (before($set->open_date) or after($set->due_date)) {
 1152     $setClosed = 1;
 1153     if (before($set->open_date)) {
 1154       $setClosedMessage = "This homework set is not yet open.";
 1155     } elsif (after($set->due_date)) {
 1156       $setClosedMessage = "This homework set is closed.";
 1157     }
 1158   }
 1159   #if (before($set->open_date) or after($set->due_date)) {
 1160   # $setClosed = 1;
 1161   # $setClosedMessage = "This homework set is closed.";
 1162   # if ($authz->hasPermissions($user, "view_answers")) {
 1163   #   $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
 1164   # } else {
 1165   #   $setClosedMessage .= " Additional attempts will not be recorded.";
 1166   # }
 1167   #}
 1168   unless (defined( $pg->{state}->{state_summary_msg}) and $pg->{state}->{state_summary_msg}=~/\S/) {
 1169     my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)";
 1170     print CGI::p(join("",
 1171       $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
 1172       "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
 1173       $submitAnswers ?"You received a score of ".sprintf("%.0f%%", $pg->{result}->{score} * 100)." for this attempt.".CGI::br():'',
 1174       $problem->attempted
 1175         ? "Your overall recorded score is $lastScore.  $notCountedMessage" . CGI::br()
 1176         : "",
 1177       $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
 1178     ));
 1179   }else {
 1180     print CGI::p($pg->{state}->{state_summary_msg});
 1181   }
 1182   print CGI::end_div();
 1183 
 1184   # save state for viewOptions
 1185   print  CGI::hidden(
 1186          -name  => "showOldAnswers",
 1187          -value => $will{showOldAnswers}
 1188        ),
 1189 
 1190        CGI::hidden(
 1191          -name  => "displayMode",
 1192          -value => $self->{displayMode}
 1193        );
 1194   print( CGI::hidden(
 1195          -name    => 'editMode',
 1196          -value   => $self->{editMode},
 1197        )
 1198   ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
 1199 
 1200   # this is a security risk -- students can use this to find the source code for the problem
 1201 
 1202   my $permissionLevel = $db->getPermissionLevel($user)->permission;
 1203   my $professorPermissionLevel = $ce->{userRoles}->{professor};
 1204   print( CGI::hidden(
 1205           -name   => 'sourceFilePath',
 1206           -value  =>  $self->{problem}->{source_file}
 1207   ))  if defined($self->{problem}->{source_file}) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors
 1208 
 1209   print( CGI::hidden(
 1210           -name   => 'problemSeed',
 1211           -value  =>  $r->param("problemSeed")
 1212   ))  if defined($r->param("problemSeed")) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors
 1213 
 1214 
 1215   # end of main form
 1216   print CGI::endform();
 1217 
 1218   print  CGI::start_div({class=>"problemFooter"});
 1219 
 1220   ## arguments for answer inspection button
 1221   #my $prof_url = $ce->{webworkURLs}->{oldProf};
 1222   #my $webworkURL = $ce->{webworkURLs}->{root};
 1223   #my $cgi_url = $prof_url;
 1224   #$cgi_url=~ s|/[^/]*$||;  # clip profLogin.pl
 1225   #my $authen_args = $self->url_authen_args();
 1226   #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
 1227 
 1228   my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
 1229     courseID => $courseName);
 1230   my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
 1231 
 1232   # print answer inspection button
 1233   if ($authz->hasPermissions($user, "view_answers")) {
 1234     print "\n",
 1235       CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"WW_Info"),"\n",
 1236       $self->hidden_authen_fields,"\n",
 1237       CGI::hidden(-name => 'courseID',  -value=>$courseName), "\n",
 1238       CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
 1239       CGI::hidden(-name => 'setID',  -value=>$problem->set_id), "\n",
 1240       CGI::hidden(-name => 'studentUser',    -value=>$problem->user_id), "\n",
 1241       CGI::p( {-align=>"left"},
 1242         CGI::submit(-name => 'action',  -value=>'Show Past Answers')
 1243       ), "\n",
 1244       CGI::endform();
 1245   }
 1246 
 1247 
 1248   print $self->feedbackMacro(
 1249     module             => __PACKAGE__,
 1250     set                => $self->{set}->set_id,
 1251     problem            => $problem->problem_id,
 1252     displayMode        => $self->{displayMode},
 1253     showOldAnswers     => $will{showOldAnswers},
 1254     showCorrectAnswers => $will{showCorrectAnswers},
 1255     showHints          => $will{showHints},
 1256     showSolutions      => $will{showSolutions},
 1257     pg_object          => $pg,
 1258   );
 1259 
 1260   print CGI::end_div();
 1261 
 1262   # debugging stuff
 1263   if (0) {
 1264     print
 1265       CGI::hr(),
 1266       CGI::h2("debugging information"),
 1267       CGI::h3("form fields"),
 1268       ref2string($self->{formFields}),
 1269       CGI::h3("user object"),
 1270       ref2string($self->{user}),
 1271       CGI::h3("set object"),
 1272       ref2string($set),
 1273       CGI::h3("problem object"),
 1274       ref2string($problem),
 1275       CGI::h3("PG object"),
 1276       ref2string($pg, {'WeBWorK::PG::Translator' => 1});
 1277   }
 1278   debug("leaving body of Problem.pm");
 1279   return "";
 1280 }
 1281 
 1282 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9