File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.81.2.3: download - view: text, annotated - select for diffs
Tue Apr 6 21:42:26 2004 UTC (20 years, 3 months ago) by matthew
Branches: version_1_1_X
CVS tags: version_1_1_3
Diff to branchpoint 1.81: preferred, unified
Bug: 2905: Heading missing in excel output of scores summary.

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

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