File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.150.2.4: download - view: text, annotated - select for diffs
Fri Feb 12 15:11:08 2010 UTC (14 years, 4 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.150: preferred, unified
- Backport 1.157, 1.160.

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

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