File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.118: download - view: text, annotated - select for diffs
Fri Mar 11 20:26:32 2005 UTC (19 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 4004: Mis-aligned headings in tries output of chart.
Also minor code cleanups and reduction in debugging spew.

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

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