File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.54: download - view: text, annotated - select for diffs
Tue Jun 10 15:42:51 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Portion of Bug 1664:  Chart now shows problem weight * partial credit.
A new selection box 'Output Data' was created to seperate the output
mode (html, excel, csv) from the data being output.
The variable $base indicates the base (tries or scores) for the data
being output.
Modified all major routines (initialize, outputstudent, finish) for
each output method (html, excel, csv) to deal with this new structure.
Excel output of raw scores or tries on each problem part is now allowed!
Created &StudentTriesOnSequence and rewrote &StudentPerformanceOnSequence
to return the tries and scores.

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

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