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

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

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