Annotation of loncom/interface/statistics/lonstathelpers.pm, revision 1.42

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

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