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

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

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