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

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

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