File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.80: download - view: text, annotated - select for diffs
Tue Jan 27 16:04:27 2004 UTC (20 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Removed reference to non-existant options in error text.  Can go in 1.1.x
without any problems.

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

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