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

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

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