File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.132: download - view: text, annotated - select for diffs
Sun Mar 5 02:00:01 2006 UTC (18 years, 4 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
When * is displayed on the chart, add code to make a pop-up-like thing
appear and show the real value for that cell.

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

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