File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.67: download - view: text, annotated - select for diffs
Wed Sep 10 15:06:34 2003 UTC (20 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Fix bug 2167, illegal characters in course names cause crashes when preparing
excel spreadsheets which use the course name as the name of the sheet.
Added Apache::loncommon::clean_excel_name to do the cleanups.

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

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