File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.163: download - view: text, annotated - select for diffs
Sat Dec 4 14:41:13 2010 UTC (13 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Add chart to grading

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

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