File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.75: download - view: text, annotated - select for diffs
Thu Nov 20 20:21:17 2003 UTC (20 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: version_1_0_99, HEAD
Localization of lonstudentassessment (chart).  And a little bit of the
new spreadsheet error reporting.

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

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