File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.166: download - view: text, annotated - select for diffs
Thu Dec 22 00:28:11 2011 UTC (12 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
Better layout of progress bar

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

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