File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.52: download - view: text, annotated - select for diffs
Tue Feb 14 16:05:46 2006 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding a mode to do analysis of grading events for bridge tasks

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstathelpers.pm,v 1.52 2006/02/14 16:05:46 albertel Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: ####################################################
   28: ####################################################
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonstathelpers - helper routines used by statistics
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This module provides a place to consolidate much of the statistics 
   39: routines that are needed across multiple statistics functions.
   40: 
   41: =head1 OVERVIEW
   42: 
   43: =over 4
   44: 
   45: =cut
   46: 
   47: ####################################################
   48: ####################################################
   49: package Apache::lonstathelpers;
   50: 
   51: use strict;
   52: use Apache::lonnet;
   53: use Apache::loncommon();
   54: use Apache::lonhtmlcommon();
   55: use Apache::loncoursedata();
   56: use Apache::lonstatistics;
   57: use Apache::lonlocal;
   58: use HTML::Entities();
   59: use Time::Local();
   60: use Spreadsheet::WriteExcel();
   61: use GDBM_File;
   62: use Storable qw(freeze thaw);
   63: 
   64: ####################################################
   65: ####################################################
   66: 
   67: =pod
   68: 
   69: =item &render_resource($resource)
   70: 
   71: Input: a navmaps resource
   72: 
   73: Retunrs: a scalar containing html for a rendering of the problem
   74: within a table.
   75: 
   76: =cut
   77: 
   78: ####################################################
   79: ####################################################
   80: sub render_resource {
   81:     my ($resource) = @_;
   82:     ##
   83:     ## Render the problem
   84:     my ($base) = ($resource->src =~ m|^(.*/)[^/]*$|);
   85:     $base="http://".$ENV{'SERVER_NAME'}.$base;
   86:     my ($src,$symb)=($resource->src,&Apache::lonnet::escape($resource->symb));
   87:     my $rendered_problem = &Apache::lonnet::ssi_body($src.'?symb='.$symb);
   88:     $rendered_problem =~ s/<\s*form\s*/<nop /g;
   89:     $rendered_problem =~ s|(<\s*/form\s*>)|<\/nop>|g;
   90:     return '<table bgcolor="ffffff"><tr><td>'.
   91:         '<base href="'.$base.'" />'.
   92:         $rendered_problem.
   93:         '</td></tr></table>';
   94: }
   95: 
   96: ####################################################
   97: ####################################################
   98: 
   99: =pod
  100: 
  101: =item &get_resources
  102: 
  103: =cut
  104: 
  105: ####################################################
  106: ####################################################
  107: sub get_resources {
  108:     my ($navmap,$sequence) = @_;
  109:     my @resources = $navmap->retrieveResources($sequence,
  110:                                                sub { shift->is_problem(); },
  111:                                                0,0,0);
  112:     return @resources;
  113: }
  114: 
  115: ####################################################
  116: ####################################################
  117: 
  118: =pod
  119: 
  120: =item &problem_selector($AcceptedResponseTypes)
  121: 
  122: Input: scalar containing regular expression which matches response
  123: types to show.  '.' will yield all, '(option|radiobutton)' will match
  124: all option response and radiobutton problems.
  125: 
  126: Returns: A string containing html for a table which lists the sequences
  127: and their contents.  A radiobutton is provided for each problem.
  128: Skips 'survey' problems.
  129: 
  130: =cut
  131: 
  132: ####################################################
  133: ####################################################
  134: sub problem_selector {
  135:     my ($AcceptedResponseTypes,$sequence_addendum) = @_;
  136:     my $Str;
  137:     $Str = "\n<table>\n";
  138:     my $rb_count =0;
  139:     my ($navmap,@sequences) = 
  140:         &Apache::lonstatistics::selected_sequences_with_assessments('all');
  141:     return $navmap if (! ref($navmap)); # error
  142:     foreach my $seq (@sequences) {
  143:         my $seq_str = '';
  144:         foreach my $res (&get_resources($navmap,$seq)) {
  145:             foreach my $part (@{$res->parts}) {
  146:                 my @response_ids   = $res->responseIds($part);
  147:                 my @response_types = $res->responseType($part);
  148:                 for (my $i=0;$i<scalar(@response_types);$i++){
  149:                     my $respid = $response_ids[$i];
  150:                     my $resptype = $response_types[$i];
  151:                     if ($resptype =~ m/$AcceptedResponseTypes/) {
  152:                         my $value = &make_target_id({symb=>$res->symb,
  153:                                                      part=>$part,
  154:                                                      respid=>$respid,
  155:                                                      resptype=>$resptype});
  156:                         my $checked = '';
  157:                         if ($env{'form.problemchoice'} eq $value) {
  158:                             $checked = 'checked ';
  159:                         }
  160:                         my $title = $res->compTitle;
  161:                         if (! defined($title) || $title eq '') {
  162:                             ($title) = ($res->src =~ m:/([^/]*)$:);
  163:                         }
  164:                         $seq_str .= '<tr>'.
  165:                             qq{<td><input type="radio" id="$rb_count" name="problemchoice" value="$value" $checked /></td>}.
  166:                             '<td><label for="'.$rb_count.'">'.$resptype.'</label></td>'.
  167:                             '<td><label for="'.$rb_count.'">'.$title.'</label>';
  168:                         if (scalar(@response_ids) > 1) {
  169:                             $seq_str .= &mt('response').' '.$respid;
  170:                         }
  171:                         my $link = $res->src.'?symb='.
  172:                             &Apache::lonnet::escape($res->symb);
  173:                         $seq_str .= ('&nbsp;'x2).
  174:                             qq{<a target="preview" href="$link">view</a>};
  175:                         $seq_str .= "</td></tr>\n";
  176:                         $rb_count++;
  177:                     }
  178:                 }
  179:             }
  180:         }
  181:         if ($seq_str ne '') {
  182:             $Str .= '<tr><td>&nbsp</td>'.
  183:                 '<td colspan="2"><b>'.$seq->compTitle.'</b></td>'.
  184:                 "</tr>\n".$seq_str;
  185:             if (defined($sequence_addendum)) {
  186:                 $Str .= '<tr>'.
  187:                     ('<td>&nbsp</td>'x2).
  188:                     '<td align="right">'.$sequence_addendum.'</td>'.
  189:                     "</tr>\n";
  190:             }
  191:         }
  192:     }
  193:     $Str .= "</table>\n";
  194:     return $Str;
  195: }
  196: 
  197: ####################################################
  198: ####################################################
  199: 
  200: =pod
  201: 
  202: =item &MultipleProblemSelector($navmap,$selected,$inputname)
  203: 
  204: Generate HTML with checkboxes for problem selection.
  205: 
  206: Input: 
  207: 
  208: $navmap: a navmap object.  If undef, navmaps will be called to create a
  209: new object.
  210: 
  211: $selected: Scalar, Array, or hash reference of currently selected items.
  212: 
  213: $inputname: The name of the form elements to use for the checkboxs.
  214: 
  215: Returns: A string containing html for a table which lists the sequences
  216: and their contents.  A checkbox is provided for each problem.
  217: 
  218: =cut
  219: 
  220: ####################################################
  221: ####################################################
  222: sub MultipleProblemSelector {
  223:     my ($navmap,$inputname,$formname)=@_;
  224:     my $cid = $env{'request.course.id'};
  225:     my $Str;
  226:     # Massage the input as needed.
  227:     if (! defined($navmap)) {
  228:         $navmap = Apache::lonnavmaps::navmap->new();
  229:         if (! defined($navmap)) {
  230:             $Str .= 
  231:                 '<h1>'.&mt('Error: cannot process course structure').'</h1>';
  232:             return $Str;
  233:         }
  234:     }
  235:     my $selected = {map { ($_,1) } (&get_selected_symbs($inputname))};
  236:     # Header
  237:     $Str .= <<"END";
  238: <script language="JavaScript" type="text/javascript">
  239:     function checkall(value,seqid) {
  240:         for (i=0; i<document.forms.$formname.elements.length; i++) {
  241:             ele = document.forms.$formname.elements[i];
  242:             if (ele.name == '$inputname') {
  243:                 if (seqid != null) {
  244:                     itemid = document.forms.$formname.elements[i].id;
  245:                     thing = itemid.split(':');
  246:                     if (thing[0] == seqid) {
  247:                         document.forms.$formname.elements[i].checked=value;
  248:                     }
  249:                 } else {
  250:                     document.forms.$formname.elements[i].checked=value;
  251:                 }
  252:             }
  253:         }
  254:     }
  255: </script>
  256: END
  257:     $Str .= 
  258:         '<a href="javascript:checkall(true)">'.&mt('Select All').'</a>'.
  259:         ('&nbsp;'x4).
  260:         '<a href="javascript:checkall(false)">'.&mt('Unselect All').'</a>';
  261:     $Str .= $/.'<table>'.$/;
  262:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  263:     my $sequence_string;
  264:     my $seq_id = 0;
  265:     my @Accumulator = (&new_accumulator($env{'course.'.$cid.'.description'},
  266:                                         '',
  267:                                         '',
  268:                                         $seq_id++,
  269:                                         $inputname));
  270:     my @Sequence_Data;
  271:     while (my $curRes = $iterator->next()) {
  272:         if ($curRes == $iterator->END_MAP) {
  273:             if (ref($Accumulator[-1]) eq 'CODE') {
  274:                 my $old_accumulator = pop(@Accumulator);
  275:                 push(@Sequence_Data,&{$old_accumulator}());
  276:             }
  277:         } elsif ($curRes == $iterator->BEGIN_MAP) {
  278:             # Not much to do here.
  279:         }
  280:         next if (! ref($curRes));
  281:         if ($curRes->is_map) {
  282:             push(@Accumulator,&new_accumulator($curRes->compTitle,
  283:                                                $curRes->src,
  284:                                                $curRes->symb,
  285:                                                $seq_id++,
  286:                                                $inputname));
  287:         } elsif ($curRes->is_problem) {
  288:             if (@Accumulator && $Accumulator[-1] ne '') {
  289:                 &{$Accumulator[-1]}($curRes,
  290:                                     exists($selected->{$curRes->symb}));
  291:             }
  292:         }
  293:     }
  294:     my $course_seq = pop(@Sequence_Data);
  295:     foreach my $seq ($course_seq,@Sequence_Data) {
  296:         #my $seq = pop(@Sequence_Data);
  297:         next if (! defined($seq) || ref($seq) ne 'HASH');
  298:         $Str.= '<tr><td colspan="2">'.
  299:             '<b>'.$seq->{'title'}.'</b>'.('&nbsp;'x2).
  300:             '<a href="javascript:checkall(true,'.$seq->{'id'}.')">'.
  301:                                   &mt('Select').'</a>'.('&nbsp;'x2).
  302:             '<a href="javascript:checkall(false,'.$seq->{'id'}.')">'.
  303:                                   &mt('Unselect').'</a>'.('&nbsp;'x2).
  304:             '</td></tr>'.$/;
  305:         $Str.= $seq->{'html'};
  306:     }
  307:     $Str .= '</table>'.$/;
  308:     return $Str;
  309: }
  310: 
  311: sub new_accumulator {
  312:     my ($title,$src,$symb,$seq_id,$inputname) = @_;
  313:     my $target;
  314:     my $item_id=0;
  315:     return 
  316:         sub {
  317:             if (@_) { 
  318:                 my ($res,$checked) = @_;
  319:                 $target.='<tr><td><label>'.
  320:                     '<input type="checkbox" name="'.$inputname.'" ';
  321:                 if ($checked) {
  322:                     $target .= 'checked ';
  323:                 }
  324:                 $target .= 'id="'.$seq_id.':'.$item_id++.'" ';
  325:                 $target.= 
  326:                     'value="'.&Apache::lonnet::escape($res->symb).'" />'.
  327:                     '&nbsp;'.$res->compTitle.'</label>'.
  328:                     ('&nbsp;'x2).'<a target="preview" '.
  329:                     'href="'.$res->src.'?symb='.
  330:                          &Apache::lonnet::escape($res->symb).'">view</a>'.
  331:                     '</td></tr>'.$/;
  332:             } else { 
  333:                 if (defined($target)) {
  334:                     return { title => $title,
  335:                              symb  => $symb,
  336:                              src   => $src,
  337:                              id    => $seq_id,
  338:                              html  => $target, }; 
  339:                 }
  340:                 return undef;
  341:             }
  342:         };
  343: }
  344: 
  345: sub get_selected_symbs {
  346:     my ($inputfield) = @_;
  347:     my $field = 'form.'.$inputfield;
  348:     my @symbs = (map {
  349:                      &Apache::lonnet::unescape($_);
  350:                      } &Apache::loncommon::get_env_multiple($field));
  351:     return @symbs;
  352: }
  353: 
  354: ####################################################
  355: ####################################################
  356: 
  357: =pod
  358: 
  359: =item &make_target_id($target)
  360: 
  361: Inputs: Hash ref with the following entries:
  362:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  363:     $target->{'resptype'}.
  364: 
  365: Returns: A string, suitable for a form parameter, which uniquely identifies
  366: the problem, part, and response to do statistical analysis on.
  367: 
  368: Used by Apache::lonstathelpers::ProblemSelector().
  369: 
  370: =cut
  371: 
  372: ####################################################
  373: ####################################################
  374: sub make_target_id {
  375:     my ($target) = @_;
  376:     my $id = &Apache::lonnet::escape($target->{'symb'}).':'.
  377:              &Apache::lonnet::escape($target->{'part'}).':'.
  378:              &Apache::lonnet::escape($target->{'respid'}).':'.
  379:              &Apache::lonnet::escape($target->{'resptype'});
  380:     return $id;
  381: }
  382: 
  383: ####################################################
  384: ####################################################
  385: 
  386: =pod
  387: 
  388: =item &get_target_from_id($id)
  389: 
  390: Inputs: $id, a scalar string from Apache::lonstathelpers::make_target_id().
  391: 
  392: Returns: A hash reference, $target, containing the following keys:
  393:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  394:     $target->{'resptype'}.
  395: 
  396: =cut
  397: 
  398: ####################################################
  399: ####################################################
  400: sub get_target_from_id {
  401:     my ($id) = @_;
  402:     if (! ref($id)) {
  403:         my ($symb,$part,$respid,$resptype) = split(':',$id);
  404:         return ({ symb     => &Apache::lonnet::unescape($symb),
  405:                   part     => &Apache::lonnet::unescape($part),
  406:                   respid   => &Apache::lonnet::unescape($respid),
  407:                   resptype => &Apache::lonnet::unescape($resptype)});
  408:     } elsif (ref($id) eq 'ARRAY') {
  409:         my @Return;
  410:         foreach my $selected (@$id) {
  411:             my ($symb,$part,$respid,$resptype) = split(':',$selected);
  412:             push(@Return,{ symb     => &Apache::lonnet::unescape($symb),
  413:                            part     => &Apache::lonnet::unescape($part),
  414:                            respid   => &Apache::lonnet::unescape($respid),
  415:                            resptype => &Apache::lonnet::unescape($resptype)});
  416:         }
  417:         return \@Return;
  418:     }
  419: }
  420: 
  421: ####################################################
  422: ####################################################
  423: 
  424: =pod
  425: 
  426: =item &get_prev_curr_next($target,$AcceptableResponseTypes,$granularity)
  427: 
  428: Determine the problem parts or responses preceeding and following the
  429: current resource.
  430: 
  431: Inputs: $target (see &Apache::lonstathelpers::get_target_from_id())
  432:   $AcceptableResponseTypes, regular expression matching acceptable
  433:                             response types,
  434:   $granularity, either 'part', 'response', 'part_survey', or 'part_task'
  435: 
  436: Returns: three hash references, $prev, $curr, $next, which refer to the
  437: preceeding, current, or following problem parts or responses, depending
  438: on the value of $granularity.  Values of undef indicate there is no
  439: previous or next part/response.  A value of undef for all three indicates
  440: there was no match found to the current part/resource.
  441: 
  442: The hash references contain the following keys:
  443:     symb, part, resource
  444: 
  445: If $granularity eq 'response', the following ADDITIONAL keys will be present:
  446:     respid, resptype
  447: 
  448: =cut
  449: 
  450: ####################################################
  451: ####################################################
  452: sub get_prev_curr_next {
  453:     my ($target,$AcceptableResponseTypes,$granularity) = @_;
  454:     #
  455:     # Build an array with the data we need to search through
  456:     my @Resource;
  457:     my ($navmap,@sequences) = 
  458:         &Apache::lonstatistics::selected_sequences_with_assessments('all');
  459:     return $navmap if (! ref($navmap));
  460:     foreach my $seq (@sequences) {
  461:         my @resources = &get_resources($navmap,$seq);
  462:         foreach my $res (@resources) {
  463:             foreach my $part (@{$res->parts}) {
  464:                 if ($res->is_survey($part) && ($granularity eq 'part_survey')){
  465:                     push (@Resource,
  466:                           { symb     => $res->symb,
  467:                             part     => $part,
  468:                             resource => $res,
  469:                         } );
  470: 		} elsif ($res->is_task($part) && ($granularity eq 'part_task')){
  471:                     push (@Resource,
  472:                           { symb     => $res->symb,
  473:                             part     => $part,
  474:                             resource => $res,
  475:                         } );
  476:                 } elsif ($granularity eq 'part') {
  477:                     push (@Resource,
  478:                           { symb     => $res->symb,
  479:                             part     => $part,
  480:                             resource => $res,
  481:                         } );
  482:                 } elsif ($granularity eq 'response') {
  483:                     my @response_ids   = $res->responseIds($part);
  484:                     my @response_types = $res->responseType($part);
  485:                     for (my $i=0;
  486:                          $i<scalar(@response_ids);
  487:                          $i++){
  488:                         my $respid   = $response_ids[$i];
  489:                         my $resptype = $response_types[$i];
  490:                         next if ($resptype !~ m/$AcceptableResponseTypes/);
  491:                         push (@Resource,
  492:                               { symb     => $res->symb,
  493:                                 part     => $part,
  494:                                 respid   => $respid,
  495:                                 resptype => $resptype,
  496:                                 resource => $res,
  497:                                 } );
  498:                     }
  499:                 }
  500:             }
  501:         }
  502:     }
  503:     #
  504:     # Get the index of the current situation
  505:     my $curr_idx;
  506:     for ($curr_idx=0;$curr_idx<$#Resource;$curr_idx++) {
  507:         my $curr_item = $Resource[$curr_idx];
  508:         if ($granularity =~ /^(part|part_survey|part_task)$/) {
  509:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  510:                 $curr_item->{'part'} eq $target->{'part'}) {
  511:                 last;
  512:             }
  513:         } elsif ($granularity eq 'response') {
  514:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  515:                 $curr_item->{'part'} eq $target->{'part'} &&
  516:                 $curr_item->{'respid'} eq $target->{'respid'} &&
  517:                 $curr_item->{'resptype'} eq $target->{'resptype'}) {
  518:                 last;
  519:             }
  520:         }
  521:     }
  522:     my $curr_item = $Resource[$curr_idx];
  523:     if ($granularity =~ /^(part|part_survey|part_task)$/) {
  524:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  525:             $curr_item->{'part'}     ne $target->{'part'}) {
  526:             # bogus symb - return nothing
  527:             return (undef,undef,undef);
  528:         }
  529:     } elsif ($granularity eq 'response') {
  530:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  531:             $curr_item->{'part'}     ne $target->{'part'} ||
  532:             $curr_item->{'respid'}   ne $target->{'respid'} ||
  533:             $curr_item->{'resptype'} ne $target->{'resptype'}){
  534:             # bogus symb - return nothing
  535:             return (undef,undef,undef);
  536:         }
  537:     }
  538:     #
  539:     # Now just pick up the data we need
  540:     my ($prev,$curr,$next);
  541:     if ($curr_idx == 0) {
  542:         $prev = undef;
  543:         $curr = $Resource[$curr_idx  ];
  544:         $next = $Resource[$curr_idx+1];
  545:     } elsif ($curr_idx == $#Resource) {
  546:         $prev = $Resource[$curr_idx-1];
  547:         $curr = $Resource[$curr_idx  ];
  548:         $next = undef;
  549:     } else {
  550:         $prev = $Resource[$curr_idx-1];
  551:         $curr = $Resource[$curr_idx  ];
  552:         $next = $Resource[$curr_idx+1];
  553:     }
  554:     return ($navmap,$prev,$curr,$next);
  555: }
  556: 
  557: 
  558: #####################################################
  559: #####################################################
  560: 
  561: =pod
  562: 
  563: =item GetStudentAnswers($r,$problem,$Students)
  564: 
  565: Determines the correct answer for a set of students on a given problem.
  566: The students answers are stored in the student hashes pointed to by the
  567: array @$Students under the key 'answer'.
  568: 
  569: Inputs: $r
  570: $problem: hash reference containing the keys 'resource', 'part', and 'respid'.
  571: $Students: reference to array containing student hashes (need 'username', 
  572:     'domain').  
  573: 
  574: Returns: nothing 
  575: 
  576: =cut
  577: 
  578: #####################################################
  579: #####################################################
  580: sub GetStudentAnswers {
  581:     my ($r,$problem,$Students,$formname,$inputname) = @_;
  582:     my %answers;
  583:     my $status_type;
  584:     if (defined($formname)) {
  585:         $status_type = 'inline';
  586:     } else {
  587:         $status_type = 'popup';
  588:     }    
  589:     my $c = $r->connection();
  590:     my %Answers;
  591:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  592:                                       $problem->{'part'},
  593:                                       $problem->{'respid'});
  594:     # Read in the cache (if it exists) before we start timing things.
  595:     &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
  596:     # Open progress window
  597:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  598:         ($r,'Student Answer Compilation Status',
  599:          'Student Answer Compilation Progress', scalar(@$Students),
  600:          $status_type,undef,$formname,$inputname);
  601:     $r->rflush();
  602:     foreach my $student (@$Students) {
  603:         last if ($c->aborted());
  604:         my $sname = $student->{'username'};
  605:         my $sdom = $student->{'domain'};
  606:         my $answer = &Apache::lonstathelpers::get_student_answer
  607:             ($resource,$sname,$sdom,$partid,$respid);
  608:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  609:                                                  &mt('last student'));
  610:         $answers{$answer}++;
  611:         $student->{'answer'} = $answer;
  612:     }
  613:     &Apache::lonstathelpers::write_analysis_cache();
  614:     return if ($c->aborted());
  615:     $r->rflush();
  616:     # close progress window
  617:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  618:     return \%answers;
  619: }
  620: 
  621: #####################################################
  622: #####################################################
  623: 
  624: =pod
  625: 
  626: =item analyze_problem_as_student
  627: 
  628: Analyzes a homework problem for a student
  629: 
  630: Inputs: $resource: a resource object
  631:         $sname, $sdom, $partid, $respid
  632: 
  633: Returns: the problem analysis hash
  634: 
  635: =cut
  636: 
  637: #####################################################
  638: #####################################################
  639: sub analyze_problem_as_student {
  640:     my ($resource,$sname,$sdom) = @_;
  641:     if (ref($resource) ne 'HASH') {
  642:         my $res = $resource;
  643:         $resource = { 'src' => $res->src,
  644:                       'symb' => $res->symb,
  645:                       'parts' => $res->parts };
  646:         foreach my $part (@{$resource->{'parts'}}) {
  647:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  648:                 [$res->responseIds($part)];
  649:         }
  650:     }
  651:     my $url = $resource->{'src'};
  652:     my $symb = $resource->{'symb'};
  653:     my $analysis = &get_from_analysis_cache($sname,$sdom,$symb);
  654:     if (! defined($analysis)) {
  655:         my $courseid = $env{'request.course.id'};
  656:         my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
  657:                                             'grade_domain' => $sdom,
  658:                                             'grade_username' => $sname,
  659:                                             'grade_symb' => $symb,
  660:                                             'grade_courseid' => $courseid));
  661:         (my $garbage,$analysis)=split(/_HASH_REF__/,$Answ,2);
  662:         &store_analysis($sname,$sdom,$symb,$analysis);
  663:     }
  664:     my %Answer=&Apache::lonnet::str2hash($analysis);
  665:     #
  666:     return \%Answer;
  667: }
  668: 
  669: #####################################################
  670: #####################################################
  671: 
  672: =pod
  673: 
  674: =item get_student_answer
  675: 
  676: Analyzes a homework problem for a particular student and returns the correct 
  677: answer.  Attempts to put together an answer for problem types 
  678: that do not natively support it.
  679: 
  680: Inputs: $resource: a resource object (from navmaps or hash from loncoursedata)
  681:         $sname, $sdom, $partid, $respid
  682: 
  683: Returns: $answer
  684: 
  685: If $partid and $respid are specified, $answer is simply a scalar containing
  686: the correct answer for the response.
  687: 
  688: If $partid or $respid are undefined, $answer will be a hash reference with
  689: keys $partid.'.'.$respid.'.answer'.
  690: 
  691: =cut
  692: 
  693: #####################################################
  694: #####################################################
  695: sub get_student_answer {
  696:     my ($resource,$sname,$sdom,$partid,$respid) = @_;
  697:     #
  698:     if (ref($resource) ne 'HASH') {
  699:         my $res = $resource;
  700:         $resource = { 'src' => $res->src,
  701:                       'symb' => $res->symb,
  702:                       'parts' => $res->parts };
  703:         foreach my $part (@{$resource->{'parts'}}) {
  704:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  705:                 [$res->responseIds($part)];
  706:         }
  707:     }
  708:     #
  709:     my $analysis = 
  710:         &analyze_problem_as_student($resource,$sname,$sdom);
  711:     my $answer;
  712:     foreach my $partid (@{$resource->{'parts'}}) {
  713:         my $partdata = $resource->{'partdata'}->{$partid};
  714:         foreach my $respid (@{$partdata->{'ResponseIds'}}) {
  715:             my $prefix = $partid.'.'.$respid;
  716:             my $key = $prefix.'.answer';
  717:             $answer->{$partid}->{$respid} = 
  718:                 &get_answer($prefix,$key,%$analysis);
  719:         }
  720:     }
  721:     my $returnvalue;
  722:     if (! defined($partid)) {
  723:         $returnvalue = $answer;
  724:     } elsif (! defined($respid)) {
  725:         $returnvalue = $answer->{$partid};
  726:     } else {
  727:         $returnvalue = $answer->{$partid}->{$respid};
  728:     }
  729:     return $returnvalue;
  730: }
  731: 
  732: sub get_answer {
  733:     my ($prefix,$key,%Answer) = @_;
  734:     my $returnvalue;
  735:     if (exists($Answer{$key})) {
  736:         my $student_answer = $Answer{$key}->[0];
  737:         if (! defined($student_answer)) {
  738:             $student_answer = $Answer{$key}->[1];
  739:         }
  740:         $returnvalue = $student_answer;
  741:     } else {
  742:         if (exists($Answer{$prefix.'.shown'})) {
  743:             # The response has foils
  744:             my %values;
  745:             while (my ($k,$v) = each(%Answer)) {
  746:                 next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
  747:                 my $foilname = $2;
  748:                 $values{$foilname}=$v;
  749:             }
  750:             foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
  751:                 if (ref($values{$foil}) eq 'ARRAY') {
  752:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  753:                         join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
  754:                 } else {
  755:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  756:                         &HTML::Entities::encode($values{$foil},'<>&"').'&';
  757:                 }
  758:             }
  759:             $returnvalue =~ s/ /\%20/g;
  760:             chop ($returnvalue);
  761:         }
  762:     }
  763:     return $returnvalue;
  764: }
  765: 
  766: #####################################################
  767: #####################################################
  768: 
  769: =pod
  770: 
  771: =item Caching routines
  772: 
  773: =over 4
  774: 
  775: =item &load_analysis_cache($symb)
  776: 
  777: Loads the cache for the given symb into memory from disk.  
  778: Requires the cache filename be set.  
  779: Only should be called by &ensure_proper_cache.
  780: 
  781: =cut
  782: 
  783: #####################################################
  784: #####################################################
  785: {
  786:     my $cache_filename = undef;
  787:     my $current_symb = undef;
  788:     my %cache;
  789: 
  790: sub load_analysis_cache {
  791:     my ($symb) = @_;
  792:     return if (! defined($cache_filename));
  793:     if (! defined($current_symb) || $current_symb ne $symb) {
  794:         undef(%cache);
  795:         my $storedstring;
  796:         my %cache_db;
  797:         if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
  798:             $storedstring = $cache_db{&Apache::lonnet::escape($symb)};
  799:             untie(%cache_db);
  800:         }
  801:         if (defined($storedstring)) {
  802:             %cache = %{thaw($storedstring)};
  803:         }
  804:     }
  805:     return;
  806: }
  807: 
  808: #####################################################
  809: #####################################################
  810: 
  811: =pod
  812: 
  813: =item &get_from_analysis_cache($sname,$sdom,$symb,$partid,$respid)
  814: 
  815: Returns the appropriate data from the cache, or undef if no data exists.
  816: 
  817: =cut
  818: 
  819: #####################################################
  820: #####################################################
  821: sub get_from_analysis_cache {
  822:     my ($sname,$sdom,$symb) = @_;
  823:     &ensure_proper_cache($symb);
  824:     my $returnvalue;
  825:     if (exists($cache{$sname.':'.$sdom})) {
  826:         $returnvalue = $cache{$sname.':'.$sdom};
  827:     } else {
  828:         $returnvalue = undef;
  829:     }
  830:     return $returnvalue;
  831: }
  832: 
  833: #####################################################
  834: #####################################################
  835: 
  836: =pod
  837: 
  838: =item &write_analysis_cache($symb)
  839: 
  840: Writes the in memory cache to disk so that it can be read in with
  841: &load_analysis_cache($symb).
  842: 
  843: =cut
  844: 
  845: #####################################################
  846: #####################################################
  847: sub write_analysis_cache {
  848:     return if (! defined($current_symb) || ! defined($cache_filename));
  849:     my %cache_db;
  850:     my $key = &Apache::lonnet::escape($current_symb);
  851:     if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
  852:         my $storestring = freeze(\%cache);
  853:         $cache_db{$key}=$storestring;
  854:         $cache_db{$key.'.time'}=time;
  855:         untie(%cache_db);
  856:     }
  857:     undef(%cache);
  858:     undef($current_symb);
  859:     undef($cache_filename);
  860:     return;
  861: }
  862: 
  863: #####################################################
  864: #####################################################
  865: 
  866: =pod
  867: 
  868: =item &ensure_proper_cache($symb)
  869: 
  870: Called to make sure we have the proper cache set up.  This is called
  871: prior to every analysis lookup.
  872: 
  873: =cut
  874: 
  875: #####################################################
  876: #####################################################
  877: sub ensure_proper_cache {
  878:     my ($symb) = @_;
  879:     my $cid = $env{'request.course.id'};
  880:     my $new_filename =  '/home/httpd/perl/tmp/'.
  881:         'problemanalysis_'.$cid.'_analysis_cache.db';
  882:     if (! defined($cache_filename) ||
  883:         $cache_filename ne $new_filename ||
  884:         ! defined($current_symb)   ||
  885:         $current_symb ne $symb) {
  886:         $cache_filename = $new_filename;
  887:         # Notice: $current_symb is not set to $symb until after the cache is
  888:         # loaded.  This is what tells &load_analysis_cache to load in a new
  889:         # symb cache.
  890:         &load_analysis_cache($symb);
  891:         $current_symb = $symb;
  892:     }
  893: }
  894: 
  895: #####################################################
  896: #####################################################
  897: 
  898: =pod
  899: 
  900: =item &store_analysis($sname,$sdom,$symb,$partid,$respid,$dataset)
  901: 
  902: Stores the analysis data in the in memory cache.
  903: 
  904: =cut
  905: 
  906: #####################################################
  907: #####################################################
  908: sub store_analysis {
  909:     my ($sname,$sdom,$symb,$dataset) = @_;
  910:     return if ($symb ne $current_symb);
  911:     $cache{$sname.':'.$sdom}=$dataset;
  912:     return;
  913: }
  914: 
  915: }
  916: #####################################################
  917: #####################################################
  918: 
  919: =pod
  920: 
  921: =back
  922: 
  923: =cut
  924: 
  925: #####################################################
  926: #####################################################
  927: 
  928: ##
  929: ## The following is copied from datecalc1.pl, part of the 
  930: ## Spreadsheet::WriteExcel CPAN module.
  931: ##
  932: ##
  933: ######################################################################
  934: #
  935: # Demonstration of writing date/time cells to Excel spreadsheets,
  936: # using UNIX/Perl time as source of date/time.
  937: #
  938: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
  939: #
  940: ######################################################################
  941: #
  942: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
  943: # measured in seconds.
  944: #
  945: # An Excel file can use exactly one of two different date/time systems.
  946: # In these systems, a floating point number represents the number of days
  947: # (and fractional parts of the day) since a start point. The floating point
  948: # number is referred to as a 'serial'.
  949: # The two systems ('1900' and '1904') use different starting points:
  950: #  '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
  951: #          a leap year - see:
  952: #            http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
  953: #          for the excuse^H^H^H^H^H^Hreason.
  954: #  '1904'; '1.00' is 2 Jan 1904.
  955: #
  956: # The '1904' system is the default for Apple Macs. Windows versions of
  957: # Excel have the option to use the '1904' system.
  958: #
  959: # Note that Visual Basic's "DateSerial" function does NOT erroneously
  960: # regard 1900 as a leap year, and thus its serials do not agree with
  961: # the 1900 serials of Excel for dates before 1 Mar 1900.
  962: #
  963: # Note that StarOffice (at least at version 5.2) does NOT erroneously
  964: # regard 1900 as a leap year, and thus its serials do not agree with
  965: # the 1900 serials of Excel for dates before 1 Mar 1900.
  966: #
  967: ######################################################################
  968: #
  969: # Calculation description
  970: # =======================
  971: #
  972: # 1900 system
  973: # -----------
  974: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
  975: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  976: # were leap years with an extra day.
  977: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
  978: # 1 Jan 1970.
  979: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
  980: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
  981: #
  982: # 1904 system
  983: # -----------
  984: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
  985: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  986: # were leap years with an extra day.
  987: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
  988: # 1 Jan 1970.
  989: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
  990: #
  991: ######################################################################
  992: #
  993: # Copyright (c) 2000, Andrew Benham.
  994: # This program is free software. It may be used, redistributed and/or
  995: # modified under the same terms as Perl itself.
  996: #
  997: # Andrew Benham, adsb@bigfoot.com
  998: # London, United Kingdom
  999: # 11 Nov 2000
 1000: #
 1001: ######################################################################
 1002: #-----------------------------------------------------------
 1003: # calc_serial()
 1004: #
 1005: # Called with (up to) 2 parameters.
 1006: #   1.  Unix timestamp.  If omitted, uses current time.
 1007: #   2.  GMT flag. Set to '1' to return serial in GMT.
 1008: #       If omitted, returns serial in appropriate timezone.
 1009: #
 1010: # Returns date/time serial according to $DATE_SYSTEM selected
 1011: #-----------------------------------------------------------
 1012: sub calc_serial {
 1013:     # Use 1900 date system on all platforms other than Apple Mac (for which
 1014:     # use 1904 date system).
 1015:     my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
 1016:     my $time = (defined $_[0]) ? $_[0] : time();
 1017:     my $gmtflag = (defined $_[1]) ? $_[1] : 0;
 1018:     #
 1019:     # Divide timestamp by number of seconds in a day.
 1020:     # This gives a date serial with '0' on 1 Jan 1970.
 1021:     my $serial = $time / 86400;
 1022:     #
 1023:     # Adjust the date serial by the offset appropriate to the
 1024:     # currently selected system (1900/1904).
 1025:     if ($DATE_SYSTEM == 0) {        # use 1900 system
 1026:         $serial += 25569;
 1027:     } else {                        # use 1904 system
 1028:         $serial += 24107;
 1029:     }
 1030:     #
 1031:     unless ($gmtflag) {
 1032:         # Now have a 'raw' serial with the right offset. But this
 1033:         # gives a serial in GMT, which is false unless the timezone
 1034:         # is GMT. We need to adjust the serial by the appropriate
 1035:         # timezone offset.
 1036:         # Calculate the appropriate timezone offset by seeing what
 1037:         # the differences between localtime and gmtime for the given
 1038:         # time are.
 1039:         #    
 1040:         my @gmtime = gmtime($time);
 1041:         my @ltime  = localtime($time);
 1042:         #
 1043:         # For the first 7 elements of the two arrays, adjust the
 1044:         # date serial where the elements differ.
 1045:         for (0 .. 6) {
 1046:             my $diff = $ltime[$_] - $gmtime[$_];
 1047:             if ($diff) {
 1048:                 $serial += _adjustment($diff,$_);
 1049:             }
 1050:         }
 1051:     }
 1052:     #
 1053:     # Perpetuate the error that 1900 was a leap year by decrementing
 1054:     # the serial if we're using the 1900 system and the date is prior to
 1055:     # 1 Mar 1900. This has the effect of making serial value '60'
 1056:     # 29 Feb 1900.
 1057:     #
 1058:     # This fix only has any effect if UNIX/Perl time on the platform
 1059:     # can represent 1900. Many can't.
 1060:     #
 1061:     unless ($DATE_SYSTEM) {
 1062:         $serial-- if ($serial < 61);    # '61' is 1 Mar 1900
 1063:     }
 1064:     return $serial;
 1065: }
 1066: 
 1067: sub _adjustment {
 1068:     # Based on the difference in the localtime/gmtime array elements
 1069:     # number, return the adjustment required to the serial.
 1070:     #
 1071:     # We only look at some elements of the localtime/gmtime arrays:
 1072:     #    seconds    unlikely to be different as all known timezones
 1073:     #               have an offset of integral multiples of 15 minutes,
 1074:     #               but it's easy to do.
 1075:     #    minutes    will be different for timezone offsets which are
 1076:     #               not an exact number of hours.
 1077:     #    hours      very likely to be different.
 1078:     #    weekday    will differ when localtime/gmtime difference
 1079:     #               straddles midnight.
 1080:     #
 1081:     # Assume that difference between localtime and gmtime is less than
 1082:     # 5 days, then don't have to do maths for day of month, month number,
 1083:     # year number, etc...
 1084:     #
 1085:     my ($delta,$element) = @_;
 1086:     my $adjust = 0;
 1087:     #
 1088:     if ($element == 0) {            # Seconds
 1089:         $adjust = $delta/86400;         # 60 * 60 * 24
 1090:     } elsif ($element == 1) {       # Minutes
 1091:         $adjust = $delta/1440;          # 60 * 24
 1092:     } elsif ($element == 2) {       # Hours
 1093:         $adjust = $delta/24;            # 24
 1094:     } elsif ($element == 6) {       # Day of week number
 1095:         # Catch difference straddling Sat/Sun in either direction
 1096:         $delta += 7 if ($delta < -4);
 1097:         $delta -= 7 if ($delta > 4);
 1098:         #    
 1099:         $adjust = $delta;
 1100:     }
 1101:     return $adjust;
 1102: }
 1103: 
 1104: ###########################################################
 1105: ###########################################################
 1106: 
 1107: =pod
 1108: 
 1109: =item get_problem_data
 1110: 
 1111: Returns a data structure describing the problem.
 1112: 
 1113: Inputs: $url
 1114: 
 1115: Returns: %Partdata
 1116: 
 1117: =cut
 1118: 
 1119: ## note: we must force each foil and option to not begin or end with
 1120: ##       spaces as they are stored without such data.
 1121: ##
 1122: ###########################################################
 1123: ###########################################################
 1124: sub get_problem_data {
 1125:     my ($url) = @_;
 1126:     my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
 1127:     (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
 1128:     my %Answer;
 1129:     %Answer=&Apache::lonnet::str2hash($Answ);
 1130:     my %Partdata;
 1131:     foreach my $part (@{$Answer{'parts'}}) {
 1132:         while (my($key,$value) = each(%Answer)) {
 1133:             #
 1134:             # Logging code:
 1135:             if (0) {
 1136:                 &Apache::lonnet::logthis($part.' got key "'.$key.'"');
 1137:                 if (ref($value) eq 'ARRAY') {
 1138:                     &Apache::lonnet::logthis('    @'.join(',',@$value));
 1139:                 } else {
 1140:                     &Apache::lonnet::logthis('    '.$value);
 1141:                 }
 1142:             }
 1143:             # End of logging code
 1144:             next if ($key !~ /^\Q$part\E/);
 1145:             $key =~ s/^\Q$part\E\.//;
 1146:             if (ref($value) eq 'ARRAY') {
 1147:                 if ($key eq 'options') {
 1148:                     $Partdata{$part}->{'_Options'}=$value;
 1149:                 } elsif ($key eq 'concepts') {
 1150:                     $Partdata{$part}->{'_Concepts'}=$value;
 1151:                 } elsif ($key eq 'items') {
 1152:                     $Partdata{$part}->{'_Items'}=$value;
 1153:                 } elsif ($key =~ /^concept\.(.*)$/) {
 1154:                     my $concept = $1;
 1155:                     foreach my $foil (@$value) {
 1156:                         $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
 1157:                                                                       $concept;
 1158:                     }
 1159:                 } elsif ($key =~ /^(unit|incorrect|answer|ans_low|ans_high|str_type)$/) {
 1160:                     $Partdata{$part}->{$key}=$value;
 1161:                 }
 1162:             } else {
 1163:                 if ($key=~ /^foil\.text\.(.*)$/) {
 1164:                     my $foil = $1;
 1165:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
 1166:                     $value =~ s/(\s*$|^\s*)//g;
 1167:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
 1168:                 } elsif ($key =~ /^foil\.value\.(.*)$/) {
 1169:                     my $foil = $1;
 1170:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
 1171:                 } elsif ($key eq 'answercomputed') {
 1172:                     $Partdata{$part}->{'answercomputed'} = $value;
 1173:                 }
 1174:             }
 1175:         }
 1176:     }
 1177:     # Further debugging code
 1178:     if (0) {
 1179:         &Apache::lonnet::logthis('lonstathelpers::get_problem_data');
 1180:         &log_hash_ref(\%Partdata);
 1181:     }
 1182:     return %Partdata;
 1183: }
 1184: 
 1185: sub log_array_ref {
 1186:     my ($arrayref,$prefix) = @_;
 1187:     return if (ref($arrayref) ne 'ARRAY');
 1188:     if (! defined($prefix)) { $prefix = ''; };
 1189:     foreach my $v (@$arrayref) {
 1190:         if (ref($v) eq 'ARRAY') {
 1191:             &log_array_ref($v,$prefix.'  ');
 1192:         } elsif (ref($v) eq 'HASH') {
 1193:             &log_hash_ref($v,$prefix.'  ');
 1194:         } else {
 1195:             &Apache::lonnet::logthis($prefix.'"'.$v.'"');
 1196:         }
 1197:     }
 1198: }
 1199: 
 1200: sub log_hash_ref {
 1201:     my ($hashref,$prefix) = @_;
 1202:     return if (ref($hashref) ne 'HASH');
 1203:     if (! defined($prefix)) { $prefix = ''; };
 1204:     while (my ($k,$v) = each(%$hashref)) {
 1205:         if (ref($v) eq 'ARRAY') {
 1206:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = array');
 1207:             &log_array_ref($v,$prefix.'  ');
 1208:         } elsif (ref($v) eq 'HASH') {
 1209:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = hash');
 1210:             &log_hash_ref($v,$prefix.'  ');
 1211:         } else {
 1212:             &Apache::lonnet::logthis($prefix.'"'.$k.'" => "'.$v.'"');
 1213:         }
 1214:     }
 1215: }
 1216: ####################################################
 1217: ####################################################
 1218: 
 1219: =pod
 1220: 
 1221: =item &limit_by_time()
 1222: 
 1223: =cut
 1224: 
 1225: ####################################################
 1226: ####################################################
 1227: sub limit_by_time_form {
 1228:     my $Starttime_form = '';
 1229:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1230:         ('limitby_startdate');
 1231:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1232:         ('limitby_enddate');
 1233:     if (! defined($endtime)) {
 1234:         $endtime = time;
 1235:     }
 1236:     if (! defined($starttime)) {
 1237:         $starttime = $endtime - 60*60*24*7;
 1238:     }
 1239:     my $state;
 1240:     if (&limit_by_time()) {
 1241:         $state = '';
 1242:     } else {
 1243:         $state = 'disabled';
 1244:     }
 1245:     my $startdateform = &Apache::lonhtmlcommon::date_setter
 1246:         ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
 1247:     my $enddateform = &Apache::lonhtmlcommon::date_setter
 1248:         ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
 1249:     my $Str;
 1250:     $Str .= '<script language="Javascript" >';
 1251:     $Str .= 'function toggle_limitby_activity(state) {';
 1252:     $Str .= '    if (state) {';
 1253:     $Str .= '        limitby_startdate_enable();';
 1254:     $Str .= '        limitby_enddate_enable();';
 1255:     $Str .= '    } else {';
 1256:     $Str .= '        limitby_startdate_disable();';
 1257:     $Str .= '        limitby_enddate_disable();';
 1258:     $Str .= '    }';    
 1259:     $Str .= '}';
 1260:     $Str .= '</script>';
 1261:     $Str .= '<fieldset>';
 1262:     my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
 1263:     if (&limit_by_time()) {
 1264:         $timecheckbox .= ' checked ';
 1265:     } 
 1266:     $timecheckbox .= 'OnChange="javascript:toggle_limitby_activity(this.checked);" ';
 1267:     $timecheckbox .= ' />';
 1268:     $Str .= '<legend><label>'.&mt('[_1] Limit by time',$timecheckbox).'</label></legend>';
 1269:     $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
 1270:     $Str .= &mt('&nbsp;End Time: [_1]',$enddateform).'<br />';
 1271:     $Str .= '</fieldset>';
 1272:     return $Str;
 1273: }
 1274: 
 1275: sub limit_by_time {
 1276:     if (exists($env{'form.limit_by_time'}) &&
 1277:         $env{'form.limit_by_time'} ne '' ) {
 1278:         return 1;
 1279:     } else {
 1280:         return 0;
 1281:     }
 1282: }
 1283: 
 1284: sub get_time_limits {
 1285:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1286:         ('limitby_startdate');
 1287:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1288:         ('limitby_enddate');
 1289:     return ($starttime,$endtime);
 1290: }
 1291: 
 1292: ####################################################
 1293: ####################################################
 1294: 
 1295: =pod
 1296: 
 1297: =item &manage_caches
 1298: 
 1299: Inputs: $r, apache request object
 1300: 
 1301: Returns: An array of scalars containing html for buttons.
 1302: 
 1303: =cut
 1304: 
 1305: ####################################################
 1306: ####################################################
 1307: sub manage_caches {
 1308:     my ($r,$formname,$inputname,$update_message) = @_;
 1309:     &Apache::loncoursedata::clear_internal_caches();
 1310:     my $sectionkey = 
 1311:         join(',',
 1312:              map {
 1313:                      &Apache::lonnet::escape($_);
 1314:                  } sort(&Apache::lonstatistics::get_selected_sections())
 1315:              );
 1316:     my $statuskey = $Apache::lonstatistics::enrollment_status;
 1317:     if (exists($env{'form.ClearCache'}) || 
 1318:         exists($env{'form.updatecaches'}) || 
 1319:         (exists($env{'form.firstrun'}) && $env{'form.firstrun'} ne 'no') ||
 1320:         (exists($env{'form.prevsection'}) &&
 1321:             $env{'form.prevsection'} ne $sectionkey) ||
 1322:         (exists($env{'form.prevenrollstatus'}) &&
 1323:             $env{'form.prevenrollstatus'} ne $statuskey)
 1324:         ) {
 1325:         if (defined($update_message)) {
 1326:             $r->print($update_message);
 1327:         }
 1328:         if (0) {
 1329:             &Apache::lonnet::logthis('Updating mysql student data caches');
 1330:         }
 1331:         &gather_full_student_data($r,$formname,$inputname);
 1332:     }
 1333:     #
 1334:     my @Buttons = 
 1335:         ('<input type="submit" name="ClearCache" '.
 1336:              'value="'.&mt('Clear Caches').'" />',
 1337:          '<input type="submit" name="updatecaches" '.
 1338:              'value="'.&mt('Update Caches').'" />'.
 1339:          &Apache::loncommon::help_open_topic('Statistics_Cache'),
 1340:          '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
 1341:          '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
 1342:          );
 1343:     #
 1344:     if (! exists($env{'form.firstrun'})) {
 1345:         $r->print('<input type="hidden" name="firstrun" value="yes" />');
 1346:     } else {
 1347:         $r->print('<input type="hidden" name="firstrun" value="no" />');
 1348:     }
 1349:     #
 1350:     return @Buttons;
 1351: }
 1352: 
 1353: sub gather_full_student_data {
 1354:     my ($r,$formname,$inputname) = @_;
 1355:     my $status_type;
 1356:     if (defined($formname)) {
 1357:         $status_type = 'inline';
 1358:     } else {
 1359:         $status_type = 'popup';
 1360:     }
 1361:     my $c = $r->connection();
 1362:     #
 1363:     &Apache::loncoursedata::clear_internal_caches();
 1364:     #
 1365:     my @Students = @Apache::lonstatistics::Students;
 1366:     #
 1367:     # Open the progress window
 1368:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1369:         ($r,&mt('Student Data Compilation Status'),
 1370:          &mt('Student Data Compilation Progress'), scalar(@Students),
 1371:          $status_type,undef,$formname,$inputname);
 1372:     #
 1373:     while (my $student = shift @Students) {
 1374:         return if ($c->aborted());
 1375:         my $status = &Apache::loncoursedata::ensure_current_full_data
 1376:             ($student->{'username'},$student->{'domain'},
 1377:              $env{'request.course.id'});
 1378:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1379:                                                  &mt('last student'));
 1380:     }
 1381:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1382:     $r->rflush();
 1383:     return;
 1384: }
 1385: 
 1386: ####################################################
 1387: ####################################################
 1388: 
 1389: =pod
 1390: 
 1391: =item &submission_report_form
 1392: 
 1393: Input: The originating reportSelected value for the current stats page.
 1394: 
 1395: Output: Scalar containing HTML with needed form elements and a link to 
 1396: the student submission reports page.
 1397: 
 1398: =cut
 1399: 
 1400: ####################################################
 1401: ####################################################
 1402: sub submission_report_form {
 1403:     my ($original_report) = @_;
 1404:     # Note: In the link below we change the reportSelected value.  If
 1405:     # the user hits the 'back' button on the browser after getting their
 1406:     # student submissions report, this value may still be around.  So we
 1407:     # output a script block to set it properly.  If the $original_report
 1408:     # value is unset, you are just asking for trouble.
 1409:     if (! defined($original_report)) {
 1410:         &Apache::lonnet::logthis
 1411:             ('someone called lonstathelpers::submission_report_form without '.
 1412:              ' enough input.');
 1413:     }
 1414:     my $html = $/.
 1415:         '<script type="Text/JavaScript">'.
 1416:         "document.Statistics.reportSelected.value='$original_report';".
 1417:         '</script>'.
 1418:         '<input type="hidden" name="correctans" value="true" />'.
 1419:         '<input type="hidden" name="prob_status" value="true" />'.
 1420:         '<input type="hidden" name="all_sub" value="true" />';
 1421:     my $output_selector = $/.'<select name="output">'.$/;
 1422:     foreach ('HTML','Excel','CSV') {
 1423:         $output_selector .= '    <option value="'.lc($_).'"';
 1424:         if ($env{'form.output'} eq lc($_)) {
 1425:             $output_selector .= ' selected ';
 1426:         }
 1427:         $output_selector .='>'.&mt($_).'</option>'.$/;
 1428:     } 
 1429:     $output_selector .= '</select>'.$/;
 1430:     my $link = '<a href="javascript:'.
 1431:        q{document.Statistics.reportSelected.value='student_submission_reports';}.
 1432:        'document.Statistics.submit();">';
 1433:     $html.= &mt('View data as [_1] [_2]go[_3]',$output_selector,
 1434:                 $link,'</a>').$/;
 1435:     return $html
 1436: }
 1437: 
 1438: ####################################################
 1439: ####################################################
 1440: 
 1441: =pod
 1442: 
 1443: =back
 1444: 
 1445: =cut
 1446: 
 1447: ####################################################
 1448: ####################################################
 1449: 
 1450: 1;
 1451: 
 1452: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>