File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.131: download - view: text, annotated - select for diffs
Mon Feb 27 19:40:30 2006 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- style police

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

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