File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.60: download - view: text, annotated - select for diffs
Tue Jun 17 17:47:54 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added <br /> after 'clear caches' button.
Fixed bad columns on scores display.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentassessment.pm,v 1.60 2003/06/17 17:47:54 matthew 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: # LON-CAPA is free software; you can redistribute it and/or modify
    9: # it under the terms of the GNU General Public License as published by
   10: # the Free Software Foundation; either version 2 of the License, or
   11: # (at your option) any later version.
   12: #
   13: # LON-CAPA is distributed in the hope that it will be useful,
   14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16: # GNU General Public License for more details.
   17: #
   18: # You should have received a copy of the GNU General Public License
   19: # along with LON-CAPA; if not, write to the Free Software
   20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21: #
   22: # /home/httpd/html/adm/gpl.txt
   23: #
   24: # http://www.lon-capa.org/
   25: #
   26: # (Navigate problems for statistical reports
   27: #
   28: #######################################################
   29: #######################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: lonstudentassessment
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Presents assessment data about a student or a group of students.
   40: 
   41: =head1 Subroutines
   42: 
   43: =over 4 
   44: 
   45: =cut
   46: 
   47: #######################################################
   48: #######################################################
   49: 
   50: package Apache::lonstudentassessment;
   51: 
   52: use strict;
   53: use Apache::lonstatistics;
   54: use Apache::lonhtmlcommon;
   55: use Apache::loncoursedata;
   56: use Apache::lonnet; # for logging porpoises
   57: use Spreadsheet::WriteExcel;
   58: 
   59: #######################################################
   60: #######################################################
   61: =pod
   62: 
   63: =item Package Variables
   64: 
   65: =over 4
   66: 
   67: =item $Statistics Hash ref to store student data.  Indexed by symb,
   68:       contains hashes with keys 'score' and 'max'.
   69: 
   70: =cut
   71: 
   72: #######################################################
   73: #######################################################
   74: 
   75: my $Statistics;
   76: 
   77: #######################################################
   78: #######################################################
   79: 
   80: =pod
   81: 
   82: =item $show_links 'yes' or 'no' for linking to student performance data
   83: 
   84: =item $output_mode 'html', 'excel', or 'csv' for output mode
   85: 
   86: =item $show 'all', 'totals', or 'scores' determines how much data is output
   87: 
   88: =item $data  determines what performance data is shown
   89: 
   90: =item $datadescription A short description of the output data selected.
   91: 
   92: =item $base 'tries' or 'scores' determines the base of the performance shown
   93: 
   94: =item $single_student_mode evaluates to true if we are showing only one
   95: student.
   96: 
   97: =cut
   98: 
   99: #######################################################
  100: #######################################################
  101: my $show_links;
  102: my $output_mode;
  103: my $data;
  104: my $base;
  105: my $datadescription;
  106: my $single_student_mode;
  107: 
  108: #######################################################
  109: #######################################################
  110: # End of package variable declarations
  111: 
  112: =pod
  113: 
  114: =back
  115: 
  116: =cut
  117: 
  118: #######################################################
  119: #######################################################
  120: 
  121: =pod
  122: 
  123: =item &BuildStudentAssessmentPage()
  124: 
  125: Inputs: 
  126: 
  127: =over 4
  128: 
  129: =item $r Apache Request
  130: 
  131: =item $c Apache Connection 
  132: 
  133: =back
  134: 
  135: =cut
  136: 
  137: #######################################################
  138: #######################################################
  139: sub BuildStudentAssessmentPage {
  140:     my ($r,$c)=@_;
  141:     undef($Statistics);
  142:     $single_student_mode = 1 if ($ENV{'form.SelectedStudent'});
  143:     if ($ENV{'form.selectstudent'}) {
  144:         &Apache::lonstatistics::DisplayClasslist($r);
  145:         return;
  146:     }
  147:     #
  148:     # Print out the HTML headers for the interface
  149:     #    This also parses the output mode selector
  150:     #    This step must *always* be done.
  151:     $r->print(&CreateInterface());
  152:     $r->print('<input type="hidden" name="notfirstrun" value="true" />');
  153:     $r->print('<input type="hidden" name="sort" value="'.
  154:               $ENV{'form.sort'}.'" />');
  155:     $r->rflush();
  156:     #
  157:     if (! exists($ENV{'form.notfirstrun'}) && ! $single_student_mode) {
  158:         return;
  159:     }
  160:     #
  161:     my $initialize     = \&html_initialize;
  162:     my $output_student = \&html_outputstudent;
  163:     my $finish         = \&html_finish;
  164:     #
  165:     if ($output_mode eq 'excel') {
  166:         $initialize     = \&excel_initialize;
  167:         $output_student = \&excel_outputstudent;
  168:         $finish         = \&excel_finish;
  169:     } elsif ($output_mode eq 'csv') {
  170:         $initialize     = \&csv_initialize;
  171:         $output_student = \&csv_outputstudent;
  172:         $finish         = \&csv_finish;
  173:     }
  174:     #
  175:     if($c->aborted()) {  return ; }
  176:     #
  177:     # Determine which students we want to look at
  178:     my @Students;
  179:     if ($single_student_mode) {
  180:         @Students = (&Apache::lonstatistics::current_student());
  181:         $r->print(&next_and_previous_buttons());
  182:         $r->rflush();
  183:     } else {
  184:         @Students = @Apache::lonstatistics::Students;
  185:     }
  186:     #
  187:     # Perform generic initialization tasks
  188:     #       Since we use lonnet::EXT to retrieve problem weights,
  189:     #       to ensure current data we must clear the caches out.
  190:     #       This makes sure that parameter changes at the student level
  191:     #       are immediately reflected in the chart.
  192:     &Apache::lonnet::clear_EXT_cache_status();
  193:     #
  194:     # Call the initialize routine selected above
  195:     $initialize->($r);
  196:     foreach my $student (@Students) {
  197:         if($c->aborted()) { 
  198:             $finish->($r);
  199:             return ; 
  200:         }
  201:         # Call the output_student routine selected above
  202:         $output_student->($r,$student);
  203:     }
  204:     # Call the "finish" routine selected above
  205:     $finish->($r);
  206:     #
  207:     return;
  208: }
  209: 
  210: #######################################################
  211: #######################################################
  212: sub next_and_previous_buttons {
  213:     my $Str = '';
  214:     $Str .= '<input type="hidden" name="SelectedStudent" value="'.
  215:         $ENV{'form.SelectedStudent'}.'" />';
  216:     #
  217:     # Build the previous student link
  218:     my $previous = &Apache::lonstatistics::previous_student();
  219:     my $previousbutton = '';
  220:     if (defined($previous)) {
  221:         my $sname = $previous->{'username'}.':'.$previous->{'domain'};
  222:         $previousbutton .= '<input type="button" value="'.
  223:             'Previous Student ('.
  224:             $previous->{'username'}.'@'.$previous->{'domain'}.')'.
  225:             '" onclick="document.Statistics.SelectedStudent.value='.
  226:             "'".$sname."'".';'.
  227:             'document.Statistics.submit();" />';
  228:     } else {
  229:         $previousbutton .= '<input type="button" value="'.
  230:             'Previous student (none)'.'" />';
  231:     }
  232:     #
  233:     # Build the next student link
  234:     my $next = &Apache::lonstatistics::next_student();
  235:     my $nextbutton = '';
  236:     if (defined($next)) {
  237:         my $sname = $next->{'username'}.':'.$next->{'domain'};
  238:         $nextbutton .= '<input type="button" value="'.
  239:             'Next Student ('.
  240:             $next->{'username'}.'@'.$next->{'domain'}.')'.
  241:             '" onclick="document.Statistics.SelectedStudent.value='.
  242:             "'".$sname."'".';'.
  243:             'document.Statistics.submit();" />';
  244:     } else {
  245:         $nextbutton .= '<input type="button" value="'.
  246:             'Next student (none)'.'" />';
  247:     }
  248:     #
  249:     # Build the 'all students' button
  250:     my $all = '';
  251:     $all .= '<input type="button" value="All Students" '.
  252:             '" onclick="document.Statistics.SelectedStudent.value='.
  253:             "''".';'.'document.Statistics.submit();" />';
  254:     $Str .= $previousbutton.('&nbsp;'x5).$all.('&nbsp;'x5).$nextbutton;
  255:     return $Str;
  256: }
  257: 
  258: #######################################################
  259: #######################################################
  260: 
  261: sub get_student_fields_to_show {
  262:     my @to_show = @Apache::lonstatistics::SelectedStudentData;
  263:     foreach (@to_show) {
  264:         if ($_ eq 'all') {
  265:             @to_show = @Apache::lonstatistics::StudentDataOrder;
  266:             last;
  267:         }
  268:     }
  269:     return @to_show;
  270: }
  271: 
  272: #######################################################
  273: #######################################################
  274: 
  275: =pod
  276: 
  277: =item &CreateInterface()
  278: 
  279: Called by &BuildStudentAssessmentPage to create the top part of the
  280: page which displays the chart.
  281: 
  282: Inputs: None
  283: 
  284: Returns:  A string containing the HTML for the headers and top table for 
  285: the chart page.
  286: 
  287: =cut
  288: 
  289: #######################################################
  290: #######################################################
  291: sub CreateInterface {
  292:     my $Str = '';
  293: #    $Str .= &CreateLegend();
  294:     $Str .= '<table cellspacing="5">'."\n";
  295:     $Str .= '<tr>';
  296:     $Str .= '<td align="center"><b>Sections</b></td>';
  297:     $Str .= '<td align="center"><b>Student Data</b></td>';
  298:     $Str .= '<td align="center"><b>Enrollment Status</b></td>';
  299:     $Str .= '<td align="center"><b>Sequences and Folders</b></td>';
  300:     $Str .= '<td align="center"><b>Output Format</b>'.
  301:         &Apache::loncommon::help_open_topic("Chart_Output_Formats").
  302:         '</td>';
  303:     $Str .= '<td align="center"><b>Output Data</b>'.
  304:         &Apache::loncommon::help_open_topic("Chart_Output_Data").
  305:         '</td>';
  306:     $Str .= '</tr>'."\n";
  307:     #
  308:     $Str .= '<tr><td align="center">'."\n";
  309:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  310:     $Str .= '</td><td align="center">';
  311:     my $only_seq_with_assessments = sub { 
  312:         my $s=shift;
  313:         if ($s->{'num_assess'} < 1) { 
  314:             return 0;
  315:         } else { 
  316:             return 1;
  317:         }
  318:     };
  319:     $Str .= &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',
  320:                                                       5,undef);
  321:     $Str .= '</td><td>'."\n";
  322:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
  323:     $Str .= '</td><td>'."\n";
  324:     $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
  325:                                               $only_seq_with_assessments);
  326:     $Str .= '</td><td>'."\n";
  327:     $Str .= &CreateAndParseOutputSelector();
  328:     $Str .= '</td><td>'."\n";
  329:     $Str .= &CreateAndParseOutputDataSelector();
  330:     $Str .= '</td></tr>'."\n";
  331:     $Str .= '</table>'."\n";
  332:     $Str .= '<input type="submit" value="Generate Chart" />';
  333:     $Str .= '&nbsp;'x5;
  334:     $Str .= '<input type="submit" name="selectstudent" '.
  335:                                   'value="Select One Student" />';
  336:     $Str .= '&nbsp;'x5;
  337:     $Str .= '<input type="submit" name="ClearCache" value="Clear Caches" />';
  338:     $Str .= '&nbsp;'x5.'<br />';
  339:     return $Str;
  340: }
  341: 
  342: #######################################################
  343: #######################################################
  344: 
  345: =pod
  346: 
  347: =item &CreateAndParseOutputSelector()
  348: 
  349: =cut
  350: 
  351: #######################################################
  352: #######################################################
  353: my @OutputOptions = 
  354:     ({ name  => 'HTML, with links',
  355:        value => 'html, with links',
  356:        description => 'Output HTML with each symbol linked to the problem '.
  357: 	   'which generated it.',
  358:        mode => 'html',
  359:        show_links => 'yes',
  360:        },
  361:      { name  => 'HTML, with all links',
  362:        value => 'html, with all links',
  363:        description => 'Output HTML with each symbol linked to the problem '.
  364: 	   'which generated it.  '.
  365:            'This includes links for unattempted problems.',
  366:        mode => 'html',
  367:        show_links => 'all',
  368:        },
  369:      { name  => 'HTML, without links',
  370:        value => 'html, without links',
  371:        description => 'Output HTML.  By not including links, the size of the'.
  372: 	   ' web page is greatly reduced.  If your browser crashes on the '.
  373: 	   'full display, try this.',
  374:        mode => 'html',
  375:        show_links => 'no',
  376:            },
  377:      { name  => 'Excel',
  378:        value => 'excel',
  379:        description => 'Output an Excel file (compatable with Excel 95).',
  380:        mode => 'excel',
  381:        show_links => 'no',
  382:    },
  383:      { name  => 'CSV',
  384:        value => 'csv',
  385:        description => 'Output a comma seperated values file suitable for '.
  386:            'import into a spreadsheet program.  Using this method as opposed '.
  387:            'to Excel output allows you to organize your data before importing'.
  388:            ' it into a spreadsheet program.',
  389:        mode => 'csv',
  390:        show_links => 'no',
  391:            },
  392:      );
  393: 
  394: sub OutputDescriptions {
  395:     my $Str = '';
  396:     $Str .= "<h2>Output Formats</h2>\n";
  397:     $Str .= "<dl>\n";
  398:     foreach my $outputmode (@OutputOptions) {
  399: 	$Str .="    <dt>".$outputmode->{'name'}."</dt>\n";
  400: 	$Str .="        <dd>".$outputmode->{'description'}."</dd>\n";
  401:     }
  402:     $Str .= "</dl>\n";
  403:     return $Str;
  404: }
  405: 
  406: sub CreateAndParseOutputSelector {
  407:     my $Str = '';
  408:     my $elementname = 'chartoutputmode';
  409:     #
  410:     # Format for output options is 'mode, restrictions';
  411:     my $selected = 'html, without links';
  412:     if (exists($ENV{'form.'.$elementname})) {
  413:         if (ref($ENV{'form.'.$elementname} eq 'ARRAY')) {
  414:             $selected = $ENV{'form.'.$elementname}->[0];
  415:         } else {
  416:             $selected = $ENV{'form.'.$elementname};
  417:         }
  418:     }
  419:     #
  420:     # Set package variables describing output mode
  421:     $show_links  = 'no';
  422:     $output_mode = 'html';
  423:     foreach my $option (@OutputOptions) {
  424:         next if ($option->{'value'} ne $selected);
  425:         $output_mode = $option->{'mode'};
  426:         $show_links  = $option->{'show_links'};
  427:     }
  428: 
  429:     #
  430:     # Build the form element
  431:     $Str = qq/<select size="5" name="$elementname">/;
  432:     foreach my $option (@OutputOptions) {
  433:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  434:         $Str .= " selected " if ($option->{'value'} eq $selected);
  435:         $Str .= ">".$option->{'name'}."<\/option>";
  436:     }
  437:     $Str .= "\n</select>";
  438:     return $Str;
  439: }
  440: 
  441: ##
  442: ## Data selector stuff
  443: ##
  444: my @OutputDataOptions =
  445:     (
  446:      { name  => 'Scores',
  447:        base  => 'scores',
  448:        value => 'scores',
  449:        shortdesc => 'Score on each Problem Part',
  450:        longdesc =>'The students score on each problem part, computed as'.
  451:            'the part weight * part awarded',
  452:        },
  453:      { name  => 'Scores Sum',
  454:        base  => 'scores',
  455:        value => 'sum only',
  456:        shortdesc => 'Sum of Scores on each Problem Part',
  457:        longdesc =>'The total of the scores of the student on each problem'.
  458:            ' part in the sequences or folders selected.',
  459:        },
  460:      { name  => 'Scores Sum & Maximums',
  461:        base  => 'scores',
  462:        value => 'sum and total',
  463:        shortdesc => 'Total Score and Maximum Possible for each '.
  464:            'Sequence or Folder',
  465:        longdesc => 'The score of each student as well as the '.
  466:            ' maximum possible on each Sequence or Folder.',
  467:        },
  468:      { name  => 'Scores Summary Table Only',
  469:        base  => 'scores',
  470:        value => 'final table scores',
  471:        shortdesc => 'Summary of Scores',
  472:        longdesc  => 'The average score on each sequence or folder for the '.
  473:            'selected students.',
  474:        },
  475:      { name  =>'Tries',
  476:        base  =>'tries',
  477:        value => 'tries',
  478:        shortdesc => 'Number of Tries before success on each Problem Part',
  479:        longdesc =>'The number of tries before success on each problem part.',
  480:        },
  481:      { name  =>'Parts Correct',
  482:        base  =>'tries',
  483:        value => 'parts correct',
  484:        shortdesc => 'Number of Problem Parts completed successfully.',
  485:        longdesc => 'The Number of Problem Parts completed successfully'.
  486:            ' on each sequence or folder.',
  487:        },
  488:      { name  =>'Parts Correct & Maximums',
  489:        base  =>'tries',
  490:        value => 'parts correct total',
  491:        shortdesc => 'Number of Problem Parts completed successfully.',
  492:        longdesc => 'The Number of Problem Parts completed successfully and '.
  493:            'the maximum possible for each student',
  494:        },
  495:      { name  => 'Parts Summary Table Only',
  496:        base  => 'tries',
  497:        value => 'final table parts',
  498:        shortdesc => 'Summary of Parts Correct',
  499:        longdesc  => 'A summary table of the average number of problem parts '.
  500:            'students were able to get correct on each sequence.',
  501:        },
  502:      );
  503: 
  504: sub HTMLifyOutputDataDescriptions {
  505:     my $Str = '';
  506:     $Str .= "<h2>Output Data</h2>\n";
  507:     $Str .= "<dl>\n";
  508:     foreach my $option (@OutputDataOptions) {
  509:         $Str .= '    <dt>'.$option->{'name'}.'</dt>';
  510:         $Str .= '<dd>'.$option->{'longdesc'}.'</dd>'."\n";
  511:     }
  512:     $Str .= "</dl>\n";
  513:     return $Str;
  514: }
  515: 
  516: sub CreateAndParseOutputDataSelector {
  517:     my $Str = '';
  518:     my $elementname = 'chartoutputdata';
  519:     #
  520:     my $selected = 'scores';
  521:     if (exists($ENV{'form.'.$elementname})) {
  522:         if (ref($ENV{'form.'.$elementname} eq 'ARRAY')) {
  523:             $selected = $ENV{'form.'.$elementname}->[0];
  524:         } else {
  525:             $selected = $ENV{'form.'.$elementname};
  526:         }
  527:     }
  528:     #
  529:     $data = 'scores';
  530:     foreach my $option (@OutputDataOptions) {
  531:         if ($option->{'value'} eq $selected) {
  532:             $data = $option->{'value'};
  533:             $base = $option->{'base'};
  534:             $datadescription = $option->{'shortdesc'};
  535:         }
  536:     }
  537:     #
  538:     # Build the form element
  539:     $Str = qq/<select size="5" name="$elementname">/;
  540:     foreach my $option (@OutputDataOptions) {
  541:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  542:         $Str .= " selected " if ($option->{'value'} eq $data);
  543:         $Str .= ">".$option->{'name'}."<\/option>";
  544:     }
  545:     $Str .= "\n</select>";
  546:     return $Str;
  547: 
  548: }
  549: 
  550: #######################################################
  551: #######################################################
  552: 
  553: =pod
  554: 
  555: =head2 HTML output routines
  556: 
  557: =item &html_initialize($r)
  558: 
  559: Create labels for the columns of student data to show.
  560: 
  561: =item &html_outputstudent($r,$student)
  562: 
  563: Return a line of the chart for a student.
  564: 
  565: =item &html_finish($r)
  566: 
  567: =cut
  568: 
  569: #######################################################
  570: #######################################################
  571: {
  572:     my $padding;
  573:     my $count;
  574: 
  575:     my $nodata_count; # The number of students for which there is no data
  576:     my %prog_state;   # progress state used by loncommon PrgWin routines
  577: 
  578: sub html_initialize {
  579:     my ($r) = @_;
  580:     #
  581:     $padding = ' 'x3;
  582:     $count = 0;
  583:     $nodata_count = 0;
  584:     #
  585:     $r->print("<h3>".$ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
  586:               "&nbsp;&nbsp;".localtime(time)."</h3>");
  587: 
  588:     if ($data !~ /^final table/) {
  589:         $r->print("<h3>".$datadescription."</h3>");        
  590:     }
  591:     #
  592:     # Set up progress window for 'final table' display only
  593:     if ($data =~ /^final table/) {
  594:         my $studentcount = scalar(@Apache::lonstatistics::Students); 
  595:         %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  596:             ($r,'Summary Table Status',
  597:              'Summary Table Compilation Progress', $studentcount);
  598:     }
  599:     my $Str = "<pre>\n";
  600:     # First, the @StudentData fields need to be listed
  601:     my @to_show = &get_student_fields_to_show();
  602:     foreach my $field (@to_show) {
  603:         my $title=$Apache::lonstatistics::StudentData{$field}->{'title'};
  604:         my $base =$Apache::lonstatistics::StudentData{$field}->{'base_width'};
  605:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  606:         $Str .= $title.' 'x($width-$base).$padding;
  607:     }
  608:     # Now the selected sequences need to be listed
  609:     foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()){
  610:         my $title = $sequence->{'title'};
  611:         my $base  = $sequence->{'base_width'};
  612:         my $width = $sequence->{'width'};
  613:         $Str .= $title.' 'x($width-$base).$padding;
  614:     }
  615:     $Str .= "total</pre>\n";
  616:     $Str .= "<pre>";
  617:     #
  618:     # Check for suppression of output
  619:     if ($data =~ /^final table/) {
  620:         $Str = '';
  621:     }
  622:     $r->print($Str);
  623:     $r->rflush();
  624:     return;
  625: }
  626: 
  627: sub html_outputstudent {
  628:     my ($r,$student) = @_;
  629:     my $Str = '';
  630:     #
  631:     if($count++ % 5 == 0 && $count > 0 && $data !~ /^final table/) {
  632:         $r->print("</pre><pre>");
  633:     }
  634:     # First, the @StudentData fields need to be listed
  635:     my @to_show = &get_student_fields_to_show();
  636:     foreach my $field (@to_show) {
  637:         my $title=$student->{$field};
  638:         my $base = length($title);
  639:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  640:         $Str .= $title.' 'x($width-$base).$padding;
  641:     }
  642:     # Get ALL the students data
  643:     my %StudentsData;
  644:     my @tmp = &Apache::loncoursedata::get_current_state
  645:         ($student->{'username'},$student->{'domain'},undef,
  646:          $ENV{'request.course.id'});
  647:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
  648:         %StudentsData = @tmp;
  649:     }
  650:     if (scalar(@tmp) < 1) {
  651:         $nodata_count++;
  652:         return if ($data =~ /^final table/);
  653:         $Str .= '<font color="blue">No Course Data</font>'."\n";
  654:         $r->print($Str);
  655:         $r->rflush();
  656:         return;
  657:     }
  658:     #
  659:     # By sequence build up the data
  660:     my $studentstats;
  661:     my $PerformanceStr = '';
  662:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  663:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
  664:         if ($base eq 'tries') {
  665:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  666:                 &StudentTriesOnSequence($student,\%StudentsData,
  667:                                         $seq,$show_links);
  668:         } else {
  669:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  670:                 &StudentPerformanceOnSequence($student,\%StudentsData,
  671:                                               $seq,$show_links);
  672:         }
  673:         my $ratio = sprintf("%3d",$score).'/'.sprintf("%3d",$seq_max);
  674:         #
  675:         if ($data eq 'sum and total' || $data eq 'parts correct total') {
  676:             $performance  = $ratio;
  677:             $performance .= ' 'x($seq->{'width'}-length($ratio));
  678:         } elsif ($data eq 'sum only' || $data eq 'parts correct') {
  679:             $performance  = $score;
  680:             $performance .= ' 'x($seq->{'width'}-length($score));
  681:         } else {
  682:             # Pad with extra spaces
  683:             $performance .= ' 'x($seq->{'width'}-$performance_length-
  684:                                  length($ratio)
  685:                                  ).$ratio;
  686:         }
  687:         #
  688:         $Str .= $performance.$padding;
  689:         #
  690:         $studentstats->{$seq->{'symb'}}->{'score'}= $score;
  691:         $studentstats->{$seq->{'symb'}}->{'max'}  = $seq_max;
  692:     }
  693:     #
  694:     # Total it up and store the statistics info.
  695:     my ($score,$max) = (0,0);
  696:     while (my ($symb,$seq_stats) = each (%{$studentstats})) {
  697:         $Statistics->{$symb}->{'score'} += $seq_stats->{'score'};
  698:         if ($Statistics->{$symb}->{'max'} < $seq_stats->{'max'}) {
  699:             $Statistics->{$symb}->{'max'} = $seq_stats->{'max'};
  700:         }
  701:         $score += $seq_stats->{'score'};
  702:         $max   += $seq_stats->{'max'};
  703:     }
  704:     $Str .= ' '.' 'x(length($max)-length($score)).$score.'/'.$max;
  705:     $Str .= " \n";
  706:     #
  707:     # Check for suppressed output and update the progress window if so...
  708:     if ($data =~ /^final table/) {
  709:         $Str = '';
  710:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  711:                                                  'last student');
  712:     }
  713:     #
  714:     $r->print($Str);
  715:     #
  716:     $r->rflush();
  717:     return;
  718: }    
  719: 
  720: sub html_finish {
  721:     my ($r) = @_;
  722:     #
  723:     # Check for suppressed output and close the progress window if so
  724:     if ($data =~ /^final table/) {
  725:         &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  726:     } else {
  727:         $r->print("</pre>\n"); 
  728:     }
  729:     if ($single_student_mode) {
  730:         $r->print(&SingleStudentTotal());
  731:     } else {
  732:         $r->print(&StudentAverageTotal());
  733:     }
  734:     $r->rflush();
  735:     return;
  736: }
  737: 
  738: sub StudentAverageTotal {
  739:     my $Str = "<h3>Summary Tables</h3>\n";
  740:     my $num_students = scalar(@Apache::lonstatistics::Students);
  741:     my $total_ave = 0;
  742:     my $total_max = 0;
  743:     $Str .= '<table border=2 cellspacing="1">'."\n";
  744:     $Str .= "<tr><th>Title</th><th>Average</th><th>Maximum</th></tr>\n";
  745:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  746:         my $ave;
  747:         if ($num_students > $nodata_count) {
  748:             $ave = int(100*($Statistics->{$seq->{'symb'}}->{'score'}/
  749:                             ($num_students-$nodata_count)))/100;
  750:         } else {
  751:             $ave = 0;
  752:         }
  753:         $total_ave += $ave;
  754:         my $max = $Statistics->{$seq->{'symb'}}->{'max'};
  755:         $total_max += $max;
  756:         if ($ave == 0) {
  757:             $ave = "0.00";
  758:         }
  759:         $ave .= '&nbsp;';
  760:         $max .= '&nbsp;&nbsp;&nbsp;';
  761:         $Str .= '<tr><td>'.$seq->{'title'}.'</td>'.
  762:             '<td align="right">'.$ave.'</td>'.
  763:                 '<td align="right">'.$max.'</td></tr>'."\n";
  764:     }
  765:     $total_ave = int(100*$total_ave)/100; # only two digit
  766:     $Str .= "</table>\n";
  767:     $Str .= '<table border=2 cellspacing="1">'."\n";
  768:     $Str .= '<tr><th>Number of Students</th><th>Average</th>'.
  769:         "<th>Maximum</th></tr>\n";
  770:     $Str .= '<tr><td>'.($num_students-$nodata_count).'</td>'.
  771:         '<td>'.$total_ave.'</td><td>'.$total_max.'</td>';
  772:     $Str .= "</table>\n";
  773:     return $Str;
  774: }
  775: 
  776: sub SingleStudentTotal {
  777:     my $student = &Apache::lonstatistics::current_student();
  778:     my $Str = "<h3>Summary table for ".$student->{'fullname'}." ".
  779:         $student->{'username'}.'@'.$student->{'domain'}."</h3>\n";
  780:     $Str .= '<table border=2 cellspacing="1">'."\n";
  781:     $Str .= 
  782:         "<tr><th>Sequence or Folder</th><th>Score</th><th>Maximum</th></tr>\n";
  783:     my $total = 0;
  784:     my $total_max = 0;
  785:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  786:         my $value = $Statistics->{$seq->{'symb'}}->{'score'};
  787:         my $max = $Statistics->{$seq->{'symb'}}->{'max'};
  788:         $Str .= '<tr><td>'.$seq->{'title'}.'</td>'.
  789:             '<td align="right">'.$value.'</td>'.
  790:                 '<td align="right">'.$max.'</td></tr>'."\n";
  791:         $total += $value;
  792:         $total_max +=$max;
  793:     }
  794:     $Str .= '<tr><td><b>Total</b></td>'.
  795:         '<td align="right">'.$total.'</td>'.
  796:         '<td align="right">'.$total_max."</td></tr>\n";
  797:     $Str .= "</table>\n";
  798:     return $Str;
  799: }
  800: 
  801: }
  802: 
  803: #######################################################
  804: #######################################################
  805: 
  806: =pod
  807: 
  808: =head2 EXCEL subroutines
  809: 
  810: =item &excel_initialize($r)
  811: 
  812: =item &excel_outputstudent($r,$student)
  813: 
  814: =item &excel_finish($r)
  815: 
  816: =cut
  817: 
  818: #######################################################
  819: #######################################################
  820: {
  821: 
  822: my $excel_sheet;
  823: my $excel_workbook;
  824: 
  825: my $filename;
  826: my $rows_output;
  827: my $cols_output;
  828: 
  829: my %prog_state; # progress window state
  830: my $request_aborted;
  831: 
  832: sub excel_initialize {
  833:     my ($r) = @_;
  834:     #
  835:     $request_aborted = undef;
  836:     my $total_columns = scalar(&get_student_fields_to_show());
  837:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  838:         # Add 2 because we need a 'sum' and 'total' column for each
  839:         $total_columns += $seq->{'num_assess_parts'}+2;
  840:     }
  841:     if ($data eq 'tries' && $total_columns > 255) {
  842:         $r->print(<<END);
  843: <h2>Unable to Complete Request</h2>
  844: <p>
  845: LON-CAPA is unable to produce your Excel spreadsheet because your selections
  846: will result in more than 255 columns.  Excel allows only 255 columns in a
  847: spreadsheet.
  848: </p><p>
  849: You may consider reducing the number of <b>Sequences or Folders</b> you
  850: have selected.  
  851: </p><p>
  852: LON-CAPA can produce <b>CSV</b> files of this data or Excel files of the
  853: summary data (<b>Parts Correct</b> or <b>Parts Correct & Totals</b>).
  854: </p>
  855: END
  856:        $request_aborted = 1;
  857:     }
  858:     if ($data eq 'scores' && $total_columns > 255) {
  859:         $r->print(<<END);
  860: <h2>Unable to Complete Request</h2>
  861: <p>
  862: LON-CAPA is unable to produce your Excel spreadsheet because your selections
  863: will result in more than 255 columns.  Excel allows only 255 columns in a
  864: spreadsheet.
  865: </p><p>
  866: You may consider reducing the number of <b>Sequences or Folders</b> you
  867: have selected.  
  868: </p><p>
  869: LON-CAPA can produce <b>CSV</b> files of this data or Excel files of the
  870: summary data (<b>Scores Sum</b> or <b>Scores Sum & Totals</b>).
  871: </p>
  872: END
  873:        $request_aborted = 1;
  874:     }
  875:     if ($data =~ /^final table/) {
  876:         $r->print(<<END);
  877: <h2>Unable to Complete Request</h2>
  878: <p>
  879: The <b>Summary Table (Scores)</b> option is not available for non-HTML output.
  880: </p>
  881: END
  882:        $request_aborted = 1;
  883:     }
  884:     return if ($request_aborted);
  885:     #
  886:     $filename = '/prtspool/'.
  887:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
  888:             time.'_'.rand(1000000000).'.xls';
  889:     #
  890:     $excel_workbook = undef;
  891:     $excel_sheet = undef;
  892:     #
  893:     $rows_output = 0;
  894:     $cols_output = 0;
  895:     #
  896:     # Create sheet
  897:     $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
  898:     #
  899:     # Check for errors
  900:     if (! defined($excel_workbook)) {
  901:         $r->log_error("Error creating excel spreadsheet $filename: $!");
  902:         $r->print("Problems creating new Excel file.  ".
  903:                   "This error has been logged.  ".
  904:                   "Please alert your LON-CAPA administrator");
  905:         return ;
  906:     }
  907:     #
  908:     # The excel spreadsheet stores temporary data in files, then put them
  909:     # together.  If needed we should be able to disable this (memory only).
  910:     # The temporary directory must be specified before calling 'addworksheet'.
  911:     # File::Temp is used to determine the temporary directory.
  912:     $excel_workbook->set_tempdir($Apache::lonnet::tmpdir);
  913:     #
  914:     # Add a worksheet
  915:     my $sheetname = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  916:     if (length($sheetname) > 31) {
  917:         $sheetname = substr($sheetname,0,31);
  918:     }
  919:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
  920:     #
  921:     # Put the course description in the header
  922:     $excel_sheet->write($rows_output,$cols_output++,
  923:                    $ENV{'course.'.$ENV{'request.course.id'}.'.description'});
  924:     $cols_output += 3;
  925:     #
  926:     # Put a description of the sections listed
  927:     my $sectionstring = '';
  928:     my @Sections = @Apache::lonstatistics::SelectedSections;
  929:     if (scalar(@Sections) > 1) {
  930:         if (scalar(@Sections) > 2) {
  931:             my $last = pop(@Sections);
  932:             $sectionstring = "Sections ".join(', ',@Sections).', and '.$last;
  933:         } else {
  934:             $sectionstring = "Sections ".join(' and ',@Sections);
  935:         }
  936:     } else {
  937:         if ($Sections[0] eq 'all') {
  938:             $sectionstring = "All sections";
  939:         } else {
  940:             $sectionstring = "Section ".$Sections[0];
  941:         }
  942:     }
  943:     $excel_sheet->write($rows_output,$cols_output++,$sectionstring);
  944:     $cols_output += scalar(@Sections);
  945:     #
  946:     # Put the date in there too
  947:     $excel_sheet->write($rows_output++,$cols_output++,
  948:                         'Compiled on '.localtime(time));
  949:     #
  950:     $cols_output = 0;
  951:     $excel_sheet->write($rows_output++,$cols_output++,$datadescription);
  952:     #
  953:     if ($data eq 'tries' || $data eq 'scores') {
  954:         $rows_output++;
  955:     }
  956:     #
  957:     # Add the student headers
  958:     $cols_output = 0;
  959:     foreach my $field (&get_student_fields_to_show()) {
  960:         $excel_sheet->write($rows_output,$cols_output++,$field);
  961:     }
  962:     my $row_offset = 0;
  963:     if ($data eq 'tries' || $data eq 'scores') {
  964:         $row_offset = -1;
  965:     }
  966:     #
  967:     # Add the remaining column headers
  968:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  969:         $excel_sheet->write($rows_output+$row_offset,
  970:                             $cols_output,$seq->{'title'});
  971:         if ($data eq 'tries' || $data eq 'scores') {
  972:             foreach my $res (@{$seq->{'contents'}}) {
  973:                 next if ($res->{'type'} ne 'assessment');
  974:                 if (scalar(@{$res->{'parts'}}) > 1) {
  975:                     foreach my $part (@{$res->{'parts'}}) {
  976:                         $excel_sheet->write($rows_output,
  977:                                             $cols_output++,
  978:                                             $res->{'title'}.' part '.$part);
  979:                     }
  980:                 } else {
  981:                     $excel_sheet->write($rows_output,
  982:                                         $cols_output++,
  983:                                         $res->{'title'});
  984:                 }
  985:             }
  986:             $excel_sheet->write($rows_output,$cols_output++,'score');
  987:             $excel_sheet->write($rows_output,$cols_output++,'maximum');
  988:         } elsif ($data eq 'sum and total' || $data eq 'parts correct total') {
  989:             $excel_sheet->write($rows_output+1,$cols_output,'score');
  990:             $excel_sheet->write($rows_output+1,$cols_output+1,'maximum');
  991:             $cols_output += 2;
  992:         } else {
  993:             $cols_output++;
  994:         }
  995:     }
  996:     #
  997:     # Bookkeeping
  998:     if ($data eq 'sum and total' || $data eq 'parts correct total') {
  999:         $rows_output += 2;
 1000:     } else {
 1001:         $rows_output += 1;
 1002:     }
 1003:     #
 1004:     # Output a row for MAX
 1005:     $cols_output = 0;
 1006:     foreach my $field (&get_student_fields_to_show()) {
 1007:         if ($field eq 'username' || $field eq 'fullname' || 
 1008:             $field eq 'id') {
 1009:             $excel_sheet->write($rows_output,$cols_output++,'Maximum');
 1010:         } else {
 1011:             $excel_sheet->write($rows_output,$cols_output++,'');
 1012:         }
 1013:     }
 1014:     #
 1015:     # Add the maximums for each sequence or assessment
 1016:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1017:         my $weight;
 1018:         my $max = 0;
 1019:         foreach my $resource (@{$seq->{'contents'}}) {
 1020:             next if ($resource->{'type'} ne 'assessment');
 1021:             foreach my $part (@{$resource->{'parts'}}) {
 1022:                 $weight = 1;
 1023:                 if ($base eq 'scores') {
 1024:                     $weight = &Apache::lonnet::EXT
 1025:                         ('resource.'.$part.'.weight',$resource->{'symb'},
 1026:                          undef,undef,undef);
 1027:                     if (!defined($weight) || ($weight eq '')) { 
 1028:                         $weight=1;
 1029:                     }
 1030:                 }
 1031:                 if ($data eq 'scores') {
 1032:                     $excel_sheet->write($rows_output,$cols_output++,$weight);
 1033:                 } elsif ($data eq 'tries') {
 1034:                     $excel_sheet->write($rows_output,$cols_output++,'');
 1035:                 }
 1036:                 $max += $weight;
 1037:             }
 1038:         } 
 1039:         if (! ($data eq 'sum only' || $data eq 'parts correct')) {
 1040:             $excel_sheet->write($rows_output,$cols_output++,'');
 1041:         }
 1042:         $excel_sheet->write($rows_output,$cols_output++,$max);
 1043:     }
 1044:     $rows_output++;
 1045:     #
 1046:     # Let the user know what we are doing
 1047:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
 1048:     $r->print("<h1>Compiling Excel spreadsheet for ".
 1049:               $studentcount.' student');
 1050:     $r->print('s') if ($studentcount > 1);
 1051:     $r->print("</h1>\n");
 1052:     $r->rflush();
 1053:     #
 1054:     # Initialize progress window
 1055:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1056:         ($r,'Excel File Compilation Status',
 1057:          'Excel File Compilation Progress', $studentcount);
 1058:     #
 1059:     return;
 1060: }
 1061: 
 1062: sub excel_outputstudent {
 1063:     my ($r,$student) = @_;
 1064:     return if ($request_aborted);
 1065:     return if (! defined($excel_sheet));
 1066:     $cols_output=0;
 1067:     #
 1068:     # Write out student data
 1069:     my @to_show = &get_student_fields_to_show();
 1070:     foreach my $field (@to_show) {
 1071:         $excel_sheet->write($rows_output,$cols_output++,$student->{$field});
 1072:     }
 1073:     #
 1074:     # Get student assessment data
 1075:     my %StudentsData;
 1076:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1077:                                                         $student->{'domain'},
 1078:                                                         undef,
 1079:                                                    $ENV{'request.course.id'});
 1080:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1081:         %StudentsData = @tmp;
 1082:     }
 1083:     #
 1084:     # Write out sequence scores and totals data
 1085:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1086:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1087:         if ($base eq 'tries') {
 1088:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1089:                 &StudentTriesOnSequence($student,\%StudentsData,
 1090:                                         $seq,'no');
 1091:         } else {
 1092:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1093:                 &StudentPerformanceOnSequence($student,\%StudentsData,
 1094:                                               $seq,'no');
 1095:         }
 1096:         if ($data eq 'tries' || $data eq 'scores') {
 1097:             foreach my $value (@$rawdata) {
 1098:                 $excel_sheet->write($rows_output,$cols_output++,$value);
 1099:             }
 1100:             $excel_sheet->write($rows_output,$cols_output++,$score);
 1101:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
 1102:         } elsif ($data eq 'sum and total' || $data eq 'sum only' || 
 1103:             $data eq 'parts correct' || $data eq 'parts correct total') {
 1104:             $excel_sheet->write($rows_output,$cols_output++,$score);
 1105:         }
 1106:         if ($data eq 'sum and total' || $data eq 'parts correct total') {
 1107:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
 1108:         }
 1109:     }
 1110:     #
 1111:     # Bookkeeping
 1112:     $rows_output++; 
 1113:     $cols_output=0;
 1114:     #
 1115:     # Update the progress window
 1116:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1117:     return;
 1118: }
 1119: 
 1120: sub excel_finish {
 1121:     my ($r) = @_;
 1122:     return if ($request_aborted);
 1123:     return if (! defined($excel_sheet));
 1124:     #
 1125:     # Write the excel file
 1126:     $excel_workbook->close();
 1127:     my $c = $r->connection();
 1128:     #
 1129:     return if($c->aborted());
 1130:     #
 1131:     # Close the progress window
 1132:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1133:     #
 1134:     # Tell the user where to get their excel file
 1135:     $r->print('<br />'.
 1136:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1137:     $r->rflush();
 1138:     return;
 1139: }
 1140: 
 1141: }
 1142: #######################################################
 1143: #######################################################
 1144: 
 1145: =pod
 1146: 
 1147: =head2 CSV output routines
 1148: 
 1149: =item &csv_initialize($r)
 1150: 
 1151: =item &csv_outputstudent($r,$student)
 1152: 
 1153: =item &csv_finish($r)
 1154: 
 1155: =cut
 1156: 
 1157: #######################################################
 1158: #######################################################
 1159: {
 1160: 
 1161: my $outputfile;
 1162: my $filename;
 1163: my $request_aborted;
 1164: my %prog_state; # progress window state
 1165: 
 1166: sub csv_initialize{
 1167:     my ($r) = @_;
 1168:     # 
 1169:     # Clean up
 1170:     $filename = undef;
 1171:     $outputfile = undef;
 1172:     undef(%prog_state);
 1173:     #
 1174:     # Deal with unimplemented requests
 1175:     $request_aborted = undef;
 1176:     if ($data =~ /final table/) {
 1177:         $r->print(<<END);
 1178: <h2>Unable to Complete Request</h2>
 1179: <p>
 1180: The <b>Summary Table (Scores)</b> option is not available for non-HTML output.
 1181: </p>
 1182: END
 1183:        $request_aborted = 1;
 1184:     }
 1185:     return if ($request_aborted);
 1186: 
 1187:     #
 1188:     # Open a file
 1189:     $filename = '/prtspool/'.
 1190:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1191:             time.'_'.rand(1000000000).'.csv';
 1192:     unless ($outputfile = Apache::File->new('>/home/httpd'.$filename)) {
 1193:         $r->log_error("Couldn't open $filename for output $!");
 1194:         $r->print("Problems occured in writing the csv file.  ".
 1195:                   "This error has been logged.  ".
 1196:                   "Please alert your LON-CAPA administrator.");
 1197:         $outputfile = undef;
 1198:     }
 1199:     #
 1200:     # Datestamp
 1201:     my $description = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1202:     print $outputfile '"'.&Apache::loncommon::csv_translate($description).'",'.
 1203:         '"'.&Apache::loncommon::csv_translate(scalar(localtime(time))).'"'.
 1204:             "\n";
 1205:     #
 1206:     # Print out the headings
 1207:     my $Str = '';
 1208:     my $Str2 = undef;
 1209:     foreach my $field (&get_student_fields_to_show()) {
 1210:         if ($data eq 'sum only') {
 1211:             $Str .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1212:         } elsif ($data eq 'sum and total' || $data eq 'parts correct total') {
 1213:             $Str .= '"",'; # first row empty on the student fields
 1214:             $Str2 .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1215:         } elsif ($data eq 'scores' || $data eq 'tries' || 
 1216:                  $data eq 'parts correct') {
 1217:             $Str  .= '"",';
 1218:             $Str2 .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1219:         }
 1220:     }
 1221:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1222:         if ($data eq 'sum only' || $data eq 'parts correct') {
 1223:             $Str .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
 1224:                 '",';
 1225:         } elsif ($data eq 'sum and total' || $data eq 'parts correct total') {
 1226:             $Str  .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
 1227:                 '","",';
 1228:             $Str2 .= '"score","total possible",';
 1229:         } elsif ($data eq 'scores' || $data eq 'tries') {
 1230:             $Str  .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
 1231:                 '",';
 1232:             $Str .= '"",'x($seq->{'num_assess_parts'}-1+2);
 1233:             foreach my $res (@{$seq->{'contents'}}) {
 1234:                 next if ($res->{'type'} ne 'assessment');
 1235:                 foreach my $part (@{$res->{'parts'}}) {
 1236:                     $Str2 .= '"'.&Apache::loncommon::csv_translate($res->{'title'}.', Part '.$part).'",';
 1237:                 }
 1238:             }
 1239:             $Str2 .= '"score","total possible",';
 1240:         }
 1241:     }
 1242:     chop($Str);
 1243:     $Str .= "\n";
 1244:     print $outputfile $Str;
 1245:     if (defined($Str2)) {
 1246:         chop($Str2);
 1247:         $Str2 .= "\n";
 1248:         print $outputfile $Str2;
 1249:     }
 1250:     #
 1251:     # Initialize progress window
 1252:     my $studentcount = scalar(@Apache::lonstatistics::Students);
 1253:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1254:         ($r,'CSV File Compilation Status',
 1255:          'CSV File Compilation Progress', $studentcount);
 1256:     return;
 1257: }
 1258: 
 1259: sub csv_outputstudent {
 1260:     my ($r,$student) = @_;
 1261:     return if ($request_aborted);
 1262:     return if (! defined($outputfile));
 1263:     my $Str = '';
 1264:     #
 1265:     # Output student fields
 1266:     my @to_show = &get_student_fields_to_show();
 1267:     foreach my $field (@to_show) {
 1268:         $Str .= '"'.&Apache::loncommon::csv_translate($student->{$field}).'",';
 1269:     }
 1270:     #
 1271:     # Get student assessment data
 1272:     my %StudentsData;
 1273:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1274:                                                         $student->{'domain'},
 1275:                                                         undef,
 1276:                                                    $ENV{'request.course.id'});
 1277:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1278:         %StudentsData = @tmp;
 1279:     }
 1280:     #
 1281:     # Output performance data
 1282:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1283:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1284:         if ($base eq 'tries') {
 1285:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1286:                 &StudentTriesOnSequence($student,\%StudentsData,
 1287:                                         $seq,'no');
 1288:         } else {
 1289:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1290:                 &StudentPerformanceOnSequence($student,\%StudentsData,
 1291:                                               $seq,'no');
 1292:         }
 1293:         if ($data eq 'sum only' || $data eq 'parts correct') {
 1294:             $Str .= '"'.$score.'",';
 1295:         } elsif ($data eq 'sum and total' || $data eq 'parts correct total') {
 1296:             $Str  .= '"'.$score.'","'.$seq_max.'",';
 1297:         } elsif ($data eq 'scores' || $data eq 'tries') {
 1298:             $Str .= '"'.join('","',(@$rawdata,$score,$seq_max)).'",';
 1299:         }
 1300:     }
 1301:     chop($Str);
 1302:     $Str .= "\n";
 1303:     print $outputfile $Str;
 1304:     #
 1305:     # Update the progress window
 1306:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1307:     return;
 1308: }
 1309: 
 1310: sub csv_finish {
 1311:     my ($r) = @_;
 1312:     return if ($request_aborted);
 1313:     return if (! defined($outputfile));
 1314:     close($outputfile);
 1315:     #
 1316:     my $c = $r->connection();
 1317:     return if ($c->aborted());
 1318:     #
 1319:     # Close the progress window
 1320:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1321:     #
 1322:     # Tell the user where to get their csv file
 1323:     $r->print('<br />'.
 1324:               '<a href="'.$filename.'">Your csv file.</a>'."\n");
 1325:     $r->rflush();
 1326:     return;
 1327:     
 1328: }
 1329: 
 1330: }
 1331: 
 1332: #######################################################
 1333: #######################################################
 1334: 
 1335: =pod
 1336: 
 1337: =item &StudentTriesOnSequence()
 1338: 
 1339: Inputs:
 1340: 
 1341: =over 4
 1342: 
 1343: =item $student
 1344: 
 1345: =item $studentdata Hash ref to all student data
 1346: 
 1347: =item $seq Hash ref, the sequence we are working on
 1348: 
 1349: =item $links if defined we will output links to each resource.
 1350: 
 1351: =back
 1352: 
 1353: =cut
 1354: 
 1355: #######################################################
 1356: #######################################################
 1357: sub StudentTriesOnSequence {
 1358:     my ($student,$studentdata,$seq,$links) = @_;
 1359:     $links = 'no' if (! defined($links));
 1360:     my $Str = '';
 1361:     my ($sum,$max) = (0,0);
 1362:     my $performance_length = 0;
 1363:     my @TriesData = ();
 1364:     my $tries;
 1365:     foreach my $resource (@{$seq->{'contents'}}) {
 1366:         next if ($resource->{'type'} ne 'assessment');
 1367:         my $resource_data = $studentdata->{$resource->{'symb'}};
 1368:         my $value = '';
 1369:         foreach my $partnum (@{$resource->{'parts'}}) {
 1370:             $tries = undef;
 1371:             $max++;
 1372:             $performance_length++;
 1373:             my $symbol = ' '; # default to space
 1374:             #
 1375:             if (exists($resource_data->{'resource.'.$partnum.'.solved'})) {
 1376:                 my $status = $resource_data->{'resource.'.$partnum.'.solved'};
 1377:                 if ($status eq 'correct_by_override') {
 1378:                     $symbol = '+';
 1379:                     $sum++;
 1380:                 } elsif ($status eq 'incorrect_by_override') {
 1381:                     $symbol = '-';
 1382:                 } elsif ($status eq 'ungraded_attempted') {
 1383:                     $symbol = '#';
 1384:                 } elsif ($status eq 'incorrect_attempted')  {
 1385:                     $symbol = '.';
 1386:                 } elsif ($status eq 'excused') {
 1387:                     $symbol = 'x';
 1388:                     $max--;
 1389:                 } elsif ($status eq 'correct_by_student' &&
 1390:                     exists($resource_data->{'resource.'.$partnum.'.tries'})){
 1391:                     $tries = $resource_data->{'resource.'.$partnum.'.tries'};
 1392:                     if ($tries > 9) {
 1393:                         $symbol = '*';
 1394:                     } elsif ($tries > 0) {
 1395:                         $symbol = $tries;
 1396:                     } else {
 1397:                         $symbol = ' ';
 1398:                     }
 1399:                     $sum++;
 1400:                 } elsif (exists($resource_data->{'resource.'.
 1401:                                                      $partnum.'.tries'})){
 1402:                     $symbol = '.';
 1403:                 } else {
 1404:                     $symbol = ' ';
 1405:                 }
 1406:             } else {
 1407:                 # Unsolved.  Did they try?
 1408:                 if (exists($resource_data->{'resource.'.$partnum.'.tries'})){
 1409:                     $symbol = '.';
 1410:                 } else {
 1411:                     $symbol = ' ';
 1412:                 }
 1413:             }
 1414:             #
 1415:             if (! defined($tries)) {
 1416:                 $tries = $symbol;
 1417:             }
 1418:             push (@TriesData,$tries);
 1419:             #
 1420:             if ( ($links eq 'yes' && $symbol ne ' ') ||
 1421:                  ($links eq 'all')) {
 1422:                 if (length($symbol) > 1) {
 1423:                     &Apache::lonnet::logthis('length of symbol "'.$symbol.'" > 1');
 1424:                 }
 1425:                 $symbol = '<a href="/adm/grades'.
 1426:                     '?symb='.&Apache::lonnet::escape($resource->{'symb'}).
 1427:                         '&student='.$student->{'username'}.
 1428:                             '&domain='.$student->{'domain'}.
 1429:                                 '&command=submission">'.$symbol.'</a>';
 1430:             }
 1431:             $value .= $symbol;
 1432:         }
 1433:         $Str .= $value;
 1434:     }
 1435:     if ($seq->{'randompick'}) {
 1436:         $max = $seq->{'randompick'};
 1437:     }
 1438:     return ($Str,$performance_length,$sum,$max,\@TriesData);
 1439: }
 1440: 
 1441: #######################################################
 1442: #######################################################
 1443: 
 1444: =pod
 1445: 
 1446: =item &StudentPerformanceOnSequence()
 1447: 
 1448: Inputs:
 1449: 
 1450: =over 4
 1451: 
 1452: =item $student
 1453: 
 1454: =item $studentdata Hash ref to all student data
 1455: 
 1456: =item $seq Hash ref, the sequence we are working on
 1457: 
 1458: =item $links if defined we will output links to each resource.
 1459: 
 1460: =back
 1461: 
 1462: =cut
 1463: 
 1464: #######################################################
 1465: #######################################################
 1466: sub StudentPerformanceOnSequence {
 1467:     my ($student,$studentdata,$seq,$links) = @_;
 1468:     $links = 'no' if (! defined($links));
 1469:     my $Str = ''; # final result string
 1470:     my ($score,$max) = (0,0);
 1471:     my $performance_length = 0;
 1472:     my $symbol;
 1473:     my @ScoreData = ();
 1474:     my $partscore;
 1475:     foreach my $resource (@{$seq->{'contents'}}) {
 1476:         next if ($resource->{'type'} ne 'assessment');
 1477:         my $resource_data = $studentdata->{$resource->{'symb'}};
 1478:         foreach my $part (@{$resource->{'parts'}}) {
 1479:             $partscore = undef;
 1480:             my $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 1481:                                               $resource->{'symb'},
 1482:                                               $student->{'domain'},
 1483:                                               $student->{'username'},
 1484:                                               $student->{'section'});
 1485:             if (!defined($weight) || ($weight eq '')) { 
 1486:                 $weight=1;
 1487:             }
 1488:             #
 1489:             $max += $weight; # see the 'excused' branch below...
 1490:             $performance_length++; # one character per part
 1491:             $symbol = ' '; # default to space
 1492:             #
 1493:             my $awarded = 0;
 1494:             if (exists($resource_data->{'resource.'.$part.'.awarded'})) {
 1495:                 $awarded = $resource_data->{'resource.'.$part.'.awarded'};
 1496:             }
 1497:             #
 1498:             $partscore = $weight*$awarded;
 1499:             $score += $partscore;
 1500:             $symbol = $weight; 
 1501:             if (length($symbol) > 1) {
 1502:                 $symbol = '*';
 1503:             }
 1504:             if (exists($resource_data->{'resource.'.$part.'.solved'})) {
 1505:                 my $status = $resource_data->{'resource.'.$part.'.solved'};
 1506:                 if ($status eq 'excused') {
 1507:                     $symbol = 'x';
 1508:                     $max -= $weight; # Do not count 'excused' problems.
 1509:                 }
 1510:             } else {
 1511:                 # Unsolved.  Did they try?
 1512:                 if (exists($resource_data->{'resource.'.$part.'.tries'})){
 1513:                     $symbol = '.';
 1514:                 } else {
 1515:                     $symbol = ' ';
 1516:                 }
 1517:             }
 1518:             #
 1519:             if (! defined($partscore)) {
 1520:                 $partscore = $symbol;
 1521:             }
 1522:             push (@ScoreData,$partscore);
 1523:             #
 1524:             if ( ($links eq 'yes' && $symbol ne ' ') || ($links eq 'all')) {
 1525:                 $symbol = '<a href="/adm/grades'.
 1526:                     '?symb='.&Apache::lonnet::escape($resource->{'symb'}).
 1527:                     '&student='.$student->{'username'}.
 1528:                     '&domain='.$student->{'domain'}.
 1529:                     '&command=submission">'.$symbol.'</a>';
 1530:             }
 1531:             $Str .= $symbol;
 1532:         }
 1533:     }
 1534:     return ($Str,$performance_length,$score,$max,\@ScoreData);
 1535: }
 1536: 
 1537: #######################################################
 1538: #######################################################
 1539: 
 1540: =pod
 1541: 
 1542: =item &CreateLegend()
 1543: 
 1544: This function returns a formatted string containing the legend for the
 1545: chart.  The legend describes the symbols used to represent grades for
 1546: problems.
 1547: 
 1548: =cut
 1549: 
 1550: #######################################################
 1551: #######################################################
 1552: sub CreateLegend {
 1553:     my $Str = "<p><pre>".
 1554:               "   1  correct by student in 1 try\n".
 1555:               "   7  correct by student in 7 tries\n".
 1556:               "   *  correct by student in more than 9 tries\n".
 1557: 	      "   +  correct by hand grading or override\n".
 1558:               "   -  incorrect by override\n".
 1559: 	      "   .  incorrect attempted\n".
 1560: 	      "   #  ungraded attempted\n".
 1561:               "      not attempted (blank field)\n".
 1562: 	      "   x  excused".
 1563:               "</pre><p>";
 1564:     return $Str;
 1565: }
 1566: 
 1567: #######################################################
 1568: #######################################################
 1569: 
 1570: =pod 
 1571: 
 1572: =back
 1573: 
 1574: =cut
 1575: 
 1576: #######################################################
 1577: #######################################################
 1578: 
 1579: 1;
 1580: 
 1581: __END__

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