File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.140: download - view: text, annotated - select for diffs
Tue May 30 12:46:50 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
&Apache::lonnet::unescape -> &unescape
&Apache::lonnet::escape -> &escape

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

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