File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.150: download - view: text, annotated - select for diffs
Tue Sep 16 13:10:19 2008 UTC (15 years, 9 months ago) by bisitz
Branches: MAIN
CVS tags: version_2_9_X, version_2_8_X, version_2_8_2, version_2_8_1, version_2_8_0, version_2_7_X, version_2_7_99_1, version_2_7_99_0, version_2_7_1, HEAD, GCI_1
Replaced style for summary tables with LON-CAPA standard table styles

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

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