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

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

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