File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.55: download - view: text, annotated - select for diffs
Tue Jun 10 19:19:57 2003 UTC (21 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Interface cleanups - 'Update Display' is no more.
"Generate Statistics" and "Generate Chart" buttons now appear below the
selection dialogs, obviating the need for explainatory verbage.
Added a brief instructional messages to the classlist display.
Cleaned up the output of just a table in the single student mode.

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

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