File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.76: download - view: text, annotated - select for diffs
Fri Dec 5 21:04:34 2003 UTC (20 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Part of Bug 2139: Chart now has a "Grand Total" column output in the
Excel format.  The sums on all the sequences are done with formulas, so
changing a students grade on a resource will propagate to their total on
the sequence and in the course.  Should go in 1.1.

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

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