File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.61: download - view: text, annotated - select for diffs
Sat Apr 17 22:48:56 2010 UTC (14 years, 2 months ago) by www
Branches: MAIN
CVS tags: PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD
Allow user to select probem when called context-free

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

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