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

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

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