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

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

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