File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.56: download - view: text, annotated - select for diffs
Wed Jun 11 14:41:59 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Add call to lonnet::clear_EXT_cache_status to help us get up to date data.

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

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