File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.76.2.5: download - view: text, annotated - select for diffs
Sat Oct 24 19:37:20 2020 UTC (3 years, 8 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_5, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
- For 2.11
  Backport 1.80

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

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