File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.58: download - view: text, annotated - select for diffs
Wed Jun 11 16:19:39 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: version_0_99_2, HEAD
Install and use chart help files.

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

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